foldkit-guard 0.10.0 → 0.12.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.
Files changed (36) hide show
  1. package/README.md +157 -85
  2. package/dist/agent.d.mts +9 -6
  3. package/dist/agent.d.mts.map +1 -1
  4. package/dist/agent.mjs +21 -13
  5. package/dist/agent.mjs.map +1 -1
  6. package/dist/{attach-CJl-GtbN.d.mts → attach-CER19mzk.d.mts} +46 -9
  7. package/dist/attach-CER19mzk.d.mts.map +1 -0
  8. package/dist/{attach-CEGlbWu5.mjs → attach-DlrBpxOl.mjs} +33 -3
  9. package/dist/attach-DlrBpxOl.mjs.map +1 -0
  10. package/dist/{condition-dNSbUHzE.mjs → condition-VNIr9gDe.mjs} +2 -4
  11. package/dist/condition-VNIr9gDe.mjs.map +1 -0
  12. package/dist/drizzle.d.mts +1 -1
  13. package/dist/drizzle.mjs +7 -4
  14. package/dist/drizzle.mjs.map +1 -1
  15. package/dist/index.d.mts +1 -1
  16. package/dist/index.mjs +4 -4
  17. package/dist/{may-DprCmMgK.mjs → may-Bd6O91A-.mjs} +62 -20
  18. package/dist/may-Bd6O91A-.mjs.map +1 -0
  19. package/dist/{me-C-gX1paZ.mjs → me-Bv7I0EcH.mjs} +3 -3
  20. package/dist/{me-C-gX1paZ.mjs.map → me-Bv7I0EcH.mjs.map} +1 -1
  21. package/dist/media.d.mts +1 -1
  22. package/dist/{placed-CGyo-NRR.mjs → placed-Dt05PaWi.mjs} +2 -2
  23. package/dist/{placed-CGyo-NRR.mjs.map → placed-Dt05PaWi.mjs.map} +1 -1
  24. package/dist/server.d.mts +9 -2
  25. package/dist/server.d.mts.map +1 -1
  26. package/dist/server.mjs +96 -73
  27. package/dist/server.mjs.map +1 -1
  28. package/dist/sync.d.mts +5 -3
  29. package/dist/sync.d.mts.map +1 -1
  30. package/dist/sync.mjs +10 -6
  31. package/dist/sync.mjs.map +1 -1
  32. package/package.json +16 -16
  33. package/dist/attach-CEGlbWu5.mjs.map +0 -1
  34. package/dist/attach-CJl-GtbN.d.mts.map +0 -1
  35. package/dist/condition-dNSbUHzE.mjs.map +0 -1
  36. package/dist/may-DprCmMgK.mjs.map +0 -1
package/dist/sync.mjs.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"file":"sync.mjs","names":[],"sources":["../src/sync.ts"],"sourcesContent":["/**\n * `foldkit-guard/sync`: a guard set's rules on `foldkit-sync`'s edits to a\n * server-owned Entity. A cell edit is a write to a member of a row, through\n * the journal instead of a Remote mutation, so it answers to the same rules.\n *\n * Writes are checked in two halves, by where each can run. What needs only\n * the principal (`always`, the row's and each member's `Update` principal\n * guards) is the journal's `authorize`, under its lock. What reads the row is\n * the exchange's `admit`, before the journal sees the edit, reading the row\n * through the Entity's guarded Source.\n *\n * Reads are one audience: every replica that opens a document receives every\n * edit committed to it. So a document names its `readers`, who alone may open\n * it, and is refused where it is declared when an edit could carry a value to\n * someone the Entity's Read rules would not show it to.\n */\nimport { Effect, Match, Option, Schema } from 'effect'\nimport type { AnyEntity } from 'foldkit-entity'\nimport type { EntitySource } from 'foldkit-remote-server'\nimport type { AuthorizeDecision, Operation } from 'foldkit-sync'\nimport { attached, isAnyone, restricts, surfaceOf, type Deny } from './attach.js'\nimport { Condition } from './condition.js'\nimport type { Policy, PrincipalGuard } from './index.js'\n\n/** One cell's change, as `foldkit-sync/entity`'s `Change` carries it. */\nexport interface CellChange {\n readonly id: unknown\n readonly member: string\n readonly value: unknown\n}\n\n/** A document of edits to an Entity's members, and who may open it. */\nexport interface GuardedDocument<User> {\n readonly entity: AnyEntity\n readonly members: ReadonlyArray<string>\n readonly readers: ReadonlyArray<PrincipalGuard<User>>\n}\n\nconst refusal = (deny: Deny): AuthorizeDecision =>\n Match.valueTags(deny, {\n Explain: ({ reason }): AuthorizeDecision => ({ allowed: false, reason }),\n Forbidden: () => false,\n NotFound: () => false,\n Omit: () => false,\n Redact: () => false,\n })\n\n/** The first rule of `rules` that does not hold over `values`, as the decision it makes. */\nconst first = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n holds: (condition: Condition) => boolean,\n): AuthorizeDecision =>\n Option.match(Option.fromUndefinedOr(rules.find(({ condition }) => !holds(condition))), {\n onNone: () => true,\n onSome: ({ deny }) => refusal(deny),\n })\n\nconst isNever = (condition: Condition) => condition === Condition.never\n\n/** The schema of `member` when the document edits it: none for a name it does not own. */\nconst memberOf = <User>(\n entity: AnyEntity,\n document: GuardedDocument<User>,\n member: string,\n): Option.Option<Schema.Codec<unknown, unknown>> => {\n const fields = entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>\n // `document` refused a member that is not a field, so one it names is one.\n return document.members.includes(member)\n ? Option.some(fields[member]!.schema as unknown as Schema.Codec<unknown, unknown>)\n : Option.none()\n}\n\nexport const GuardSync = {\n /**\n * A document of edits to `edits.entity`'s `edits.members`, opened by any of\n * `readers`. Refused here, not discovered later: a member that is not a\n * field of the Entity, a member with a Read rule\n * of its own (its value would reach a reader the rule hides it from), a\n * reader the row's Read rule does not name (it would receive edits to rows\n * it cannot read), a guarded row with no readers, and `always` rules that\n * read the row (no reader could be shown to pass them).\n *\n * ```ts\n * const Edits = GuardSync.document(ProductEdits, { readers: [G.isStaff] })\n * ```\n */\n document: <User>(\n edits: { readonly entity: AnyEntity; readonly members: ReadonlyArray<string> },\n options: { readonly readers: ReadonlyArray<PrincipalGuard<User>> },\n ): GuardedDocument<User> => {\n const { entity, members } = edits\n const fail = (why: string): never => {\n throw new Error(`[foldkit-guard] GuardSync.document of ${entity.name}: ${why}`)\n }\n for (const member of members) {\n if (!Object.hasOwn(entity.fields, member)) fail(`${member} is not a field of it`)\n }\n Option.map(attached(entity), attachment => {\n for (const member of members) {\n if (restricts(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })))\n fail(`${member} has a Read rule of its own, and every reader receives every edit`)\n }\n const read = surfaceOf(attachment, { _tag: 'Row', interaction: 'Read' })\n if (Option.isSome(read) && restricts(read)) {\n if (options.readers.length === 0)\n fail('its rows have a Read rule, so the document names its readers')\n for (const reader of options.readers) {\n const named = read.value.rules.some(\n rule =>\n rule._tag === 'PrincipalGuard' &&\n rule.name === reader.name &&\n rule.set === reader.set,\n )\n if (!named) fail(`${reader.name} is not in its rows' Read rule, so may not read them`)\n }\n }\n if (attachment.always.some(rule => rule._tag !== 'PrincipalGuard' && !isAnyone(rule)))\n fail('its `always` rules read the row, which no reader can be shown to pass')\n })\n return Object.freeze({ entity, members, readers: options.readers })\n },\n\n /**\n * Whether `principal` may open the document: any of its readers (anyone,\n * when it names none), and every `always` rule of the Entity. For\n * `journalExchange`'s `opens`.\n */\n opens: <User>(\n policy: Policy<User>,\n document: GuardedDocument<User>,\n principal: Option.Option<User>,\n ): Effect.Effect<boolean> => {\n const always = Option.match(attached(document.entity), {\n onNone: () => [],\n onSome: ({ always }) => always.filter(rule => rule._tag === 'PrincipalGuard'),\n }) as ReadonlyArray<PrincipalGuard<User>>\n const decided = (guards: ReadonlyArray<PrincipalGuard<User>>) =>\n Effect.forEach(guards, guard =>\n Effect.map(policy.decide(guard, { principal, interaction: 'Read' }), d => d === true),\n )\n return Effect.map(\n Effect.all([decided(document.readers), decided(always)]),\n // No readers named: its rows have no Read rule, so it is everyone's.\n ([readers, rules]) =>\n (document.readers.length === 0 || readers.some(Boolean)) && rules.every(Boolean),\n )\n },\n\n /**\n * The journal's `authorize` for a Message of cell edits: refuses one whose\n * row's `Update` or a changed member's `Update` the principal guards settle\n * as refused, with an `explain`'s sentence. It runs under the journal's\n * lock, so it reads no row (`admit` does), and its bodies must not suspend.\n *\n * ```ts\n * authorize: { EditedProducts: GuardSync.authorize(Policy, Edits) }\n * ```\n */\n authorize:\n <User>(policy: Policy<User>, document: GuardedDocument<User>) =>\n (request: {\n readonly principal: Option.Option<User>\n readonly message: { readonly changes: ReadonlyArray<CellChange> }\n }): AuthorizeDecision => {\n const { principal, message } = request\n const row = Effect.runSync(policy.writable(document.entity, principal, 'Update'))\n if (isNever(row.condition)) return refusal(row.deny)\n const members = Effect.runSync(\n policy.writeMembers(\n document.entity,\n principal,\n [...new Set(message.changes.map(change => change.member))],\n 'Update',\n ),\n )\n return first(members, condition => !isNever(condition))\n },\n\n /**\n * The exchange's `admit` for `principal`: each row an operation's edits\n * name is read through `source` (the Entity's guarded Source) and must let\n * the principal update it as it is and as it would be after all of the\n * operation's edits to it. Each changed member's rule must hold over the row\n * as it is, and over the row after with that member's own edit undone: the\n * edit must be allowed given the operation's other edits to the row. A row the\n * principal cannot see is refused, as is an edit to a member outside the\n * document or a value its member cannot encode. `changesOf` reads the edits\n * from an operation; one with none is admitted.\n *\n * The row is read from the table, which takes an edit only once its exchange\n * settles: an edit that changes what a rule reads lets another, admitted\n * before it lands, be judged against the row as it was.\n */\n admit:\n <User, R>(\n policy: Policy<User>,\n document: GuardedDocument<User>,\n options: {\n readonly principal: Option.Option<User>\n readonly source: EntitySource<Option.Option<User>, R>\n readonly changesOf: (operation: Operation) => ReadonlyArray<CellChange>\n },\n ) =>\n (operation: Operation): Effect.Effect<AuthorizeDecision, unknown, R> =>\n Effect.gen(function* () {\n const { principal, source } = options\n const changes = options.changesOf(operation)\n if (changes.length === 0) return true\n const { entity } = document\n // A member is a client's word: only the document's own, by own key.\n const encoded = Option.all(\n changes.map(change =>\n Option.flatMap(memberOf(entity, document, change.member), schema =>\n Option.map(Schema.encodeUnknownOption(schema)(change.value), value => ({\n id: String(change.id),\n member: change.member,\n value,\n })),\n ),\n ),\n )\n if (Option.isNone(encoded)) return false\n const row = yield* policy.writable(entity, principal, 'Update')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n [...new Set(changes.map(change => change.member))],\n 'Update',\n )\n const input = policy.inputOf(principal)\n const fields = [\n ...new Set([\n 'id',\n ...[row, ...members].flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n const holdsOver = (values: Readonly<Record<string, unknown>>) => (condition: Condition) =>\n Condition.holds(condition, values, input, () => false, policy.operators)\n // Every edit to one row is judged together: two may each keep it in reach, and both not.\n const byRow = new Map<string, Record<string, unknown>>()\n for (const { id, member, value } of encoded.value) {\n byRow.set(id, { ...byRow.get(id), [member]: value })\n }\n for (const [id, edits] of byRow) {\n const records = yield* source.read({ ids: [id], fields, principal })\n const current = Option.fromUndefinedOr(records.find(record => record.id === id)?.values)\n if (Option.isNone(current)) return refusal(row.deny)\n const changed = members.filter(({ member }) => Object.hasOwn(edits, member))\n const before = first([row, ...changed], holdsOver(current.value))\n if (before !== true) return before\n const after = { ...current.value, ...edits }\n const moved = first([row], holdsOver(after))\n if (moved !== true) return moved\n // Each member's rule also over the row they leave with its own edit undone: over the\n // row before alone, two edits could set together what each alone may not; over the\n // whole row after, \"only while a draft\" would refuse leaving the draft.\n for (const rule of changed) {\n const given = first(\n [rule],\n holdsOver({ ...after, [rule.member]: current.value[rule.member] }),\n )\n if (given !== true) return given\n }\n }\n return true\n }),\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,WAAW,SACf,MAAM,UAAU,MAAM;CACpB,UAAU,EAAE,cAAiC;EAAE,SAAS;EAAO;CAAO;CACtE,iBAAiB;CACjB,gBAAgB;CAChB,YAAY;CACZ,cAAc;AAChB,CAAC;;AAGH,MAAM,SACJ,OACA,UAEA,OAAO,MAAM,OAAO,gBAAgB,MAAM,MAAM,EAAE,gBAAgB,CAAC,MAAM,SAAS,CAAC,CAAC,GAAG;CACrF,cAAc;CACd,SAAS,EAAE,WAAW,QAAQ,IAAI;AACpC,CAAC;AAEH,MAAM,WAAW,cAAyB,cAAc,UAAU;;AAGlE,MAAM,YACJ,QACA,UACA,WACkD;CAClD,MAAM,SAAS,OAAO;CAEtB,OAAO,SAAS,QAAQ,SAAS,MAAM,IACnC,OAAO,KAAK,OAAO,OAAO,CAAE,MAAmD,IAC/E,OAAO,KAAK;AAClB;AAEA,MAAa,YAAY;;;;;;;;;;;;;;CAcvB,WACE,OACA,YAC0B;EAC1B,MAAM,EAAE,QAAQ,YAAY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AAQ,KAAK,SAAS,QAAQ,MAAM,KAAK;IAAQ,CAAC,CACnE;IACA,IAAI,UAAU,MAAM,OAAO;GAC7B;EACF;EACA,OAAO;CACT,CAAC;AACP"}
1
+ {"version":3,"file":"sync.mjs","names":[],"sources":["../src/sync.ts"],"sourcesContent":["/**\n * `foldkit-guard/sync`: a guard set's rules on `foldkit-sync`'s edits to a\n * server-owned Entity. A cell edit is a write to a member of a row, through\n * the journal instead of a Remote mutation, so it answers to the same rules.\n *\n * Writes are checked in two halves, by where each can run. What needs only\n * the principal (`always`, the row's and each member's `Update` principal\n * guards) is the journal's `authorize`, under its lock. What reads the row is\n * the exchange's `admit`, before the journal sees the edit, reading the row\n * through the Entity's guarded Source.\n *\n * Reads are one audience: every replica that opens a document receives every\n * edit committed to it. So a document names its `readers`, who alone may open\n * it, and is refused where it is declared when an edit could carry a value to\n * someone the Entity's Read rules would not show it to.\n */\nimport { Effect, Match, Option, Schema } from 'effect'\nimport type { AnyEntity } from 'foldkit-entity'\nimport type { EntitySource } from 'foldkit-remote-server'\nimport type { AuthorizeDecision, Operation } from 'foldkit-sync'\nimport { enforced, isAnyone, reachingRules, restricts, surfaceOf, type Deny } from './attach.js'\nimport { Condition } from './condition.js'\nimport type { Policy, PrincipalGuard } from './index.js'\n\n/** One cell's change, as `foldkit-sync/entity`'s `Change` carries it. */\nexport interface CellChange {\n readonly id: unknown\n readonly member: string\n readonly value: unknown\n}\n\n/** A document of edits to an Entity's members, and who may open it. */\nexport interface GuardedDocument<User> {\n readonly entity: AnyEntity\n readonly members: ReadonlyArray<string>\n readonly readers: ReadonlyArray<PrincipalGuard<User>>\n}\n\nconst refusal = (deny: Deny): AuthorizeDecision =>\n Match.valueTags(deny, {\n Explain: ({ reason }): AuthorizeDecision => ({ allowed: false, reason }),\n Forbidden: () => false,\n NotFound: () => false,\n Omit: () => false,\n Redact: () => false,\n })\n\n/** The first rule of `rules` that does not hold over `values`, as the decision it makes. */\nconst first = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n holds: (condition: Condition) => boolean,\n): AuthorizeDecision =>\n Option.match(Option.fromUndefinedOr(rules.find(({ condition }) => !holds(condition))), {\n onNone: () => true,\n onSome: ({ deny }) => refusal(deny),\n })\n\nconst isNever = (condition: Condition) => condition === Condition.never\n\n/** The schema of `member` when the document edits it: none for a name it does not own. */\nconst memberOf = <User>(\n entity: AnyEntity,\n document: GuardedDocument<User>,\n member: string,\n): Option.Option<Schema.Codec<unknown, unknown>> => {\n const fields = entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>\n // `document` refused a member that is not a field, so one it names is one.\n return document.members.includes(member)\n ? Option.some(fields[member]!.schema as unknown as Schema.Codec<unknown, unknown>)\n : Option.none()\n}\n\nexport const GuardSync = {\n /**\n * A document of edits to `edits.entity`'s `edits.members`, opened by any of\n * `readers`. Refused here, not discovered later: a member that is not a\n * field of the Entity, a member with a Read rule\n * of its own (its value would reach a reader the rule hides it from), a\n * reader the row's Read rule does not name (it would receive edits to rows\n * it cannot read), a guarded row with no readers, `always` rules that\n * read the row (no reader could be shown to pass them), and an `Update`\n * rule that reads another row (an edit is admitted over the one row read,\n * by no statement).\n *\n * ```ts\n * const Edits = GuardSync.document(ProductEdits, { readers: [G.isStaff] })\n * ```\n */\n document: <User>(\n edits: { readonly entity: AnyEntity; readonly members: ReadonlyArray<string> },\n options: { readonly readers: ReadonlyArray<PrincipalGuard<User>> },\n ): GuardedDocument<User> => {\n const { entity, members } = edits\n const fail = (why: string): never => {\n throw new Error(`[foldkit-guard] GuardSync.document of ${entity.name}: ${why}`)\n }\n for (const member of members) {\n if (!Object.hasOwn(entity.fields, member)) fail(`${member} is not a field of it`)\n }\n Option.map(enforced(entity), attachment => {\n for (const member of members) {\n if (restricts(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })))\n fail(`${member} has a Read rule of its own, and every reader receives every edit`)\n }\n const read = surfaceOf(attachment, { _tag: 'Row', interaction: 'Read' })\n if (Option.isSome(read) && restricts(read)) {\n if (options.readers.length === 0)\n fail('its rows have a Read rule, so the document names its readers')\n for (const reader of options.readers) {\n const named = read.value.rules.some(\n rule =>\n rule._tag === 'PrincipalGuard' &&\n rule.name === reader.name &&\n rule.set === reader.set,\n )\n if (!named) fail(`${reader.name} is not in its rows' Read rule, so may not read them`)\n }\n }\n if (attachment.always.some(rule => rule._tag !== 'PrincipalGuard' && !isAnyone(rule)))\n fail('its `always` rules read the row, which no reader can be shown to pass')\n // `admit` judges an edit over the one row it reads, and a document runs no statement.\n const reaching = reachingRules(attachment, 'Update')\n if (reaching.length > 0)\n fail(\n `its Update rule's ${reaching.join(', ')} reads another row (a path or an exists), which an edit admitted over the one row read cannot judge; write those members through a declared write and GuardServer.writer over a writer that judges rules in its statement, or rule Update over the row alone`,\n )\n })\n return Object.freeze({ entity, members, readers: options.readers })\n },\n\n /**\n * Whether `principal` may open the document: any of its readers (anyone,\n * when it names none), and every `always` rule of the Entity. For\n * `journalExchange`'s `opens`.\n */\n opens: <User>(\n policy: Policy<User>,\n document: GuardedDocument<User>,\n principal: Option.Option<User>,\n ): Effect.Effect<boolean> => {\n const always = Option.match(enforced(document.entity), {\n onNone: () => [],\n onSome: ({ always }) => always.filter(rule => rule._tag === 'PrincipalGuard'),\n }) as ReadonlyArray<PrincipalGuard<User>>\n const decided = (guards: ReadonlyArray<PrincipalGuard<User>>) =>\n Effect.forEach(guards, guard =>\n Effect.map(policy.decide(guard, { principal, interaction: 'Read' }), d => d === true),\n )\n return Effect.map(\n Effect.all([decided(document.readers), decided(always)]),\n // No readers named: its rows have no Read rule, so it is everyone's.\n ([readers, rules]) =>\n (document.readers.length === 0 || readers.some(Boolean)) && rules.every(Boolean),\n )\n },\n\n /**\n * The journal's `authorize` for a Message of cell edits: refuses one whose\n * row's `Update` or a changed member's `Update` the principal guards settle\n * as refused, with an `explain`'s sentence. It runs under the journal's\n * lock, so it reads no row (`admit` does), and its bodies must not suspend.\n *\n * ```ts\n * authorize: { EditedProducts: GuardSync.authorize(Policy, Edits) }\n * ```\n */\n authorize:\n <User>(policy: Policy<User>, document: GuardedDocument<User>) =>\n (request: {\n readonly principal: Option.Option<User>\n readonly message: { readonly changes: ReadonlyArray<CellChange> }\n }): AuthorizeDecision => {\n const { principal, message } = request\n const row = Effect.runSync(policy.writable(document.entity, principal, 'Update'))\n if (isNever(row.condition)) return refusal(row.deny)\n const members = Effect.runSync(\n policy.writeMembers(\n document.entity,\n principal,\n [...new Set(message.changes.map(change => change.member))],\n 'Update',\n ),\n )\n return first(members, condition => !isNever(condition))\n },\n\n /**\n * The exchange's `admit` for `principal`: each row an operation's edits\n * name is read through `source` (the Entity's guarded Source) and must let\n * the principal update it as it is and as it would be after all of the\n * operation's edits to it. Each changed member's rule must hold over the row\n * as it is, and over the row after with that member's own edit undone: the\n * edit must be allowed given the operation's other edits to the row. A row the\n * principal cannot see is refused, as is an edit to a member outside the\n * document or a value its member cannot encode. `changesOf` reads the edits\n * from an operation; one with none is admitted.\n *\n * The row is read from the table, which takes an edit only once its exchange\n * settles: an edit that changes what a rule reads lets another, admitted\n * before it lands, be judged against the row as it was.\n */\n admit:\n <User, R>(\n policy: Policy<User>,\n document: GuardedDocument<User>,\n options: {\n readonly principal: Option.Option<User>\n readonly source: EntitySource<Option.Option<User>, R>\n readonly changesOf: (operation: Operation) => ReadonlyArray<CellChange>\n },\n ) =>\n (operation: Operation): Effect.Effect<AuthorizeDecision, unknown, R> =>\n Effect.gen(function* () {\n const { principal, source } = options\n const changes = options.changesOf(operation)\n if (changes.length === 0) return true\n const { entity } = document\n // A member is a client's word: only the document's own, by own key.\n const encoded = Option.all(\n changes.map(change =>\n Option.flatMap(memberOf(entity, document, change.member), schema =>\n Option.map(Schema.encodeUnknownOption(schema)(change.value), value => ({\n id: String(change.id),\n member: change.member,\n value,\n })),\n ),\n ),\n )\n if (Option.isNone(encoded)) return false\n const row = yield* policy.writable(entity, principal, 'Update')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n [...new Set(changes.map(change => change.member))],\n 'Update',\n )\n const input = policy.inputOf(principal)\n const fields = [\n ...new Set([\n 'id',\n ...[row, ...members].flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n const holdsOver = (values: Readonly<Record<string, unknown>>) => (condition: Condition) =>\n Condition.holds(condition, values, input, () => false, policy.operators)\n // Every edit to one row is judged together: two may each keep it in reach, and both not.\n const byRow = new Map<string, Record<string, unknown>>()\n for (const { id, member, value } of encoded.value) {\n byRow.set(id, { ...byRow.get(id), [member]: value })\n }\n for (const [id, edits] of byRow) {\n const records = yield* source.read({ ids: [id], fields, principal })\n const current = Option.fromUndefinedOr(records.find(record => record.id === id)?.values)\n if (Option.isNone(current)) return refusal(row.deny)\n const changed = members.filter(({ member }) => Object.hasOwn(edits, member))\n const before = first([row, ...changed], holdsOver(current.value))\n if (before !== true) return before\n const after = { ...current.value, ...edits }\n const moved = first([row], holdsOver(after))\n if (moved !== true) return moved\n // Each member's rule also over the row they leave with its own edit undone: over the\n // row before alone, two edits could set together what each alone may not; over the\n // whole row after, \"only while a draft\" would refuse leaving the draft.\n for (const rule of changed) {\n const given = first(\n [rule],\n holdsOver({ ...after, [rule.member]: current.value[rule.member] }),\n )\n if (given !== true) return given\n }\n }\n return true\n }),\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,WAAW,SACf,MAAM,UAAU,MAAM;CACpB,UAAU,EAAE,cAAiC;EAAE,SAAS;EAAO;CAAO;CACtE,iBAAiB;CACjB,gBAAgB;CAChB,YAAY;CACZ,cAAc;AAChB,CAAC;;AAGH,MAAM,SACJ,OACA,UAEA,OAAO,MAAM,OAAO,gBAAgB,MAAM,MAAM,EAAE,gBAAgB,CAAC,MAAM,SAAS,CAAC,CAAC,GAAG;CACrF,cAAc;CACd,SAAS,EAAE,WAAW,QAAQ,IAAI;AACpC,CAAC;AAEH,MAAM,WAAW,cAAyB,cAAc,UAAU;;AAGlE,MAAM,YACJ,QACA,UACA,WACkD;CAClD,MAA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C,KAAK,GAAG,OAAO,GAAG,UAAU,QAAQ,KAAK,CAAC;GAChE,IAAI,WAAW,MAAM,OAAO;GAC5B,MAAM,QAAQ;IAAE,GAAG,QAAQ;IAAO,GAAG;GAAM;GAC3C,MAAM,QAAQ,MAAM,CAAC,GAAG,GAAG,UAAU,KAAK,CAAC;GAC3C,IAAI,UAAU,MAAM,OAAO;GAI3B,KAAK,MAAM,QAAQ,SAAS;IAC1B,MAAM,QAAQ,MACZ,CAAC,IAAI,GACL,UAAU;KAAE,GAAG;MAAQ,KAAK,SAAS,QAAQ,MAAM,KAAK;IAAQ,CAAC,CACnE;IACA,IAAI,UAAU,MAAM,OAAO;GAC7B;EACF;EACA,OAAO;CACT,CAAC;AACP"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-guard",
3
- "version": "0.10.0",
3
+ "version": "0.12.0",
4
4
  "description": "Who may do what, declared once on a Foldkit Plus domain: principal guards implemented on the server, row guards as query expressions.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -61,17 +61,17 @@
61
61
  "LICENSE"
62
62
  ],
63
63
  "dependencies": {
64
- "foldkit-entity": "0.17.0",
65
- "foldkit-metadata": "0.1.0"
64
+ "foldkit-entity": "0.18.0",
65
+ "foldkit-metadata": "0.2.0"
66
66
  },
67
67
  "peerDependencies": {
68
68
  "drizzle-orm": "1.0.0-rc.5",
69
69
  "effect": "^4.1.0",
70
- "foldkit-media": "^0.7.0",
71
- "foldkit-remote": "^0.25.0",
72
- "foldkit-remote-drizzle": "^0.19.0",
73
- "foldkit-remote-server": "^0.22.0",
74
- "foldkit-sync": "^0.16.0"
70
+ "foldkit-media": "^0.9.0",
71
+ "foldkit-remote-drizzle": "^0.21.0",
72
+ "foldkit-remote-server": "^0.24.0",
73
+ "foldkit-remote": "^0.27.0",
74
+ "foldkit-sync": "^0.18.0"
75
75
  },
76
76
  "peerDependenciesMeta": {
77
77
  "drizzle-orm": {
@@ -96,17 +96,17 @@
96
96
  "devDependencies": {
97
97
  "@electric-sql/pglite": "0.5.11",
98
98
  "drizzle-orm": "1.0.0-rc.5",
99
- "effect": "^4.1.1",
99
+ "effect": "4.1.4",
100
100
  "foldkit": "0.170.0",
101
101
  "tsdown": "^0.23.1",
102
102
  "typescript": "7.0.2",
103
- "foldkit-agent": "0.12.0",
104
- "foldkit-media": "0.7.0",
105
- "foldkit-remote": "0.25.0",
106
- "foldkit-remote-server": "0.22.0",
107
- "foldkit-remote-drizzle": "0.19.0",
108
- "foldkit-sync": "0.16.0",
109
- "foldkit-surface": "0.14.0"
103
+ "foldkit-agent": "0.13.0",
104
+ "foldkit-media": "0.9.0",
105
+ "foldkit-remote-drizzle": "0.21.0",
106
+ "foldkit-remote": "0.27.0",
107
+ "foldkit-remote-server": "0.24.0",
108
+ "foldkit-surface": "0.15.0",
109
+ "foldkit-sync": "0.18.0"
110
110
  },
111
111
  "scripts": {
112
112
  "build": "node ../../scripts/declarations.mjs . && tsdown && node ../../scripts/declared-any.mjs .",
@@ -1 +0,0 @@
1
- {"version":3,"file":"attach-CEGlbWu5.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. */\n/** The rules, each `all` opened into its parts: every guard they ask. */\nexport const flattenRules = (rules: ReadonlyArray<AnyRule>): ReadonlyArray<AnyRule> =>\n rules.flatMap(rule =>\n Match.valueTags(rule, {\n PrincipalGuard: () => [rule],\n RowGuard: () => [rule],\n All: ({ rules: parts }) => flattenRules(parts),\n Inherit: () => [rule],\n }),\n )\n\n/** Every rule attached anywhere: on the row, each member and relation, and always. */\nexport const attachedRules = (attachment: Attachment): ReadonlyArray<AnyRule> =>\n flattenRules([\n ...attachment.always,\n ...[\n attachment.row,\n ...Object.values(attachment.members),\n ...Object.values(attachment.relations),\n ]\n .flatMap(surfaces => Object.values(surfaces))\n .flatMap(surface => surface.rules),\n ])\n\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/**\n * The row surfaces a rule that reads another row may sit on: Read, compiled\n * to SQL, and Update and Delete, judged in the write's own statement. Every\n * other is judged over one row in memory.\n */\nconst reachingSurfaces = new Set(['Read', 'Update', 'Delete'])\n\n/**\n * Throws for a row guard over another Entity that shares the target's name,\n * and, where the surface is judged over one row in memory, for one that reads\n * another row.\n */\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 if (!reachingSurfaces.has(where) && Query.dependencies(guard.query).reaches.length > 0) {\n throw new Error(\n `[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, which reads another row (a path or an exists); only a row's Read rule may (judged in SQL), and its Update and Delete rules (judged in the write's statement), so name those rather than Write`,\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,CA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berKeys","_$__attach_js0.Attach","_$__attach_js0.AnyRule","_$__attach_js0.Inherit","_$__attach_js0.All","_$__attach_js0.Redact","_$__attach_js0.Explain","_$__attach_js0.On"],"sources":["../src/condition.ts","../src/may.ts","../src/me.ts","../src/index.ts","../src/attach.ts"],"mappings":";;KAuBY;WACG;;WACA;;;;WAGA;WACA,OAAO,cAAc;WACrB,SAAS;;;;WAGT;WAA0B;;WAC1B;WAAsB,YAAY,cAAc;;WAChD;WAAqB,YAAY,cAAc;;;cAUxD,MAAG,YAAgB,cAAc,eAAa;;cAY9C,KAAE,YAAgB,cAAc,eAAa;cAWtC;;aA5CQ;;;aACA;;;;;;;;;;;;;;EA4DN,QAAA,WAAA,WAAS,QACZ,SAAS,0BAAwB,OAClC,SAAS,0BAAwB,UAC9B,8BAA4B,WAC3B;;;;;;;;EA2BA,WAAA,WAAA,WAAS,QACZ,SAAS,0BAAwB,OAClC,SAAS,0BAAwB,WAC7B,oBACV;;EAmBkB,UAAA,WAAA,cAAY,OAAO;;;;;;;;;EAkBf,cAAA,WAAA,WAAS,SAAW,cAAY;;;;;;;;;EA2CtC,QAAA,WAAA,WAAS,KAAO,SAAO,MAAQ,UAAQ;;;;;;;EA0BnC,YAAA,WAAA,WAAS,OAAS,wBAAsB;;EAiB1C,UAAA,WAAA,cAAY;;;UAelB;WACN;WACA,WAAW;WACX,MAAM;;;UAyDA;WACN,WAAW;WACX,MAAM;;;;;;;;cC9SJ,WAAS,OAAA;;;;;;;;;KASV,mBAAmB,UAAU;KAEpCA,aAAW,UAAU,oBAAoB,oBAAoB;cA+LrD;;;;;;;EAOX,SAAM,UAAA,WAAA,QAAA,mBAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EAON,MAAG,KAAQ,WAAS,mCAAqC;;;;;;EAQzD,SAAM,KACC,WAAS,mCACqB,mBAClC,OAAO;;EAGV,SAAS,UAAU,WAAS,KAAO,WAAS,SAAW,GAA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WAAW,gBAAgB,gBAAgB,aAAa;;KAGlE,OAAO,MAAM,oBAAoB,UAAU;WAC5C;aACE,OAAO,cAAc,QAAQ,MAAM,KAAK,aAAa,QAAQ,aAAa;aAC1E,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;;aAEtC,QAAQ,UAAU,QAAQ,MAAM,KAAK;;;;;;;;WAQvC;cACG,GAAG,iBAAiB,UAAU,QAAQ,MAAM,KAAK;;;WAGpD,sBACG,KAAK,WAAW;aACf,OAAO,KAAK,QAAQ,MAAM,KAAK,YAAY,OAAO,OAAO,GAAG;;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;;cAoSpB,WAAQ,QAAY,cAAY,OAAO,OAAO"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"condition-dNSbUHzE.mjs","names":[],"sources":["../src/condition.ts"],"sourcesContent":["/**\n * What an attachment's read rules come to for one principal, once its\n * principal guards are decided: a condition over the row, which an\n * interpreter runs (`evaluate` in memory, SQL in a binding). Principal guards\n * never reach it, so their bodies stay on the server that decided them.\n */\nimport { Effect, Match, Option } from 'effect'\nimport {\n Held,\n Judge,\n Query,\n evaluateEach,\n viewerIdOf,\n type AnyEntity,\n type EntityRef,\n type ExprContext,\n type HeldRow,\n type HeldRows,\n type MemoryOperators,\n} from 'foldkit-entity'\nimport { attached, defaultDeny, surfaceOf, type AnyRule, type Deny } from './attach.js'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\nexport type Condition =\n | { readonly _tag: 'Always' }\n | { readonly _tag: 'Never' }\n /** A row guard, and what its `Expr.viewer` reads: the principal it was decided for. */\n | {\n readonly _tag: 'Row'\n readonly guard: RowGuard<any, AnyEntity>\n readonly context: ExprContext\n }\n /** The row its `one` relation points at is readable. */\n | { readonly _tag: 'Inherit'; readonly relation: string }\n | { readonly _tag: 'And'; readonly conditions: ReadonlyArray<Condition> }\n | { readonly _tag: 'Or'; readonly conditions: ReadonlyArray<Condition> }\n\n/** Whether a row guard reads another row: one row cannot judge it. */\nconst reachesOther = (guard: RowGuard<any, AnyEntity>): boolean =>\n Query.dependencies(guard.query).reaches.length > 0\n\nconst always: Condition = Object.freeze({ _tag: 'Always' })\nconst never: Condition = Object.freeze({ _tag: 'Never' })\n\n/** A conjunction, with what it settles already folded away. */\nconst and = (conditions: ReadonlyArray<Condition>): Condition => {\n const kept: Array<Condition> = []\n for (const condition of conditions) {\n if (condition._tag === 'Never') return never\n if (condition._tag !== 'Always') kept.push(condition)\n }\n if (kept.length === 0) return always\n if (kept.length === 1) return kept[0]!\n return Object.freeze({ _tag: 'And', conditions: Object.freeze(kept) })\n}\n\n/** A disjunction, with what it settles already folded away. */\nconst or = (conditions: ReadonlyArray<Condition>): Condition => {\n const kept: Array<Condition> = []\n for (const condition of conditions) {\n if (condition._tag === 'Always') return always\n if (condition._tag !== 'Never') kept.push(condition)\n }\n if (kept.length === 0) return never\n if (kept.length === 1) return kept[0]!\n return Object.freeze({ _tag: 'Or', conditions: Object.freeze(kept) })\n}\n\nexport const Condition = {\n always,\n never,\n and,\n or,\n\n /**\n * Whether a row's stored values meet `condition`, its row guards read with\n * `input` (the principal's, from `G.inputOf`). `inherit` answers whether the\n * row a relation points at is readable, which only the caller can look up.\n * `operators` runs the guards' primitive operators: the policy's.\n *\n * A row guard the row's own values make an operator refuse (text holding a\n * NUL, an implementation that throws) does not hold: what a write supplies\n * can deny it, never end the request.\n */\n holds: (\n condition: Condition,\n values: Readonly<Record<string, unknown>>,\n input: Readonly<Record<string, unknown>>,\n inherit: (relation: string) => boolean,\n operators: MemoryOperators,\n ): boolean => {\n const holds = (each: Condition): boolean =>\n Match.valueTags(each, {\n Always: () => true,\n Never: () => false,\n // A row as a Source reads it holds its links as ref keys; the rule reads ids.\n Row: ({ guard, context }) =>\n evaluateEach(guard.query, input, [Held.fromRefs(guard.query, values)], {\n operators,\n context,\n }).matched.length === 1,\n Inherit: ({ relation }) => inherit(relation),\n And: ({ conditions }) => conditions.every(holds),\n Or: ({ conditions }) => conditions.some(holds),\n })\n return holds(condition)\n },\n\n /**\n * `condition` decided over one row as far as one row can: each row guard\n * over the row alone judged (`holds`), an inherited Read refused, as a\n * writer refuses one, and each row guard that reads another row (a path, an\n * exists) kept for a statement to judge. `Always` or `Never` when the row\n * alone decides it.\n */\n residual: (\n condition: Condition,\n values: Readonly<Record<string, unknown>>,\n input: Readonly<Record<string, unknown>>,\n operators: MemoryOperators,\n ): Condition => {\n const decided = (each: Condition): Condition =>\n Match.valueTags(each, {\n Always: () => each,\n Never: () => each,\n Row: row =>\n reachesOther(row.guard)\n ? each\n : Condition.holds(each, values, input, () => false, operators)\n ? always\n : never,\n Inherit: () => never,\n And: ({ conditions }) => and(conditions.map(decided)),\n Or: ({ conditions }) => or(conditions.map(decided)),\n })\n return decided(condition)\n },\n\n /** `Always` and `Never` as what one row decided; none where a statement must judge the rest. */\n decided: (condition: Condition): Option.Option<boolean> =>\n Match.valueTags(condition, {\n Always: () => Option.some(true),\n Never: () => Option.some(false),\n Row: () => Option.none(),\n Inherit: () => Option.none(),\n And: () => Option.none(),\n Or: () => Option.none(),\n }),\n\n /**\n * The members of `written`, the row a write changes, that a condition's\n * guards reading another row start from: each one's fields, the relation\n * each path leaves by, and, where `written` is the viewer's own row, what a\n * path from the viewer leaves it by. A write that changes one would need the\n * guard judged over the row it leaves, which a statement over the stored row\n * does not do.\n */\n reachedFrom: (condition: Condition, written: EntityRef): ReadonlyArray<string> => {\n const read = (each: Condition): ReadonlyArray<string> =>\n Match.valueTags(each, {\n Always: () => [],\n Never: () => [],\n Row: ({ guard, context }) => {\n if (!reachesOther(guard)) return []\n const dependencies = Query.dependencies(guard.query)\n return [\n ...dependencies.predicate.map(field => field.key),\n // An exists reached through a path leaves by its first relation as surely\n // as a path does; one over the row itself reads only its id. A path from the\n // viewer leaves the row written the same way when that row is the viewer's.\n ...dependencies.reaches.flatMap(reach =>\n Match.valueTags(reach, {\n Path: ({ via }) => [via[0]!.key],\n Exists: ({ via }) => via.slice(0, 1).map(relation => relation.key),\n ViewerPath: ({ viewer, via, field }) => {\n const start = viewer.target()\n return start.name === written.entity &&\n Option.exists(viewerIdOf(start, context), id => id === written.id)\n ? [via[0]?.key ?? field.key]\n : []\n },\n }),\n ),\n ]\n },\n Inherit: () => [],\n And: ({ conditions }) => conditions.flatMap(read),\n Or: ({ conditions }) => conditions.flatMap(read),\n })\n return [...new Set(read(condition))]\n },\n\n /**\n * Whether a row a client holds meets `condition`, a part it cannot decide\n * taken to be `assumed`: a row guard over the principal's fields, which a\n * client is not given, an inherited Read, and a rule over a row or field\n * the holder lacks. A row guard reads the holder's rows (`rows`) where it\n * follows a path from the viewer. Run once assuming each way, it is decided\n * where both agree, since no part of a condition is negated.\n */\n judge: (condition: Condition, row: HeldRow, rows: HeldRows, assumed: boolean): boolean => {\n const judge = (each: Condition): boolean =>\n Match.valueTags(each, {\n Always: () => true,\n Never: () => false,\n Row: ({ guard, context }) =>\n readsPrincipal(guard)\n ? assumed\n : Judge.match(Judge.predicate(guard.body, row, { context, rows }), {\n // SQL's null leaves a row out, as false does.\n onKnown: truth => truth === true,\n onUnknown: () => assumed,\n }),\n Inherit: () => assumed,\n And: ({ conditions }) => conditions.every(judge),\n Or: ({ conditions }) => conditions.some(judge),\n })\n return judge(condition)\n },\n\n /**\n * `condition` with every row guard that reads one of `unset`, and every\n * relation of them it follows, refused: a field a create leaves unset\n * matches no guard, `isNull` and `isNotNull` alike, since the create never\n * said what it holds.\n */\n unsetting: (condition: Condition, unset: ReadonlySet<string>): Condition => {\n const kept = (each: Condition): Condition =>\n Match.valueTags(each, {\n Always: () => each,\n Never: () => each,\n Row: ({ guard }) =>\n Query.dependencies(guard.query).predicate.some(field => unset.has(field.key))\n ? never\n : each,\n Inherit: ({ relation }) => (unset.has(relation) ? never : each),\n And: ({ conditions }) => and(conditions.map(kept)),\n Or: ({ conditions }) => or(conditions.map(kept)),\n })\n return kept(condition)\n },\n\n /** The members a condition reads: its row guards' fields, and each relation it follows. */\n members: (condition: Condition): ReadonlyArray<string> => {\n const read = (each: Condition): ReadonlyArray<string> =>\n Match.valueTags(each, {\n Always: () => [],\n Never: () => [],\n Row: ({ guard }) => Query.dependencies(guard.query).predicate.map(field => field.key),\n Inherit: ({ relation }) => [relation],\n And: ({ conditions }) => conditions.flatMap(read),\n Or: ({ conditions }) => conditions.flatMap(read),\n })\n return [...new Set(read(condition))]\n },\n}\n\n/** A member's read rule for one principal: the condition, and what a refusal shows. */\nexport interface MemberRead {\n readonly member: string\n readonly condition: Condition\n readonly deny: Deny\n}\n\n/**\n * Whether a row guard reads the principal's fields. A visitor has none, so\n * passes no guard that does; one over the row alone (`publishedAt` is set)\n * holds for a visitor as for anyone.\n */\nexport const readsPrincipal = (guard: RowGuard<any, AnyEntity>): boolean =>\n Query.dependencies(guard.query).inputs.length > 0\n\n/** Every principal guard the rules name, each once. */\nconst principalGuardsIn = (rules: ReadonlyArray<AnyRule>): ReadonlyArray<PrincipalGuard<any>> => {\n const found = new Map<string, PrincipalGuard<any>>()\n const visit = (rule: AnyRule): void =>\n Match.valueTags(rule, {\n PrincipalGuard: guard => void found.set(guard.name, guard),\n RowGuard: () => {},\n All: ({ rules }) => rules.forEach(visit),\n Inherit: () => {},\n })\n rules.forEach(visit)\n return [...found.values()]\n}\n\n/**\n * Turns `rules` into a condition for one principal. Each principal guard is\n * decided once, however many rules name it; a visitor passes no row guard\n * that reads the principal.\n */\nconst conditionsFor = <R>(\n rules: ReadonlyArray<AnyRule>,\n decide: (guard: PrincipalGuard<any>) => Effect.Effect<boolean, never, R>,\n visitor: boolean,\n context: ExprContext,\n): Effect.Effect<(rules: ReadonlyArray<AnyRule>, join: typeof and) => Condition, never, R> =>\n Effect.map(\n Effect.forEach(principalGuardsIn(rules), guard =>\n Effect.map(decide(guard), allowed => [guard.name, allowed] as const),\n ),\n decisions => {\n const allowed = new Map(decisions)\n const conditionOf = (rule: AnyRule): Condition =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => (allowed.get(name) === true ? always : never),\n RowGuard: guard =>\n visitor && readsPrincipal(guard)\n ? never\n : Object.freeze({ _tag: 'Row' as const, guard, context }),\n All: ({ rules }) => and(rules.map(conditionOf)),\n Inherit: ({ relation }) => Object.freeze({ _tag: 'Inherit' as const, relation }),\n })\n return (rules, join) => join(rules.map(conditionOf))\n },\n )\n\n/** A row's rule for one interaction and principal: the condition, and what a refusal shows. */\nexport interface RowRule {\n readonly condition: Condition\n readonly deny: Deny\n}\n\n/**\n * How a Policy decides one interaction, given the set's principal guards as\n * decided for it.\n */\nexport const deciding = <R>(\n decide: (guard: PrincipalGuard<any>) => Effect.Effect<boolean, never, R>,\n visitor: boolean,\n interaction: string,\n context: ExprContext,\n) => ({\n /** Who may do it to which rows of `entity`: `always`, then the row's rules for it. */\n row: (entity: AnyEntity): Effect.Effect<RowRule, never, R> =>\n Option.match(attached(entity), {\n onNone: () =>\n Effect.succeed({ condition: always, deny: defaultDeny(rowTarget(interaction)) }),\n onSome: attachment => {\n const target = rowTarget(interaction)\n const row = surfaceOf(attachment, target)\n const rules = Option.match(row, {\n onNone: (): ReadonlyArray<AnyRule> => [],\n onSome: ({ rules }) => rules,\n })\n // An interaction left without rules falls to the set's default.\n const unguarded = attachment.unguarded === 'allow' ? always : never\n return Effect.map(\n conditionsFor([...attachment.always, ...rules], decide, visitor, context),\n condition => ({\n condition: and([\n condition(attachment.always, and),\n Option.isSome(row) ? condition(rules, or) : unguarded,\n ]),\n deny: Option.getOrElse(\n Option.flatMap(row, ({ deny }) => deny),\n () => defaultDeny(target),\n ),\n }),\n )\n },\n }),\n\n /**\n * The rule of each of `members` that has one for this interaction. One\n * without follows its row. A relation key's Read is its relation's, decided\n * over the parent row as a member's is.\n */\n members: (\n entity: AnyEntity,\n members: ReadonlyArray<string>,\n ): Effect.Effect<ReadonlyArray<MemberRead>, never, R> =>\n Option.match(attached(entity), {\n onNone: () => Effect.succeed([]),\n onSome: attachment => {\n const surfaces = members.flatMap(member => {\n const target = Object.hasOwn(entity.relations, member)\n ? ({ _tag: 'Relation', relation: member, interaction } as const)\n : ({ _tag: 'Member', member, interaction } as const)\n return Option.match(surfaceOf(attachment, target), {\n onNone: () => [],\n onSome: ({ rules, deny }) => [\n { member, rules, deny: Option.getOrElse(deny, () => defaultDeny(target)) },\n ],\n })\n })\n return Effect.map(\n conditionsFor(\n surfaces.flatMap(({ rules }) => rules),\n decide,\n visitor,\n context,\n ),\n condition =>\n surfaces.map(({ member, rules, deny }) => ({\n member,\n condition: condition(rules, or),\n deny,\n })),\n )\n },\n }),\n\n /** A relation's rule for this interaction (`Link`, `Unlink`), when it has one. */\n relation: (\n entity: AnyEntity,\n relation: string,\n ): Effect.Effect<Option.Option<RowRule>, never, R> => {\n const target = { _tag: 'Relation', relation, interaction } as const\n return Option.match(\n Option.flatMap(attached(entity), attachment => surfaceOf(attachment, target)),\n {\n onNone: () => Effect.succeed(Option.none()),\n onSome: ({ rules, deny }) =>\n Effect.map(conditionsFor(rules, decide, visitor, context), condition =>\n Option.some({\n condition: condition(rules, or),\n deny: Option.getOrElse(deny, () => defaultDeny(target)),\n }),\n ),\n },\n )\n },\n})\n\nconst rowTarget = (interaction: string) => ({ _tag: 'Row', interaction }) as const\n"],"mappings":";;;;;;;;;;;AAsCA,MAAM,gBAAgB,UAC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MAAM,GAAG;KACjD,cAAc,CAAC;KACf,SAAS,EAAE,OAAO,WAAW,CAC3B;MAAE;MAAQ;MAAO,MAAM,OAAO,UAAU,YAAY,YAAY,MAAM,CAAC;KAAE,CAC3E;IACF,CAAC;GACH,CAAC;GACD,OAAO,OAAO,IACZ,cACE,SAAS,SAAS,EAAE,YAAY,KAAK,GACrC,QACA,SACA,OACF,IACA,cACE,SAAS,KAAK,EAAE,QAAQ,OAAO,YAAY;IACzC;IACA,WAAW,UAAU,OAAO,EAAE;IAC9B;GACF,EAAE,CACN;EACF;CACF,CAAC;;CAGH,WACE,QACA,aACoD;EACpD,MAAM,SAAS;GAAE,MAAM;GAAY;GAAU;EAAY;EACzD,OAAO,OAAO,MACZ,OAAO,QAAQ,SAAS,MAAM,IAAG,eAAc,UAAU,YAAY,MAAM,CAAC,GAC5E;GACE,cAAc,OAAO,QAAQ,OAAO,KAAK,CAAC;GAC1C,SAAS,EAAE,OAAO,WAChB,OAAO,IAAI,cAAc,OAAO,QAAQ,SAAS,OAAO,IAAG,cACzD,OAAO,KAAK;IACV,WAAW,UAAU,OAAO,EAAE;IAC9B,MAAM,OAAO,UAAU,YAAY,YAAY,MAAM,CAAC;GACxD,CAAC,CACH;EACJ,CACF;CACF;AACF;AAEA,MAAM,aAAa,iBAAyB;CAAE,MAAM;CAAO;AAAY"}
@@ -1 +0,0 @@
1
- {"version":3,"file":"may-DprCmMgK.mjs","names":[],"sources":["../src/may.ts"],"sourcesContent":["/**\n * `may`: what a principal may do with a row, as a derived member the client\n * reads like any other. The server answers it for the row as it was read; a\n * client foresees it for a row it writes, from the same rules, where they\n * decide it whatever it does not know. Either way it is a hint for a\n * greyed-out button, never the check: the write is checked again when made.\n */\nimport { Effect, Match, Option, Record, Schema } from 'effect'\nimport { Derived, Entity, type AnyEntity, type Forbids, type Predict } from 'foldkit-entity'\nimport { attached, type InteractionKey } from './attach.js'\nimport { Condition, deciding, type MemberRead, type RowRule } from './condition.js'\n\n/**\n * The answer: per row interaction (`Update`, `Delete`, and each one the\n * application named), per member with its own `Update` rule, and per relation\n * with a `Link` or `Unlink` rule; and, for a row interaction refused with an\n * `explain`, its sentence.\n */\nexport const MaySchema = Schema.Struct({\n row: Schema.Record(Schema.String, Schema.Boolean),\n reasons: Schema.Record(Schema.String, Schema.String),\n members: Schema.Record(Schema.String, Schema.Boolean),\n relations: Schema.Record(\n Schema.String,\n Schema.Struct({ Link: Schema.Boolean, Unlink: Schema.Boolean }),\n ),\n})\nexport type MayAnswer = typeof MaySchema.Type\n\ntype MemberKeys<E extends AnyEntity> = (keyof E['fields'] | keyof E['derived']) & string\n\nconst can = (may: MayAnswer, interaction: string): boolean => may.row[interaction] === true\n\n/** The row's `Update`, and the member's own rule when it has one. */\nconst setting = (may: MayAnswer, member: string): boolean =>\n can(may, 'Update') && (!Object.hasOwn(may.members, member) || may.members[member] === true)\n\n/** The row's `Update`, and the relation's own rule for the direction when it has one. */\nconst linking = (may: MayAnswer, relation: string, interaction: 'Link' | 'Unlink'): boolean =>\n can(may, 'Update') &&\n (!Object.hasOwn(may.relations, relation) || may.relations[relation]![interaction])\n\nconst isMay = Schema.is(MaySchema)\nconst sameMay = Schema.toEquivalence(MaySchema)\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 * What `may` asks, for one principal: each row interaction's rule, each\n * member's own `Update`, each relation's `Link` and `Unlink`.\n */\nexport interface MayRules {\n readonly rows: ReadonlyArray<readonly [string, RowRule]>\n readonly members: ReadonlyArray<MemberRead>\n readonly relations: ReadonlyArray<{\n readonly relation: string\n readonly link: Option.Option<RowRule>\n readonly unlink: Option.Option<RowRule>\n }>\n}\n\n/** How one side decides a rule for its principal: a Policy's bodies, or a client's assumption. */\nexport interface MayAsk<R> {\n readonly row: (interaction: string) => Effect.Effect<RowRule, never, R>\n readonly members: (\n members: ReadonlyArray<string>,\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n readonly relation: (\n relation: string,\n interaction: 'Link' | 'Unlink',\n ) => Effect.Effect<Option.Option<RowRule>, never, R>\n}\n\n/** The rules `may` answers for `entity`, each decided by `ask`. */\nexport const mayRules = <R>(\n entity: AnyEntity,\n ask: MayAsk<R>,\n): Effect.Effect<MayRules, 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(ask.row(interaction), rule => [interaction, rule] as const),\n ),\n ask.members(ruledMembers),\n Effect.forEach(ruledRelations, relation =>\n Effect.map(\n Effect.all([ask.relation(relation, 'Link'), ask.relation(relation, 'Unlink')]),\n ([link, unlink]) => ({ relation, link, unlink }),\n ),\n ),\n ]),\n ([rows, members, relations]) => ({ rows, members, relations }),\n )\n}\n\n/** Every condition the rules hold a row to. */\nexport const mayConditions = (rules: MayRules): ReadonlyArray<Condition> => [\n ...rules.rows.map(([, { condition }]) => condition),\n ...rules.members.map(({ condition }) => condition),\n ...rules.relations.flatMap(({ link, unlink }) =>\n [...Option.toArray(link), ...Option.toArray(unlink)].map(({ condition }) => condition),\n ),\n]\n\n/**\n * The answer over one row, each condition decided by `decide`. A row\n * interaction it cannot decide over one row (a rule reading another row,\n * which the write's statement judges) is left out, and so refuses nothing.\n */\nexport const answerOf = (\n rules: MayRules,\n decide: (condition: Condition) => Option.Option<boolean>,\n): MayAnswer => {\n // Member and relation rules never read another row (`Guards.attach` refuses one).\n const holds = (condition: Condition) => Option.getOrElse(decide(condition), () => false)\n // A relation without a rule for one direction leaves it to the row's Update.\n const allows = (rule: Option.Option<RowRule>) =>\n Option.match(rule, { onNone: () => true, onSome: ({ condition }) => holds(condition) })\n const decided = rules.rows.flatMap(([interaction, rule]) =>\n Option.match(decide(rule.condition), {\n onNone: () => [],\n onSome: answer => [{ interaction, rule, answer }],\n }),\n )\n return {\n row: Object.fromEntries(decided.map(({ interaction, answer }) => [interaction, answer])),\n // Only an `explain`'s sentence is for whoever asked.\n reasons: Object.fromEntries(\n decided.flatMap(({ interaction, rule: { deny }, answer }) =>\n answer\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 rules.members.map(({ member, condition }) => [member, holds(condition)]),\n ),\n relations: Object.fromEntries(\n rules.relations.map(({ relation, link, unlink }) => [\n relation,\n { Link: allows(link), Unlink: allows(unlink) },\n ]),\n ),\n }\n}\n\n/**\n * `may` foreseen for a row the client writes. A principal guard's body is\n * the server's, and the principal's fields are not the client's to know, so\n * each is unknown, as is a rule over a row or field the store lacks. Every\n * rule is a conjunction and disjunction of its parts, so it is decided when\n * it comes out the same with every unknown part taken to hold and taken not\n * to: the answer is foreseen only when the whole of it is.\n */\nconst predict: Predict = ({ entity, row, rows, context }) => {\n // Never a visitor here: a client without a viewer may be one that was not told it.\n const answerAssuming = (assumed: boolean): MayAnswer => {\n const decide = (interaction: string) =>\n deciding(() => Effect.succeed(assumed), false, interaction, context)\n const rules = Effect.runSync(\n mayRules(entity, {\n row: interaction => decide(interaction).row(entity),\n members: members => decide('Update').members(entity, members),\n relation: (relation, interaction) => decide(interaction).relation(entity, relation),\n }),\n )\n return answerOf(rules, condition => Option.some(Condition.judge(condition, row, rows, assumed)))\n }\n const held = answerAssuming(true)\n return sameMay(held, answerAssuming(false)) ? Option.some(held) : Option.none()\n}\n\n/** Whether `answer` names `key`, and says no to it. */\nconst refuses = (answer: Readonly<Record<string, boolean>>, key: string): boolean =>\n Object.hasOwn(answer, key) && answer[key] === false\n\n/**\n * The write a held `may` refuses, as the server would: the row's `Update` or\n * `Delete`, a written member's own `Update`, a relation's `Link` or `Unlink`,\n * each judged over the row as read, where the answer says `false`. What it\n * does not name refuses nothing, and neither does a value that is no answer.\n */\nconst forbids: Forbids = (value, surface) => {\n if (!isMay(value)) return Option.none()\n // Only a row interaction's refusal carries the `explain` the server would give.\n if (refuses(value.row, surface.kind)) {\n return Option.some({\n reason: Option.fromUndefinedOr(\n Object.hasOwn(value.reasons, surface.kind) ? value.reasons[surface.kind] : undefined,\n ),\n })\n }\n const member = surface.members.some(key => refuses(value.members, key))\n const relation = surface.relations.some(\n ({ relation, interaction }) =>\n Object.hasOwn(value.relations, relation) && !value.relations[relation]![interaction],\n )\n return member || relation ? Option.some({ reason: Option.none() }) : Option.none()\n}\n\nexport const May = {\n /**\n * Adds the `may` member to an Entity, after its guards are attached:\n * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`. Select it as any\n * member (`may: true`); `GuardServer.filter` answers it. A client holding it\n * refuses, where it is made, a write it says no to (`Forbidden`).\n */\n member: Entity.derived({ may: Derived.make(MaySchema, { predict, forbids }) }),\n\n /**\n * Whether the row's rule for `interaction` let the principal, when it was\n * read. An interaction the answer does not name was not ruled where the row\n * was read, and reads `false`: a hint errs on the side of asking.\n */\n can: (may: MayAnswer, interaction: 'Update' | 'Delete' | InteractionKey): boolean =>\n can(may, interaction),\n\n /**\n * Why the row's rule for `interaction` refused, when it was refused with an\n * `explain`: words for whoever asked. None where it was allowed (the server\n * gives none then), or refused without one.\n */\n reason: (\n may: MayAnswer,\n interaction: 'Update' | 'Delete' | InteractionKey,\n ): Option.Option<string> => Record.get(may.reasons, interaction),\n\n /** Whether the principal may set `member` on this row: the row's `Update`, and the member's own rule. */\n canSet: <E extends AnyEntity>(may: MayAnswer, _entity: E, member: MemberKeys<E>): boolean =>\n setting(may, member),\n\n /** Whether the principal may point `relation` at a row, or away from one. */\n canLink: <E extends AnyEntity>(\n may: MayAnswer,\n _entity: E,\n relation: keyof E['relations'] & string,\n interaction: 'Link' | 'Unlink',\n ): boolean => linking(may, relation, interaction),\n\n /**\n * `foldkit-crud`'s `locks` for `entity`: an editor loads `may` beside the\n * form's members and locks each the reader may not set. A relation is locked\n * unless it may be both unlinked and linked. Nothing is locked while `may`\n * is not answered (a Source without the filter): the write is checked anyway.\n *\n * ```ts\n * Crud.editor('todo', { form, mutation: EditTodo, locks: May.locks(Todo) })\n * ```\n */\n locks: (entity: AnyEntity) => ({\n select: { may: true } as const,\n locked: (row: Readonly<Record<string, unknown>>, member: string): boolean => {\n const may = row.may\n if (!isMay(may)) return false\n return Object.hasOwn(entity.relations, member)\n ? !(linking(may, member, 'Unlink') && linking(may, member, 'Link'))\n : !setting(may, member)\n },\n }),\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAkBA,MAAa,YAAY,OAAO,OAAO;CACrC,KAAK,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;CAChD,SAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,MAAM;CACnD,SAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;CACpD,WAAW,OAAO,OAChB,OAAO,QACP,OAAO,OAAO;EAAE,MAAM,OAAO;EAAS,QAAQ,OAAO;CAAQ,CAAC,CAChE;AACF,CAAC;AAKD,MAAM,OAAO,KAAgB,gBAAiC,IAAI,IAAI,iBAAiB;;AAGvF,MAAM,WAAW,KAAgB,WAC/B,IAAI,KAAK,QAAQ,MAAM,CAAC,OAAO,OAAO,IAAI,SAAS,MAAM,KAAK,IAAI,QAAQ,YAAY;;AAGxF,MAAM,WAAW,KAAgB,UAAkB,gBACjD,IAAI,KAAK,QAAQ,MAChB,CAAC,OAAO,OAAO,IAAI,WAAW,QAAQ,KAAK,IAAI,UAAU,SAAS,CAAE;AAEvE,MAAM,QAAQ,OAAO,GAAG,SAAS;AACjC,MAAM,UAAU,OAAO,cAAc,SAAS;;AAG9C,MAAM,6BAAa,IAAI,IAAI;CAAC;CAAQ;CAAU;C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