foldkit-guard 0.11.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
@@ -1 +1 @@
1
- {"version":3,"file":"server.mjs","names":[],"sources":["../src/diagnostics.ts","../src/server.ts"],"sourcesContent":["/**\n * What a guarded server meets and answers past: a computed value an operator\n * refused, answered with a fixed message, and writes `GuardServer.validate`\n * finds unpinned. Each is reported through `Diagnostics.report`.\n */\nimport type { Diagnostic } from 'foldkit-remote'\n\nconst source = 'foldkit-guard'\n\n/**\n * An operator refused to work out a value a guarded write computes (text\n * holding NUL, an implementation that throws). The write was refused with a\n * fixed message, since the operator's own may say anything.\n */\nexport interface ComputeRefused extends Diagnostic {\n readonly _tag: 'ComputeRefused'\n readonly entity: string\n /** The operator's own refusal. */\n readonly error: Error\n}\n\n/**\n * Writes through a `GuardServer.writer` given no revision, where a change can\n * come between the check and the write, which is then not seen.\n */\nexport interface UnpinnedWrites extends Diagnostic {\n readonly _tag: 'UnpinnedWrites'\n readonly mutations: ReadonlyArray<string>\n}\n\n/** Every diagnostic `foldkit-guard` reports. */\nexport type GuardDiagnostic = ComputeRefused | UnpinnedWrites\n\nexport const computeRefused = (entity: string, error: Error): ComputeRefused => ({\n _tag: 'ComputeRefused',\n source,\n level: 'error',\n message: `${entity}'s write was refused: a value it computes could not be worked out (${error.message})`,\n entity,\n error,\n})\n\nexport const unpinnedWrites = (mutations: ReadonlyArray<string>): UnpinnedWrites => ({\n _tag: 'UnpinnedWrites',\n source,\n level: 'warning',\n message: `GuardServer.validate: ${mutations.join(', ')} ${mutations.length === 1 ? 'writes' : 'write'} through a GuardServer.writer with no revision, so a change between its check and its write is not seen; pass { revision }`,\n mutations,\n})\n","/**\n * A guard set's read rules as `foldkit-remote-server`'s seams: an\n * `EntitySource.filter` from each member's Read rule, and `RemoteServer.memory`'s\n * `readable` and `filter` from the row's, and a check at startup that a server\n * applies them. A subpath, so the shared declaration the browser imports never\n * brings the server along.\n */\nimport { Effect, Match, Option, Schema, SchemaAST, identity } from 'effect'\nimport {\n Entity,\n Expr,\n Query,\n QueryEvaluateError,\n Write,\n dependenciesOf,\n supported,\n type AnyEntity,\n type AnyQuery,\n} from 'foldkit-entity'\nimport {\n Diagnostics,\n RemoteForbidden,\n type MutationDescriptor,\n type RemoteUnauthenticated,\n type ReportDiagnostic,\n} from 'foldkit-remote'\nimport {\n RemoteInvalid,\n RemoteServer,\n DeleteOutcome,\n RemoteServerError,\n RowRequirement,\n type EntityRecord,\n type EntitySource,\n type EntityWriter,\n type MutationOutcome,\n type MutationRefused,\n type MutationSource,\n type MemoryReadable,\n type ReadPlan,\n type ServerDefinition,\n type CascadeRequirement,\n type WriteRequirement,\n type WriteWhen,\n} from 'foldkit-remote-server'\nimport {\n attached,\n attachedRules,\n readRowsRuled,\n readRuled,\n surfaceOf,\n type Attachment,\n type Deny,\n type InteractionKey,\n} from './attach.js'\nimport { Condition, type MemberRead, type RowRule } from './condition.js'\nimport type { Policy } from './index.js'\nimport { answerOf, mayConditions, mayRules, type MayAnswer } from './may.js'\nimport { ME, type MeEntity } from './me.js'\nimport { memberRules, rowRules, writeRules } from './placed.js'\nimport { computeRefused, unpinnedWrites } from './diagnostics.js'\n\nexport type { ComputeRefused, GuardDiagnostic, UnpinnedWrites } from './diagnostics.js'\n\nconst noMembers = (record: EntityRecord) => record\n\n/** Two stored values, which are JSON: equal when they encode the same. */\nconst sameStored = (left: unknown, right: unknown): boolean =>\n JSON.stringify(left) === JSON.stringify(right)\n\n/** The members of `fields` that have a Read rule, once each. */\nconst hiddenOf = (\n attachment: Attachment,\n fields: ReadonlyArray<{ readonly key: string }>,\n): ReadonlyArray<string> => [\n ...new Set(fields.map(field => field.key).filter(key => readRuled(attachment, key))),\n]\n\n/** A member of a row a body reaches: the Entity it belongs to, by name, and its key. */\ninterface ReachedMember {\n readonly entity: string\n readonly key: string\n}\n\n/**\n * Each member a body reads on a row it reaches rather than judges: every\n * relation a path, a path from the viewer or an exists follows, the field a\n * path ends at, and an exists' pointing relation and filter. SQL reads such a\n * row under its `visible` rule alone, never its members'.\n */\nconst reachedMembers = (\n reaches: ReturnType<typeof dependenciesOf>['reaches'],\n): ReadonlyArray<ReachedMember> =>\n reaches.flatMap(reached => {\n const via = reached.via.map(relation => ({ entity: relation.owner.name, key: relation.key }))\n return Match.valueTags(reached, {\n Path: ({ field }) => [...via, { entity: field.owner.name, key: field.key }],\n ViewerPath: ({ field }) => [...via, { entity: field.owner.name, key: field.key }],\n Exists: ({ relation, where }) => {\n const filter = Option.match(where, {\n onNone: () => [],\n onSome: body => {\n const read = dependenciesOf(body)\n return [\n ...read.fields.map(field => ({ entity: field.entity, key: field.key })),\n ...reachedMembers(read.reaches),\n ]\n },\n })\n return [...via, { entity: relation.owner.name, key: relation.key }, ...filter]\n },\n })\n })\n\n/** Each guarded writer's `revision`, or none: one a change can fall between check and write of. */\nconst pins = new WeakMap<object, Option.Option<string>>()\n\n/** A ref key's two halves, `Entity:id`; `none` for anything else. */\nconst refOf = (value: unknown): Option.Option<{ readonly entity: string; readonly id: string }> => {\n if (typeof value !== 'string') return Option.none()\n const split = value.indexOf(':')\n return split <= 0\n ? Option.none()\n : Option.some({ entity: value.slice(0, split), id: value.slice(split + 1) })\n}\n\nexport const GuardServer = {\n /**\n * `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`\n * answered by `policy`. `signedIn` is whether the server answered as\n * someone; `key` is their `key`. Any other id is no row.\n *\n * ```ts\n * RemoteServer.make({ entities: [GuardServer.me(Me, Policy), …] })\n * ```\n */\n me: <User, R>(\n entity: MeEntity,\n policy: Policy<User, R>,\n ): EntitySource<Option.Option<User>, R> => {\n // Otherwise every read would die deciding another set's guards.\n Option.map(attached(entity), ({ set }) => {\n if (set !== policy.set) {\n throw new Error(\n `[foldkit-guard] GuardServer.me: Me carries the guards of ${set}, not ${policy.set}`,\n )\n }\n })\n return {\n ...RemoteServer.entity<Option.Option<User>, R>(entity, {\n read: ({ ids, principal }) =>\n Effect.succeed(\n ids\n .filter(id => id === ME)\n .map(id => ({\n id,\n values: {\n signedIn: Option.isSome(principal),\n // Encoded, as a Source answers: `null` for a visitor.\n key: Option.match(principal, {\n onNone: () => null,\n onSome: policy.key,\n }),\n },\n })),\n ),\n filter: GuardServer.filter(entity, policy),\n }),\n // Its Read rule as this Source applies it: only the asker's own row,\n // which `Guards.me` lets anyone read. One per call: the registry is keyed\n // by it, and another call is for another Policy.\n visible: rowRules.add(Object.freeze({ reads: 'the asker’s own row' }), policy, [entity]),\n }\n },\n\n /**\n * An `EntitySource.filter` for `entity`: each requested member with a Read\n * rule is decided per record, omitted or redacted where the rule refuses.\n * The fields a rule reads are read too, so it can be decided.\n *\n * ```ts\n * RemoteServer.entity(Todo, { read, filter: GuardServer.filter(Todo, Policy) })\n * ```\n */\n filter: <User, R>(entity: AnyEntity, policy: Policy<User, R>) =>\n memberRules.add(\n (\n principal: Option.Option<User>,\n fields: readonly string[],\n ): Effect.Effect<ReadPlan, never, R> =>\n Effect.map(\n Effect.all([\n policy.readMembers(entity, principal, fields),\n // `may` is answered here, where the row is read as its principal sees it.\n asksMay(entity, fields)\n ? Effect.map(mayOf(entity, policy, principal), Option.some)\n : Effect.succeed(Option.none<MayPlan>()),\n ]),\n ([members, may]): ReadPlan => {\n if (members.length === 0 && Option.isNone(may)) return { fields, apply: noMembers }\n const input = policy.inputOf(principal)\n const decided = members.map(member => ({\n ...member,\n // A redacted value is a decoded one; the record holds what the store holds.\n redacted: Match.valueTags(member.deny, {\n Redact: deny =>\n Option.some(\n Schema.encodeSync(\n (entity.members as Readonly<Record<string, { readonly schema: Schema.Top }>>)[\n member.member\n ]!.schema as unknown as Schema.Codec<unknown, unknown>,\n )(deny.value),\n ),\n NotFound: () => Option.none(),\n Omit: () => Option.none(),\n Forbidden: () => Option.none(),\n Explain: () => Option.none(),\n }),\n }))\n return {\n fields: [\n ...new Set([\n ...fields,\n ...members.flatMap(({ condition }) => Condition.members(condition)),\n ...Option.match(may, { onNone: () => [], onSome: ({ fields }) => fields }),\n ]),\n ],\n apply: record => {\n const values: Record<string, unknown> = { ...record.values }\n for (const { member, condition, redacted } of decided) {\n // Member rules carry no inherited Read: only a row's Read may inherit.\n if (\n Condition.holds(condition, record.values, input, () => false, policy.operators)\n )\n continue\n Option.match(redacted, {\n onNone: () => {\n delete values[member]\n },\n onSome: value => {\n values[member] = value\n },\n })\n }\n Option.map(may, ({ answer }) => {\n values.may = answer(record.values)\n })\n return { id: record.id, values }\n },\n }\n },\n ),\n policy,\n [entity],\n ),\n\n /**\n * `RemoteServer.memory`'s `readable` and `filter` for `entities`, the\n * Entities as `Guards.attach` returned them. A row's Read is decided per\n * stored row, an inherited Read by looking the related row up; an Entity\n * not listed is read by everyone.\n */\n memory: <User>(policy: Policy<User>, entities: ReadonlyArray<AnyEntity>) => ({\n readable: rowRules.add(\n (\n principal: Option.Option<User>,\n row: (entity: string, id: string) => Option.Option<Readonly<Record<string, unknown>>>,\n ): Effect.Effect<MemoryReadable> =>\n Effect.map(\n Effect.forEach(entities, entity =>\n Effect.map(\n policy.readable(entity, principal),\n condition => [entity.name, condition] as const,\n ),\n ),\n (decided): MemoryReadable => {\n const conditions = new Map(decided)\n const input = policy.inputOf(principal)\n // `seen` stops a cycle of inherited Reads, which would otherwise never end.\n const holds = (\n entity: string,\n values: Readonly<Record<string, unknown>>,\n seen: ReadonlySet<string>,\n ): boolean => {\n const condition = conditions.get(entity)\n if (condition === undefined) return true\n return Condition.holds(\n condition,\n values,\n input,\n relation =>\n Option.match(refOf(values[relation]), {\n onNone: () => false,\n onSome: ref => {\n const key = `${ref.entity}:${ref.id}`\n if (seen.has(key)) return false\n return Option.match(row(ref.entity, ref.id), {\n onNone: () => false,\n onSome: target => holds(ref.entity, target, new Set([...seen, key])),\n })\n },\n }),\n policy.operators,\n )\n }\n return (entity, values) => holds(entity, values, new Set())\n },\n ),\n policy,\n entities,\n ),\n filter: Object.fromEntries(\n entities.map(entity => [entity.name, GuardServer.filter(entity, policy)] as const),\n ),\n }),\n\n /**\n * `writer` with `entity`'s write rules checked before each write lands, for\n * `RemoteServer.write`. An update or a delete reads the row first under\n * the writer's own `read` (its Source's read rule): a row the writer may not\n * see is refused as one that is not there, and a delete of it changes\n * nothing. Then the row's rule for the command must hold over the row, each\n * member it sets must allow setting it, and each relation it points\n * elsewhere must allow the unlink and the link. An update's row rule holds\n * over the row as it would be after it too, so a write cannot move a row out\n * of its writer's reach. Each of its member and `Link` rules holds over the\n * row after with that one change undone (that member's value, or where that\n * relation pointed, as before): the change must be allowed given everything\n * else the write does, so one write cannot set together what each change\n * alone would be refused, while a rule reading its own member (\"only while\n * a draft\") still allows the change. An increment or a computed assignment\n * to a member is that member's own change. An `Unlink` rule holds over the\n * row before alone. A create's rules hold over the values it proposes, where a field the\n * create leaves unset matches no guard, not even one for an empty value. A refusal is\n * `Forbidden`, with the sentence an `explain` gave, or `Unauthenticated` for a\n * visitor; the write never runs.\n *\n * What the Entity sets from the write's context (`Entity.sets`: who asks,\n * when) reaches a create or an update already set by `RemoteServer.write`,\n * so a rule over it holds of the creator. A member rule over such a member\n * judges the server's value like any other: declare none there.\n *\n * `revision` names a field stored as a number, which the writer moves on by\n * one with each write it lands. An update or a delete then lands only on the\n * revision its rules were decided over (the writer's `expect`), so a change\n * between the check and the write is never written over; it is decided\n * again against the row as it now is, up to three times. A change that does\n * not move the revision (a handler's, `applyEdits`', raw SQL) is not seen.\n * Without `revision`, none is, and `validate` warns of an update, or a delete\n * of an Entity the server updates (an insert has no row). An input that expects a\n * revision the row read is not at is a `Conflict`, decided before any rule;\n * an input may expect only the field the writer pins.\n *\n * A delete that cascades (`Relation.one(…, { onDelete: 'cascade' })`) holds\n * each row it takes to that row's own `Delete` rule, for the same person, in\n * the statement that deletes (#348): one refused, and the whole delete is\n * `Forbidden`, naming the Entity, and nothing is removed. A relation declared\n * `authorizedBy: 'parent'` lets whoever may delete the row take the rows\n * pointing at it through that relation unjudged. The rules of an Entity\n * taken under its own are read from its guarded descriptor, given as\n * `children`; one missing is refused where the writer is made.\n *\n * ```ts\n * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))\n * GuardServer.writer(Post, Policy, writer(Db.Post), { children: [Like] })\n * ```\n */\n writer: <E extends AnyEntity, User, R, RW>(\n entity: E,\n policy: Policy<User, R>,\n writer: EntityWriter<Option.Option<User>, RW>,\n options: {\n readonly revision?: keyof E['fields'] & string\n /**\n * The guarded descriptor of each Entity a delete takes rows of under\n * their own `Delete` rule (`authorizedBy: 'child'`), whose rules judge them.\n */\n readonly children?: ReadonlyArray<AnyEntity>\n } = {},\n ): EntityWriter<Option.Option<User>, R | RW> => {\n const revision = options.revision\n if (revision !== undefined) {\n const field = Object.hasOwn(entity.fields, revision)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[revision]\n : undefined\n if (field === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${revision}\" for its revision`,\n )\n }\n // The writer moves it on by one in the statement it writes with, so it is stored as a number.\n if (!SchemaAST.isNumber(Schema.toEncoded(field.schema).ast)) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s revision \"${revision}\" is not stored as a number`,\n )\n }\n }\n if (writer.entity !== entity.name) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s rules over a writer for ${writer.entity}`,\n )\n }\n const read = writer.read\n if (read === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s writer reads no row as its writer may see it; bind it with a visible rule (GuardDrizzle.visible)`,\n )\n }\n // A rule reading another row is judged in the statement that writes: the writer must.\n const reaching = Option.match(attached(entity), {\n onNone: () => [],\n onSome: ({ row }) =>\n (['Update', 'Delete'] as const).flatMap(interaction =>\n (row[interaction]?.rules ?? []).flatMap(function names(rule): ReadonlyArray<string> {\n return Match.valueTags(rule, {\n PrincipalGuard: () => [],\n RowGuard: guard =>\n Query.dependencies(guard.query).reaches.length > 0 ? [guard.name] : [],\n All: ({ rules }) => rules.flatMap(names),\n Inherit: () => [],\n })\n }),\n ),\n })\n if (reaching.length > 0 && writer.requires !== true) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s ${reaching.join(', ')} reads another row, which only a writer judging rules in its statement can hold it to (foldkit-remote-drizzle's writer); this writer does not`,\n )\n }\n const judging = cascadeJudges(entity, options.children ?? [])\n if (judging.length > 0 && (writer.requires !== true || writer.cascades !== true)) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: a delete of ${entity.name} takes ${judging.map(child => child.name).join(', ')} rows under their own Delete rule, which only a writer judging rules in its statement and removing what cascades can hold it to (foldkit-remote-drizzle's writer); this writer does not`,\n )\n }\n const clearJudging = clearJudges(entity, options.children ?? [])\n if (clearJudging.length > 0 && (writer.requires !== true || writer.clears !== true)) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: a delete of ${entity.name} clears links of ${clearJudging.map(({ child }) => child.name).join(', ')} rows under their own Update rules, which only a writer judging rules in its statement and clearing links can hold it to (foldkit-remote-drizzle's writer); this writer does not`,\n )\n }\n const used = new Set([\n ...judging.map(child => child.identity.token),\n ...clearJudging.map(({ child }) => child.identity.token),\n ])\n const unused = (options.children ?? []).filter(child => !used.has(child.identity.token))\n if (unused.length > 0)\n throw new Error(\n `[foldkit-guard] GuardServer.writer: a delete of ${entity.name} takes no ${unused.map(child => child.name).join(', ')} rows under their own Delete rule, and clears no link of theirs, so children has nothing to judge them by`,\n )\n /**\n * The row rule over `values` as far as one row decides it: refused where it\n * fails, and otherwise what the writer's statement must still judge.\n */\n const rowRule = (\n rule: RowRule,\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ): Effect.Effect<Option.Option<WriteRequirement>, RemoteForbidden> => {\n const left = Condition.residual(\n rule.condition,\n values,\n policy.inputOf(principal),\n policy.operators,\n )\n return Match.valueTags(left, {\n Always: () => Effect.succeed(Option.none()),\n Never: () => Effect.fail(refused(rule.deny)),\n Row: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n Inherit: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n And: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n Or: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n })\n }\n const required = (\n left: Condition,\n deny: Deny,\n principal: Option.Option<User>,\n ): WriteRequirement => ({\n holds: requirementOf(left, policy.inputOf(principal)),\n reason: explained(deny),\n })\n const holds = (\n rule: { readonly condition: Condition },\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Condition.holds(\n rule.condition,\n values,\n policy.inputOf(principal),\n () => false,\n policy.operators,\n )\n /** Fails with the first rule of `rules` that does not hold over `values`. */\n const require = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Option.match(Option.fromUndefinedOr(rules.find(rule => !holds(rule, values, principal))), {\n onNone: () => Effect.void,\n onSome: rule => Effect.fail(refused(rule.deny)),\n })\n type Links = Readonly<\n Record<string, Option.Option<{ readonly entity: string; readonly id: string }>>\n >\n /** Each relation `links` points: its rules for unlinking and for linking a row. */\n const linkRules = (principal: Option.Option<User>, links: Links) =>\n Effect.forEach(Object.entries(links), ([relation, target]) =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Unlink'),\n policy.linkable(entity, principal, relation, 'Link'),\n ]),\n ([unlink, link]) => ({ relation, now: linkKey(target), unlink, link }),\n ),\n )\n /**\n * The rules a change from what each relation was linked to, to what it now\n * points at, must meet; none `before` is a create, which unlinks nothing.\n * Where `exact` is false, `links` are the row as its writer sees it, where\n * a link to a row hidden from them reads as none: a relation seen unlinked\n * may be linked after all, so changing it unlinks too.\n */\n const linking = (\n rules: ReadonlyArray<{\n readonly relation: string\n readonly now: string | null\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n before: Option.Option<{\n readonly links: Readonly<Record<string, unknown>>\n readonly exact: boolean\n }>,\n ): ReadonlyArray<RowRule> =>\n rules.flatMap(({ relation, now, unlink, link }) =>\n Option.match(before, {\n onNone: () => (now === null ? [] : Option.toArray(link)),\n onSome: ({ links, exact }) => {\n const was = links[relation] ?? null\n if (was === now && (exact || was !== null)) return []\n return [\n ...(was === null && exact ? [] : Option.toArray(unlink)),\n ...(now === null ? [] : Option.toArray(link)),\n ]\n },\n }),\n )\n const ruleOf = (\n rules: ReadonlyArray<{\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n ) => rules.flatMap(({ unlink, link }) => [...Option.toArray(unlink), ...Option.toArray(link)])\n const fieldsOf = (\n rules: ReadonlyArray<{ readonly condition: Condition }>,\n more: Iterable<string>,\n ) => [\n ...new Set([\n 'id',\n ...more,\n ...rules.flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n type Expect = Option.Option<{ readonly field: string; readonly revision: unknown }>\n /** The fields that say which version of the row was read: the revision, and the input's. */\n const versionFields = (expect: Expect) => [\n ...(revision === undefined ? [] : [revision]),\n ...Option.match(expect, { onNone: () => [], onSome: ({ field }) => [field] }),\n ]\n /** Whether the row read is not at the revision the input expects. */\n const moved = (expect: Expect, before: Readonly<Record<string, unknown>>) =>\n Option.exists(expect, ({ field, revision }) => !sameStored(before[field], revision))\n /** The write held to the row its rules were decided over, where there is a revision. */\n const pin = (expect: Expect, before: Readonly<Record<string, unknown>>): Expect =>\n revision === undefined ? expect : Option.some({ field: revision, revision: before[revision] })\n /**\n * `attempt` run again while its pinned write misses: the row moved after it\n * was read, so it is decided again over the row as it now is. A write the\n * input pinned misses as a conflict, and is not run again.\n */\n const pinned = <A, E, RA>(\n id: string,\n expect: Expect,\n missed: (outcome: A) => boolean,\n attempt: () => Effect.Effect<A, E, RA>,\n ): Effect.Effect<A, E | RemoteServerError, RA> => {\n if (revision === undefined) return attempt()\n if (Option.isSome(expect)) {\n // The pin is the one revision the write moves on; another would stand still.\n return expect.value.field === revision\n ? attempt()\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s input expects \"${expect.value.field}\", but its writer pins \"${revision}\"`,\n }),\n )\n }\n const loop = (left: number): Effect.Effect<A, E | RemoteServerError, RA> =>\n Effect.flatMap(attempt(), outcome =>\n !missed(outcome)\n ? Effect.succeed(outcome)\n : left > 1\n ? loop(left - 1)\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name} ${id} changed while it was written`,\n }),\n ),\n )\n return loop(3)\n }\n const attachment = attached(entity)\n const hiddenByBody = new WeakMap<AnyQuery, ReadonlyArray<string>>()\n // An invariant reading a member a Read rule hides is still enforced, but named to no\n // one: which one failed, and where, would say what that member holds.\n const unnamed = new Set(\n Option.match(attachment, {\n onNone: () => [],\n onSome: ruled =>\n Entity.invariants(entity)\n .filter(held => [...held.before, ...held.after].some(key => readRuled(ruled, key)))\n .map(held => held.id),\n }),\n )\n const told = <E>(error: E | RemoteInvalid): E | RemoteInvalid =>\n error instanceof RemoteInvalid && Option.exists(error.rule, rule => unnamed.has(rule))\n ? RemoteServer.invalid('The row would be invalid')\n : error\n /**\n * Fails a write whose `when` reads, whose `expect` names, or whose\n * computed assignment reads, a member with a Read rule: Unmet or written,\n * Conflict or not, and the computed value answered, would answer for it.\n * `validate` refuses the same at startup; this holds where it was not run.\n */\n const discloses = (\n expect: Expect,\n when: Option.Option<WriteWhen>,\n assignments: UpdateContext['assignments'] = {},\n ): Effect.Effect<void, RemoteServerError> =>\n Option.match(attachment, {\n onNone: () => Effect.void,\n onSome: ruled => {\n const read = Option.match(when, {\n onNone: () => [],\n onSome: ({ body }) => {\n const known = hiddenByBody.get(body)\n if (known !== undefined) return known\n const hidden = hiddenOf(ruled, Query.dependencies(body).predicate)\n hiddenByBody.set(body, hidden)\n return hidden\n },\n })\n const expected = Option.match(expect, {\n onNone: () => [],\n onSome: ({ field }) => (readRuled(ruled, field) ? [field] : []),\n })\n const computed = Write.boundReads({ increments: {}, assignments }).filter(field =>\n readRuled(ruled, field),\n )\n const hidden = [...new Set([...read, ...expected, ...computed])]\n return hidden.length === 0\n ? Effect.void\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write reads ${hidden.join(', ')}, which a Read rule hides from its writer`,\n }),\n )\n },\n })\n /**\n * The answer the writer's ledger holds for this operation, as `answered`\n * makes it, or else `write`: a retry of a write that landed is answered as\n * it landed, not decided again over a row, or a time, that has moved since.\n */\n const answeredOr = <A, E, RA>(\n context: {\n readonly id: string\n readonly operation: Option.Option<string>\n readonly request: string\n readonly principal: Option.Option<User>\n },\n answered: (answer: Readonly<Record<string, unknown>>) => A,\n write: () => Effect.Effect<A, E, RA>,\n ) => {\n const recorded = writer.recorded\n if (recorded === undefined || Option.isNone(context.operation)) return write()\n return Effect.flatMap(\n recorded({\n operation: context.operation.value,\n request: context.request,\n id: context.id,\n principal: context.principal,\n }),\n Option.match({ onSome: answer => Effect.succeed(answered(answer)), onNone: write }),\n )\n }\n // What an answer shows: the row as the writer may see it, members ruled.\n const memberRead = GuardServer.filter(entity, policy)\n // An update, step by step: admitted for what it declares, its rules chosen, the\n // row they read read, the rules decided over it as it is and as it would be, then\n // written pinned to that row. Each step refuses before the next can speak.\n type UpdateContext = Parameters<EntityWriter<Option.Option<User>, RW>['update']>[0]\n interface UpdateRules {\n readonly row: RowRule\n readonly members: ReadonlyArray<MemberRead>\n readonly relating: Effect.Success<ReturnType<typeof linkRules>>\n }\n /** Refused before any rule, for what the write declares rather than what the row holds. */\n const admitUpdate = (context: UpdateContext): Effect.Effect<void, RemoteServerError> =>\n Effect.andThen(discloses(context.expect, context.when, context.assignments), () =>\n // The rules judge a sum over the row read: unpinned, that is not the row written.\n Object.keys(context.increments).length + Object.keys(context.assignments).length > 0 &&\n Option.isNone(context.expect) &&\n revision === undefined\n ? Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write moves a field and expects no revision, and its writer pins none, so its rules would judge a value over a row that may move; give the writer a revision`,\n }),\n )\n : Effect.void,\n )\n /** The rules an update must meet: the row's, each member it sets, each relation it points. */\n const updateRules = (context: UpdateContext) =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Update')\n // A field moved or computed is set as surely as a written one: its Update rule holds.\n const members = yield* policy.writeMembers(\n entity,\n context.principal,\n [\n ...Object.keys(context.values),\n ...Object.keys(context.increments),\n ...Object.keys(context.assignments),\n ],\n 'Update',\n )\n const relating = yield* linkRules(context.principal, context.links)\n return { row, members, relating } satisfies UpdateRules\n })\n /**\n * The row as its writer may see it, with every field the rules and the\n * version read, and those the write's amounts and assignments read to\n * work out the row it leaves.\n */\n const readBefore = (context: UpdateContext, rules: UpdateRules) =>\n read({\n id: context.id,\n fields: fieldsOf(\n [rules.row, ...rules.members, ...ruleOf(rules.relating)],\n [\n ...Object.keys(context.links),\n ...versionFields(context.expect),\n ...Write.boundReads(context),\n // What its rule reads of the row by a path is compared with the row it leaves.\n ...Condition.reachedFrom(rules.row.condition, { entity: entity.name, id: context.id }),\n ],\n ),\n principal: context.principal,\n })\n /**\n * The memory table the row a write leaves is worked out by: the writer's,\n * so the rules judge the value its statement writes, else the policy's.\n */\n const computing = writer.operators ?? policy.operators\n /**\n * The row `context` would leave `before` as. An operator's refusal (text\n * holding NUL, an implementation that throws) is a server error, as the\n * writer answers what it cannot compile: reported here (`ComputeRefused`),\n * and never sent, since an implementation's own message may say anything.\n * So is a field it cannot\n * work out at all: judging its old value would let a rule over it pass.\n */\n const leaves = (before: Readonly<Record<string, unknown>>, context: UpdateContext) =>\n Effect.suspend(() => {\n const unworkable = Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write could not be worked out to judge its rules`,\n }),\n )\n try {\n const applied = Write.apply(before, context, { operators: computing })\n return applied.unknown.length === 0 ? Effect.succeed(applied.row) : unworkable\n } catch (error) {\n if (!(error instanceof QueryEvaluateError)) throw error\n return Diagnostics.report(computeRefused(entity.name, error)).pipe(\n Effect.andThen(unworkable),\n )\n }\n })\n /** The rules, over the row as it is and as the write would leave it. */\n const decideUpdate = (\n context: UpdateContext,\n rules: UpdateRules,\n before: Readonly<Record<string, unknown>>,\n ) =>\n Effect.gen(function* () {\n const { principal, links } = context\n const linked = Object.keys(links)\n const stored =\n writer.linked === undefined || linked.length === 0\n ? Option.none()\n : yield* writer.linked({ id: context.id, relations: linked })\n const was = Option.some(\n Option.match(stored, {\n onNone: () => ({ links: before, exact: false }),\n onSome: links => ({ links, exact: true }),\n }),\n )\n const relations = linking(rules.relating, was)\n // The rules over the row as stored refuse first: a writer they refuse learns\n // nothing of what its input would compute. What the row alone cannot decide\n // of its own rule is the statement's to judge, over the row it writes.\n const requires = yield* rowRule(rules.row, before, principal)\n yield* require([...rules.members, ...relations], before, principal)\n // What the writer will store, over the row read, which the pin keeps as the row\n // written: `Write.apply`'s, as the writer works it out.\n const after = {\n ...(yield* leaves(before, context)),\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n // Over the row it leaves, a rule reading another row is the statement's too,\n // which judges the stored row: so a write may not change what such a rule\n // reads of its own row, the one difference between the two.\n const leaving = yield* rowRule(rules.row, after, principal)\n if (Option.isSome(leaving)) {\n const read = Condition.reachedFrom(\n Condition.residual(\n rules.row.condition,\n after,\n policy.inputOf(principal),\n policy.operators,\n ),\n { entity: entity.name, id: context.id },\n )\n if (read.some(key => !sameStored(before[key], after[key]))) {\n return yield* Effect.fail(refused(rules.row.deny))\n }\n }\n // Each member's rule and each link's also over the row it leaves with that one\n // change undone: may it change, given all else the write does. Over the row before\n // alone, one write could set together what each change alone may not; over the\n // whole row after, \"only while a draft\" would refuse leaving the draft. An unlink is\n // of the row before, which the row after no longer points from.\n const undone = [\n ...rules.members.map(rule => ({ rule, key: rule.member })),\n ...rules.relating.flatMap(rule =>\n linking([{ ...rule, unlink: Option.none() }], was).map(link => ({\n rule: link,\n key: rule.relation,\n })),\n ),\n ]\n yield* Effect.forEach(\n undone,\n ({ rule, key }) => require([rule], { ...after, [key]: before[key] }, principal),\n { discard: true },\n )\n return requires\n })\n const guarded: EntityWriter<Option.Option<User>, R | RW> = {\n entity: writer.entity,\n // The precondition is the writer's to check, in the statement that writes.\n ...(writer.preconditions === true ? { preconditions: true } : {}),\n ...(writer.increments === true ? { increments: true } : {}),\n ...(writer.assignments === true ? { assignments: true } : {}),\n // With a revision every update lands over the row its rules read. Without one an\n // unpinned move is refused, so what the writer would say commutes is not passed on.\n ...(revision === undefined ? {} : { pins: true }),\n ...(writer.ledger === true ? { ledger: true } : {}),\n // Invariants are the writer's to judge, over the row its statement writes.\n ...(writer.invariants === true ? { invariants: true } : {}),\n // The rows a delete takes with it are the writer's to remove; the guard judges the row named.\n ...(writer.cascades === true ? { cascades: true } : {}),\n // So is refusing a row still pointed at, which only someone the rules let delete it learns.\n ...(writer.restricts === true ? { restricts: true } : {}),\n // So is clearing a link to it; the guard hands over each such row's Update rules.\n ...(writer.clears === true ? { clears: true } : {}),\n // What the store refuses, the store knows: the guard drops none of its reasons. It\n // adds one: its rules judge the row the write leaves, worked out by the policy's\n // table, so an assignment that table cannot run would be judged as its old value.\n refuses: write => [\n ...(writer.refuses?.(write) ?? []),\n ...write.assignments.flatMap(({ field, expr }) =>\n Expr.unsupported([expr], { operations: supported, operators: computing }).map(\n missing =>\n `its assignment to \"${field.key}\" calls ${missing}, which the guard cannot work out`,\n ),\n ),\n // Refused per request too (`admitUpdate`), for a caller that registers none.\n ...((write.increments.length > 0 || write.assignments.length > 0) &&\n write.expect === undefined &&\n revision === undefined\n ? [\n 'it moves a field and expects no revision, and the guarded writer pins none, so its rules would judge a value over a row that may move; give the writer a revision',\n ]\n : []),\n ],\n ...(writer.recorded === undefined ? {} : { recorded: writer.recorded }),\n read: ({ id, fields, principal }) =>\n seenRow(\n { filter: memberRead },\n seen => read({ id, fields: seen, principal }),\n principal,\n fields,\n id,\n ),\n update: context =>\n Effect.mapError(\n Effect.andThen(admitUpdate(context), () =>\n answeredOr(context, Option.some, () =>\n pinned(context.id, context.expect, Option.isNone, () =>\n Effect.gen(function* () {\n const rules = yield* updateRules(context)\n const current = yield* readBefore(context, rules)\n if (Option.isNone(current)) return yield* Effect.fail(refused(rules.row.deny))\n if (moved(context.expect, current.value)) return Option.none()\n const requires = yield* decideUpdate(context, rules, current.value)\n return yield* writer.update({\n ...context,\n expect: pin(context.expect, current.value),\n ...Option.match(requires, {\n onNone: () => ({}),\n onSome: held => ({ requires: held }),\n }),\n })\n }),\n ),\n ),\n ),\n told,\n ),\n insert: context =>\n answeredOr(context, identity, () =>\n Effect.gen(function* () {\n const { principal, values, links } = context\n const row = yield* policy.writable(entity, principal, 'Create')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n Object.keys(values),\n 'Create',\n )\n const relations = linking(yield* linkRules(principal, links), Option.none())\n const proposed = {\n ...values,\n id: context.id,\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n const rules = [row, ...members, ...relations]\n const ruled = rules.flatMap(({ condition }) => Condition.members(condition))\n const unset = new Set(ruled.filter(field => !Object.hasOwn(proposed, field)))\n yield* require(rules.map(rule => ({\n ...rule,\n condition: Condition.unsetting(rule.condition, unset),\n })), proposed, principal)\n return yield* Effect.mapError(writer.insert(context), told)\n }),\n ),\n delete: context =>\n Effect.andThen(discloses(context.expect, context.when), () =>\n pinned(context.id, context.expect, DeleteOutcome.$is('Moved'), () =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Delete')\n const current = yield* read({\n id: context.id,\n fields: fieldsOf([row], versionFields(context.expect)),\n principal: context.principal,\n })\n // Hidden or gone, the writer sees no row: there is nothing of theirs to delete.\n if (Option.isNone(current)) return DeleteOutcome.Absent()\n if (moved(context.expect, current.value)) return DeleteOutcome.Moved()\n const requires = yield* rowRule(row, current.value, context.principal)\n // Each row the cascade takes under its own rule, judged by the writer over the\n // rows as they are when it deletes, before it removes any.\n const cascading = yield* Effect.forEach(judging, child =>\n Effect.map(\n policy.writable(child, context.principal, 'Delete'),\n ({ condition, deny }): CascadeRequirement => ({\n entity: child.name,\n requires: required(condition, deny, context.principal),\n }),\n ),\n )\n // Each row whose link the delete clears, judged as an update unlinking it is:\n // the row's Update rule and the relation's Unlink rule, both of them.\n const clearing = yield* Effect.forEach(clearJudging, ({ child, relations }) =>\n Effect.gen(function* () {\n const row = yield* policy.writable(child, context.principal, 'Update')\n const unlinks = yield* Effect.forEach(relations, relation =>\n policy.linkable(child, context.principal, relation, 'Unlink'),\n )\n const rules = [row, ...unlinks.flatMap(Option.toArray)]\n const each = rules.map(rule =>\n required(rule.condition, rule.deny, context.principal),\n )\n return {\n entity: child.name,\n requires: {\n holds: RowRequirement.All({ of: each.map(({ holds }) => holds) }),\n reason: Option.firstSomeOf(each.map(({ reason }) => reason)),\n },\n } satisfies CascadeRequirement\n }),\n )\n return yield* writer.delete({\n ...context,\n expect: pin(context.expect, current.value),\n ...Option.match(requires, {\n onNone: () => ({}),\n onSome: held => ({ requires: held }),\n }),\n ...(judging.length === 0 ? {} : { cascading }),\n ...(clearJudging.length === 0 ? {} : { clearing }),\n })\n }),\n ),\n ),\n }\n const asked: EntityWriter<Option.Option<User>, R | RW> = {\n ...guarded,\n update: context => signInFirst(context.principal, guarded.update(context)),\n insert: context => signInFirst(context.principal, guarded.insert(context)),\n delete: context => signInFirst(context.principal, guarded.delete(context)),\n }\n pins.set(asked, Option.fromUndefinedOr(revision))\n return writeRules.add(asked, policy, [entity])\n },\n\n /**\n * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for\n * `interaction` checked before it runs. The row the input names (`id`) is\n * read through `source`, which must apply the Entity's Read rules, and the\n * rule must hold over it; a row its writer may not see is refused. With no\n * `id` (a create), the rule must hold of who is asking alone, a field it\n * reads matching no guard. `run` is given the row as read: its fields the\n * rule reads, its `id`, and `fields`. A refusal is `Forbidden`, or\n * `Unauthenticated` for a visitor; `run` never runs. What `run` writes is its own: check members it sets there. Each\n * row of `entity` its answer carries is read back through `source`, so the\n * answer shows its writer only what they may see, a row it hid from them\n * as deleted.\n *\n * ```ts\n * GuardServer.mutation(ArchiveTodo, {\n * entity: Todo, policy: Policy, interaction: Archive.key,\n * id: input => input.id, source: source(Db.Todo),\n * }, ({ input, row }) => …)\n * ```\n */\n mutation: <User, R, RS, RM, Name extends string, Input, Output, Refused>(\n mutation: MutationDescriptor<Name, Input, Output, Refused>,\n guard: {\n readonly entity: AnyEntity\n readonly policy: Policy<User, R>\n readonly interaction: 'Create' | 'Update' | 'Delete' | InteractionKey\n /**\n * The row the input acts on; none for a create. An input whose id may be\n * absent (`Option`, as one editor's for create and edit) creates when it\n * is, checked against `Create`.\n */\n readonly id?: ((input: Input) => string | Option.Option<string>) | undefined\n /** Reads the row as its writer may see it: the Entity's guarded Source. */\n readonly source: EntitySource<Option.Option<User>, RS>\n /** More of the row for `run`, beside what the rule reads. */\n readonly fields?: ReadonlyArray<string> | undefined\n },\n run: (context: {\n readonly input: Input\n readonly principal: Option.Option<User>\n readonly requestId: string\n readonly row: Option.Option<Readonly<Record<string, unknown>>>\n }) => Effect.Effect<\n MutationOutcome<Output>,\n RemoteServerError | MutationRefused | RemoteForbidden,\n RM\n >,\n ): MutationSource<Option.Option<User>, R | RS | RM> => {\n const { entity, policy, interaction, id, source } = guard\n if (!rowRules.has(source.visible, policy, entity)) {\n throw new Error(\n `[foldkit-guard] GuardServer.mutation: ${mutation.name}'s Source does not apply ${entity.name}'s Read rules`,\n )\n }\n /**\n * The answer as its writer may now see it: each row of `entity` it carries\n * read back through `source`, and one the handler hid from them deleted.\n */\n const shown = (outcome: MutationOutcome<Output>, principal: Option.Option<User>) =>\n Effect.map(\n Effect.forEach(outcome.entities ?? [], patch =>\n patch.entity !== entity.name\n ? Effect.succeed(Option.some(patch))\n : Effect.map(\n seenRow(\n source,\n fields =>\n Effect.map(rowOf(source, principal, fields, patch.id), Option.fromUndefinedOr),\n principal,\n Object.keys(patch.values),\n patch.id,\n ),\n Option.map(seen => ({ ...patch, values: seen })),\n ),\n ),\n read => ({\n ...outcome,\n entities: read.flatMap(Option.toArray),\n deleted: [\n ...(outcome.deleted ?? []),\n ...(outcome.entities ?? [])\n .filter((_, index) => Option.isNone(read[index]!))\n .map(({ entity, id }) => ({ entity, id })),\n ],\n }),\n )\n return RemoteServer.mutation<Option.Option<User>, R | RS | RM, Name, Input, Output, Refused>(\n mutation,\n context =>\n Effect.gen(function* () {\n const { principal } = context\n // `context.input` was decoded against the mutation's Input before this runs.\n const target = Option.flatMap(Option.fromUndefinedOr(id), of => {\n const named = of(context.input)\n return typeof named === 'string' ? Option.some(named) : named\n })\n const rule = yield* policy.writable(\n entity,\n principal,\n id !== undefined && Option.isNone(target) ? 'Create' : interaction,\n )\n const ruled = Condition.members(rule.condition)\n const input = policy.inputOf(principal)\n if (Option.isNone(target)) {\n const unset = Condition.unsetting(rule.condition, new Set(ruled))\n if (!Condition.holds(unset, {}, input, () => false, policy.operators)) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row: Option.none() }), principal)\n }\n const fields = [...new Set(['id', ...ruled, ...(guard.fields ?? [])])]\n const row = Option.fromUndefinedOr(yield* rowOf(source, principal, fields, target.value))\n if (\n Option.isNone(row) ||\n !Condition.holds(rule.condition, row.value, input, () => false, policy.operators)\n ) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row }), principal)\n }).pipe(answered => signInFirst(context.principal, answered)),\n )\n },\n\n /**\n * Checks, at startup, that `server` applies the guards of `entities`, the\n * Entities as `Guards.attach` returned them: each one's Source and each\n * query listing it apply its row's Read rules (`GuardDrizzle.visible`, or\n * `GuardServer.memory`), its Source applies its members' and relations'\n * (`GuardServer.filter`), and each declared write of it lands through\n * `GuardServer.writer`, all built from `policy`; and that no query's body\n * filters or orders by a member with a Read rule, its own or one of a row it\n * reaches through a path or an exists, which would answer for the value it\n * hides. A hand-written Source over a guarded Entity would serve\n * every row, and a bare writer would take every write; this throws instead,\n * naming each. A handler (`RemoteServer.mutation`) writes what its code\n * writes, which no check at startup can read. A write a change can come\n * between, through a writer given no revision, is not refused but reported:\n * `UnpinnedWrites`, a warning, to `diagnostics`.\n *\n * ```ts\n * GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })\n * ```\n */\n validate: <User, R>(\n policy: Policy<User, R>,\n config: {\n readonly entities: ReadonlyArray<AnyEntity>\n /** The Remote domain the server answers, for which Entity each query lists. */\n readonly domain: {\n readonly registry: {\n readonly queries: ReadonlyMap<\n string,\n { readonly Result: unknown; readonly body?: AnyQuery | undefined }\n >\n }\n }\n readonly server: ServerDefinition<any, any>\n /** Where the `UnpinnedWrites` warning goes; `Diagnostics.Reporter`'s default, the log, when not given. */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n ): void => {\n const byName = new Map(config.entities.map(entity => [entity.name, entity]))\n /** Whether a reached member has a Read rule; one of an Entity not validated has none checked. */\n const hidesFromReach = ({ entity, key }: ReachedMember) =>\n Option.exists(\n Option.flatMap(Option.fromUndefinedOr(byName.get(entity)), attached),\n attachment => readRuled(attachment, key),\n )\n /** Whether who may read the rows of `entity` depends on who is asking. */\n const rowsRuled = (entity: AnyEntity | undefined) =>\n Option.exists(Option.flatMap(Option.fromUndefinedOr(entity), attached), attachment =>\n readRowsRuled(attachment),\n )\n // A query the domain does not declare lists an Entity no one can name.\n const undeclared = [...config.server.queries.keys()]\n .filter(query => !config.domain.registry.queries.has(query))\n .map(query => `query ${query} is served, but the domain does not declare it`)\n const entityProblems = config.entities.flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => {\n const name = entity.name\n if (attachment.set !== policy.set) {\n return [`${name} carries the guards of ${attachment.set}, not ${policy.set}`]\n }\n // Every guarded Entity's, whether or not it has rules there yet: a rule\n // attached later is then applied, not served past.\n const source = Option.fromUndefinedOr(config.server.entities.get(name))\n const sourceProblems = Option.match(source, {\n onNone: () => [],\n onSome: ({ visible, filter }) => [\n ...(rowRules.has(visible, policy, entity)\n ? []\n : [`${name}'s Source does not apply its Read rules`]),\n ...(memberRules.has(filter, policy, entity)\n ? []\n : [`${name}'s Source does not apply its members' Read rules`]),\n ],\n })\n const queryProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, query]) => {\n const listed = config.server.queries.get(queryName)\n return listed !== undefined &&\n lists(query.Result, name) &&\n !rowRules.has(listed.visible, policy, entity)\n ? [`query ${queryName} lists ${name} without its Read rules`]\n : []\n },\n )\n // A row the reader may see with a member it may not still answers a\n // filter or an order on that member: `cost < $max`, halved twenty\n // times, reads the cost the row came back without.\n const bodyProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, { body }]) => {\n if (body === undefined || body.entity.name !== name) return []\n const { predicate, order, reaches } = Query.dependencies(body)\n const reached = [\n ...new Set(\n reachedMembers(reaches)\n .filter(hidesFromReach)\n .map(\n ({ entity, key }) =>\n `query ${queryName} reaches ${entity}'s ${key}, which has a Read rule`,\n ),\n ),\n ]\n return [\n ...hiddenOf(attachment, predicate).map(\n member =>\n `query ${queryName} filters ${name} by ${member}, which has a Read rule`,\n ),\n ...hiddenOf(attachment, order).map(\n member => `query ${queryName} orders ${name} by ${member}, which has a Read rule`,\n ),\n ...reached,\n ]\n },\n )\n const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => {\n if (source.writes === undefined || source.writes.entity !== name) return []\n if (!writeRules.has(source.writes.writer, policy, entity)) {\n return [`write ${mutation} writes ${name} without its write rules`]\n }\n const { write, writer } = source.writes\n const interaction = Match.valueTags(write, {\n Insert: () => 'Create',\n Update: () => 'Update',\n Delete: () => 'Delete',\n })\n // Left without a rule under 'allow', a served write is anyone's: that is\n // written down as `Guards.anyone`, never left to a forgotten rule.\n const open =\n attachment.unguarded === 'allow' &&\n Option.isNone(surfaceOf(attachment, { _tag: 'Row', interaction }))\n ? [\n `write ${mutation} ${interaction === 'Create' ? 'creates' : `${interaction.toLowerCase()}s`} ${name}, which has no ${interaction} rule, so unguarded: 'allow' lets anyone; give it one, or [Guards.anyone] to say anyone may`,\n ]\n : []\n // Unmet or written, Conflict or not, answers for a member its writer may not read.\n const when = Option.match(write.when, {\n onNone: () => [],\n onSome: body => hiddenOf(attachment, Query.dependencies(body).predicate),\n })\n const computed = write.assignments.flatMap(assignment =>\n hiddenOf(attachment, dependenciesOf(assignment.expr).fields).map(\n member =>\n `write ${mutation} computes ${name}'s ${assignment.field.key} from its ${member}, which has a Read rule`,\n ),\n )\n const expected = write.expect?.field.key\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n return [\n ...open,\n ...when.map(\n member =>\n `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`,\n ),\n ...computed,\n ...(expected !== undefined && readRuled(attachment, expected)\n ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`]\n : []),\n ...(expected !== undefined &&\n pin !== undefined &&\n Option.exists(pin, field => field !== expected)\n ? [\n `write ${mutation} expects ${name}'s ${expected}, but its writer pins ${Option.getOrThrow(pin)}`,\n ]\n : []),\n ]\n })\n // A shared field goes to every live subscriber as written: no rule may tell them apart.\n const shared: ReadonlyArray<string> = Option.match(source, {\n onNone: () => [],\n onSome: source => [...(source.shared ?? [])],\n })\n const sharedProblems = [\n ...(shared.length > 0 && readRowsRuled(attachment)\n ? [`${name}'s Source shares ${shared.join(', ')}, but its rows have a Read rule`]\n : []),\n // Each reader's own answer, whoever may read the row.\n ...(shared.includes('may') && asksMay(entity, ['may'])\n ? [`${name}'s Source shares may, which is answered for each reader`]\n : []),\n ...shared.flatMap(member => {\n const own = readRuled(attachment, member)\n ? [`${name}'s Source shares ${member}, which has a Read rule`]\n : []\n if (!Object.hasOwn(entity.relations, member)) return own\n const target = entity.relations[member]!.target().name\n if (!byName.has(target))\n return [\n ...own,\n `${name}'s Source shares ${member}, whose ${target} is not validated`,\n ]\n return rowsRuled(byName.get(target))\n ? [...own, `${name}'s Source shares ${member}, whose rows have a Read rule`]\n : own\n }),\n ]\n // A rule calling an operator the policy's table does not run would fail when\n // asked, so the server does not start with one (expr-operations-DESIGN §5.6).\n const operatorProblems = attachedRules(attachment).flatMap(rule =>\n Match.value(rule).pipe(\n Match.tag('RowGuard', guard =>\n Query.unsupported(guard.query, supported, policy.operators).map(\n missing =>\n `${name}'s ${guard.name} calls ${missing}, which the policy does not run`,\n ),\n ),\n Match.orElse(() => []),\n ),\n )\n // A live Source sends what it reads: only one reading through the Source\n // checked above is known to send what a read would.\n const live = Option.fromUndefinedOr(config.server.live.get(name))\n const liveProblems = Option.exists(\n live,\n ({ reads }) => !Option.exists(source, checked => checked === reads),\n )\n ? [\n `${name}'s live Source does not read through its guarded Source; poll through that Source (pollLive) or serve changes through a live hub`,\n ]\n : []\n return [\n ...sourceProblems,\n ...queryProblems,\n ...bodyProblems,\n ...writeProblems,\n ...sharedProblems,\n ...operatorProblems,\n ...liveProblems,\n ]\n },\n }),\n )\n const problems = [...undeclared, ...entityProblems]\n if (problems.length > 0) {\n throw new Error(`[foldkit-guard] GuardServer.validate: ${problems.join('; ')}`)\n }\n // Not refused yet: a writer given no revision is how every writer was made before it.\n // Named only where a change between the check and the write can happen: an update\n // always, a delete where the server updates that Entity, an insert, with no row, never.\n const updated = new Set(\n [...config.server.mutations.values()]\n .flatMap(source => (source.writes === undefined ? [] : [source.writes]))\n .filter(writes => writes.write._tag === 'Update')\n .map(writes => writes.entity),\n )\n const unpinned = [...config.server.mutations].flatMap(([mutation, source]) => {\n const writes = source.writes\n if (writes === undefined) return []\n const writer = writes.writer\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n if (pin === undefined || Option.isSome(pin)) return []\n const races = Match.valueTags(writes.write, {\n Update: () => true,\n Delete: () => updated.has(writes.entity),\n Insert: () => false,\n })\n return races ? [mutation] : []\n })\n if (unpinned.length > 0) {\n // A startup check runs before any Effect of the server's, so the reporter is an option.\n const report = Diagnostics.report(unpinnedWrites(unpinned))\n const { diagnostics } = config\n Effect.runFork(\n diagnostics === undefined\n ? report\n : Effect.provideService(report, Diagnostics.Reporter, diagnostics),\n )\n }\n },\n}\n\n/** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */\nconst asksMay = (entity: AnyEntity, fields: ReadonlyArray<string>) =>\n fields.includes('may') && Object.hasOwn(entity.derived, 'may')\n\n/** How one principal's `may` is answered: the fields its rules read, and the answer over a row. */\ninterface MayPlan {\n readonly fields: ReadonlyArray<string>\n readonly answer: (values: Readonly<Record<string, unknown>>) => MayAnswer\n}\n\n/**\n * `may` for `principal`: each row interaction's rule, each member's own\n * `Update`, each relation's `Link` and `Unlink`, decided once and held over\n * each row as a write's check would hold them over it as it is.\n */\nconst mayOf = <User, R>(\n entity: AnyEntity,\n policy: Policy<User, R>,\n principal: Option.Option<User>,\n): Effect.Effect<MayPlan, never, R> =>\n Effect.map(\n mayRules(entity, {\n // A named one was attached as an `InteractionKey`; its key is the name.\n row: interaction => policy.writable(entity, principal, interaction as InteractionKey),\n members: members => policy.writeMembers(entity, principal, members, 'Update'),\n relation: (relation, interaction) =>\n policy.linkable(entity, principal, relation, interaction),\n }),\n (rules): MayPlan => {\n const input = policy.inputOf(principal)\n return {\n // `id` too, so a row is read when its rules read none of it (an admin's).\n fields: ['id', ...new Set(mayConditions(rules).flatMap(Condition.members))],\n // A rule reading another row is the write's statement's to judge: not answered here.\n answer: values =>\n answerOf(rules, condition =>\n Condition.decided(Condition.residual(condition, values, input, policy.operators)),\n ),\n }\n },\n )\n\n/** A refused write as the client receives it: the sentence an `explain` gave, or none. */\n/** The words a refusal gives: an `explain`'s, or none. */\nconst explained = (deny: Deny): Option.Option<string> =>\n Match.valueTags(deny, {\n Explain: ({ reason }) => Option.some(reason),\n Forbidden: () => Option.none(),\n NotFound: () => Option.none(),\n Omit: () => Option.none(),\n Redact: () => Option.none(),\n })\n\n/**\n * The guarded descriptor of each Entity a delete of `root`'s row takes rows of\n * under their own `Delete` rule (`authorizedBy: 'child'`), followed through\n * every cascade, `root` itself for a cascade into its own Entity. Refused\n * where one is not among `children`, and where a child is given that no\n * such cascade reaches, so the option cannot quietly say nothing.\n */\nconst cascadeJudges = (\n root: AnyEntity,\n children: ReadonlyArray<AnyEntity>,\n): ReadonlyArray<AnyEntity> => {\n const given = new Map(children.map(child => [child.identity.token, child]))\n given.set(root.identity.token, root)\n const judged = new Map<symbol, AnyEntity>()\n const seen = new Set([root.identity.token])\n const queue: Array<AnyEntity> = [root]\n for (let next = queue.shift(); next !== undefined; next = queue.shift())\n for (const { relation, owner } of Entity.cascading(next)) {\n const token = owner.identity.token\n const own = Option.getOrElse(relation.authorizedBy, () => 'child' as const) === 'child'\n if (own && !judged.has(token)) {\n const guarded = given.get(token)\n if (guarded === undefined)\n throw new Error(\n `[foldkit-guard] GuardServer.writer: a delete of ${root.name} takes ${owner.name} rows under their own Delete rule (${owner.name}.${relation.key}); give ${owner.name}'s guarded Entity as children: [${owner.name}], or declare the relation authorizedBy: 'parent'`,\n )\n judged.set(token, guarded)\n }\n if (!seen.has(token)) {\n seen.add(token)\n queue.push(owner)\n }\n }\n return [...judged.values()]\n}\n\n/**\n * The guarded descriptor of each Entity whose link a delete of `root`'s row\n * clears (`onDelete: 'setNull'`, #467), with the relations it clears: each\n * such row is held to its own `Update` rules over the link. Refused where one\n * is not among `children`.\n */\nconst clearJudges = (\n root: AnyEntity,\n children: ReadonlyArray<AnyEntity>,\n): ReadonlyArray<{ readonly child: AnyEntity; readonly relations: ReadonlyArray<string> }> => {\n const given = new Map(children.map(child => [child.identity.token, child]))\n given.set(root.identity.token, root)\n const judged = new Map<symbol, { child: AnyEntity; relations: Array<string> }>()\n for (const { relation, owner } of Entity.clearing(root)) {\n const token = owner.identity.token\n const guarded = given.get(token)\n if (guarded === undefined)\n throw new Error(\n `[foldkit-guard] GuardServer.writer: a delete of ${root.name} clears ${owner.name}.${relation.key} under ${owner.name}'s own Update rules; give ${owner.name}'s guarded Entity as children: [${owner.name}]`,\n )\n const known = judged.get(token) ?? { child: guarded, relations: [] }\n known.relations.push(relation.key)\n judged.set(token, known)\n }\n return [...judged.values()]\n}\n\n/**\n * What is left of a condition, as a writer's statement judges it: each row\n * guard a body over the row, its input the principal's (`G.inputOf`), and its\n * context the one it was decided for. An inherited Read, which a writer\n * refuses, requires what no row holds.\n */\nconst requirementOf = (\n condition: Condition,\n input: Readonly<Record<string, unknown>>,\n): RowRequirement =>\n Match.valueTags(condition, {\n Always: () => RowRequirement.All({ of: [] }),\n Never: () => RowRequirement.Any({ of: [] }),\n Row: ({ guard, context }) => RowRequirement.Body({ query: guard.query, input, context }),\n Inherit: () => RowRequirement.Any({ of: [] }),\n And: ({ conditions }) =>\n RowRequirement.All({ of: conditions.map(each => requirementOf(each, input)) }),\n Or: ({ conditions }) =>\n RowRequirement.Any({ of: conditions.map(each => requirementOf(each, input)) }),\n })\n\n/**\n * A visitor's refused write as a sign-in it needs: `Unauthenticated`, never\n * `Forbidden`, so a client tells a session that ended (its cookie gone, it\n * asks as a visitor) from a person refused, and a durable write waits for the\n * sign-in rather than failing (#403). A refusal's words go with it.\n */\nconst signInFirst = <User, A, E, R>(\n principal: Option.Option<User>,\n write: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E | RemoteUnauthenticated, R> =>\n Option.isSome(principal)\n ? write\n : Effect.mapError(write, error =>\n error instanceof RemoteForbidden ? RemoteServer.unauthenticated(error.reason) : error,\n )\n\nconst refused = (deny: Deny) =>\n Match.valueTags(deny, {\n Explain: ({ reason }) => RemoteServer.forbid(reason),\n Forbidden: () => RemoteServer.forbid(),\n NotFound: () => RemoteServer.forbid(),\n Omit: () => RemoteServer.forbid(),\n Redact: () => RemoteServer.forbid(),\n })\n\n/** One row, by id, as `principal` may read it through `source`. */\nconst rowOf = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n) =>\n Effect.map(\n source.read({ ids: [id], fields: [...fields], principal }),\n records => records.find(record => record.id === id)?.values,\n )\n\n/**\n * Row `id` of `fields` as `principal` may see it, through `see`'s `authorize`\n * and `filter` as a Source applies them, and no more than was asked: what an\n * answer shows its writer. None when the row is not there to them.\n */\nconst seenRow = <P, R, RS>(\n see: Pick<EntitySource<P, RS>, 'authorize' | 'filter'>,\n read: (\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n): Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R | RS> =>\n Effect.gen(function* () {\n const allowed = see.authorize === undefined ? fields : see.authorize(principal, [...fields])\n const plan: ReadPlan =\n see.filter === undefined\n ? { fields: allowed, apply: noMembers }\n : yield* see.filter(principal, allowed)\n // The id too: a row asked for nothing else is still there or not.\n const row = yield* read([...new Set(['id', ...plan.fields])])\n return Option.map(row, values => {\n const shown = plan.apply({ id, values }).values\n return Object.fromEntries(\n allowed.filter(field => Object.hasOwn(shown, field)).map(field => [field, shown[field]]),\n )\n })\n })\n\n/** A link's value as a row holds it: the ref's key, or `null` for none. */\nconst linkKey = (link: Option.Option<{ readonly entity: string; readonly id: string }>) =>\n Option.match(link, { onNone: () => null, onSome: ref => `${ref.entity}:${ref.id}` })\n\n/** Whether a query's result is a connection over `entity`. */\nconst lists = (result: unknown, entity: string): boolean =>\n typeof result === 'object' && result !== null && 'entity' in result && result.entity === entity\n"],"mappings":";;;;;;;;;;AAOA,MAAM,SAAS;AA0Bf,MAAa,kBAAkB,QAAgB,WAAkC;CAC/E,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,OAAO,qEAAqE,MAAM,QAAQ;CACtG;CACA;AACF;AAEA,MAAa,kBAAkB,eAAsD;CACnF,MAAM;CACN;CACA,OAAO;CACP,SAAS,yBAAyB,UAAU,KAAK,IAAI,EAAE,GAAG,UAAU,WAAW,IAAI,WAAW,QAAQ;CACtG;AACF;;;;;;;;;ACgBA,MAAM,aAAa,WAAyB;;AAG5C,MAAM,cAAc,MAAe,UACjC,KAAK,UAAU,IAAI,MAA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AG;AAAU,CAAC,IACzD,YAAW,QAAQ,MAAK,WAAU,OAAO,OAAO,EAAE,CAAC,EAAE,MACvD;;;;;;AAOF,MAAM,WACJ,KACA,MAGA,WACA,QACA,OAEA,OAAO,IAAI,aAAa;CACtB,MAAM,UAAU,IAAI,cAAc,KAAA,IAAY,SAAS,IAAI,UAAU,WAAW,CAAC,GAAG,MAAM,CAAC;CAC3F,MAAM,OACJ,IAAI,WAAW,KAAA,IACX;EAAE,QAAQ;EAAS,OAAO;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"}
1
+ {"version":3,"file":"server.mjs","names":[],"sources":["../src/diagnostics.ts","../src/server.ts"],"sourcesContent":["/**\n * What a guarded server meets and answers past: a computed value an operator\n * refused, answered with a fixed message, and writes `GuardServer.validate`\n * finds unpinned. Each is reported through `Diagnostics.report`.\n */\nimport type { Diagnostic } from 'foldkit-remote'\n\nconst source = 'foldkit-guard'\n\n/**\n * An operator refused to work out a value a guarded write computes (text\n * holding NUL, an implementation that throws). The write was refused with a\n * fixed message, since the operator's own may say anything.\n */\nexport interface ComputeRefused extends Diagnostic {\n readonly _tag: 'ComputeRefused'\n readonly entity: string\n /** The operator's own refusal. */\n readonly error: Error\n}\n\n/**\n * Writes through a `GuardServer.writer` given no revision, where a change can\n * come between the check and the write, which is then not seen.\n */\nexport interface UnpinnedWrites extends Diagnostic {\n readonly _tag: 'UnpinnedWrites'\n readonly mutations: ReadonlyArray<string>\n}\n\n/** Every diagnostic `foldkit-guard` reports. */\nexport type GuardDiagnostic = ComputeRefused | UnpinnedWrites\n\nexport const computeRefused = (entity: string, error: Error): ComputeRefused => ({\n _tag: 'ComputeRefused',\n source,\n level: 'error',\n message: `${entity}'s write was refused: a value it computes could not be worked out (${error.message})`,\n entity,\n error,\n})\n\nexport const unpinnedWrites = (mutations: ReadonlyArray<string>): UnpinnedWrites => ({\n _tag: 'UnpinnedWrites',\n source,\n level: 'warning',\n message: `GuardServer.validate: ${mutations.join(', ')} ${mutations.length === 1 ? 'writes' : 'write'} through a GuardServer.writer with no revision, so a change between its check and its write is not seen; pass { revision }`,\n mutations,\n})\n","/**\n * A guard set's read rules as `foldkit-remote-server`'s seams: an\n * `EntitySource.filter` from each member's Read rule, and `RemoteServer.memory`'s\n * `readable` and `filter` from the row's, and a check at startup that a server\n * applies them. A subpath, so the shared declaration the browser imports never\n * brings the server along.\n */\nimport { Effect, Match, Option, Schema, SchemaAST, identity } from 'effect'\nimport {\n Entity,\n Expr,\n Query,\n QueryEvaluateError,\n Write,\n dependenciesOf,\n supported,\n type AnyEntity,\n type AnyQuery,\n type Invariant,\n} from 'foldkit-entity'\nimport {\n Diagnostics,\n RemoteForbidden,\n type MutationDescriptor,\n type RemoteUnauthenticated,\n type ReportDiagnostic,\n} from 'foldkit-remote'\nimport {\n RemoteInvalid,\n RemoteServer,\n DeleteOutcome,\n RemoteServerError,\n RowRequirement,\n type EntityRecord,\n type EntitySource,\n type EntityWriter,\n type MutationOutcome,\n type MutationRefused,\n type MutationSource,\n type MemoryReadable,\n type ReadPlan,\n type ServerDefinition,\n type CascadeRequirement,\n type WriteRequirement,\n type WriteWhen,\n} from 'foldkit-remote-server'\nimport {\n attachedRules,\n enforced,\n reachingRules,\n readRowsRuled,\n readRuled,\n surfaceOf,\n type Attachment,\n type Deny,\n type InteractionKey,\n} from './attach.js'\nimport { Condition, type MemberRead, type RowRule } from './condition.js'\nimport type { Policy } from './index.js'\nimport { answerOf, mayConditions, mayRules, type MayAnswer } from './may.js'\nimport { ME, type MeEntity } from './me.js'\nimport { memberRules, rowRules, writeRules } from './placed.js'\nimport { computeRefused, unpinnedWrites } from './diagnostics.js'\n\nexport type { ComputeRefused, GuardDiagnostic, UnpinnedWrites } from './diagnostics.js'\n\nconst noMembers = (record: EntityRecord) => record\n\n/** Two stored values, which are JSON: equal when they encode the same. */\nconst sameStored = (left: unknown, right: unknown): boolean =>\n JSON.stringify(left) === JSON.stringify(right)\n\n/** The members of `fields` that have a Read rule, once each. */\nconst hiddenOf = (\n attachment: Attachment,\n fields: ReadonlyArray<{ readonly key: string }>,\n): ReadonlyArray<string> => [\n ...new Set(fields.map(field => field.key).filter(key => readRuled(attachment, key))),\n]\n\n/** A member of a row a body reaches: the Entity it belongs to, by name, and its key. */\ninterface ReachedMember {\n readonly entity: string\n readonly key: string\n}\n\n/**\n * Each member a body reads on a row it reaches rather than judges: every\n * relation a path, a path from the viewer or an exists follows, the field a\n * path ends at, and an exists' pointing relation and filter. SQL reads such a\n * row under its `visible` rule alone, never its members'.\n */\nconst reachedMembers = (\n reaches: ReturnType<typeof dependenciesOf>['reaches'],\n): ReadonlyArray<ReachedMember> =>\n reaches.flatMap(reached => {\n const via = reached.via.map(relation => ({ entity: relation.owner.name, key: relation.key }))\n return Match.valueTags(reached, {\n Path: ({ field }) => [...via, { entity: field.owner.name, key: field.key }],\n ViewerPath: ({ field }) => [...via, { entity: field.owner.name, key: field.key }],\n Exists: ({ relation, where }) => {\n const filter = Option.match(where, {\n onNone: () => [],\n onSome: body => {\n const read = dependenciesOf(body)\n return [\n ...read.fields.map(field => ({ entity: field.entity, key: field.key })),\n ...reachedMembers(read.reaches),\n ]\n },\n })\n return [...via, { entity: relation.owner.name, key: relation.key }, ...filter]\n },\n })\n })\n\n/** Each guarded writer's `revision`, or none: one a change can fall between check and write of. */\nconst pins = new WeakMap<object, Option.Option<string>>()\n\n/** A ref key's two halves, `Entity:id`; `none` for anything else. */\nconst refOf = (value: unknown): Option.Option<{ readonly entity: string; readonly id: string }> => {\n if (typeof value !== 'string') return Option.none()\n const split = value.indexOf(':')\n return split <= 0\n ? Option.none()\n : Option.some({ entity: value.slice(0, split), id: value.slice(split + 1) })\n}\n\nexport const GuardServer = {\n /**\n * `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`\n * answered by `policy`. `signedIn` is whether the server answered as\n * someone; `key` is their `key`. Any other id is no row.\n *\n * ```ts\n * RemoteServer.make({ entities: [GuardServer.me(Me, Policy), …] })\n * ```\n */\n me: <User, R>(\n entity: MeEntity,\n policy: Policy<User, R>,\n ): EntitySource<Option.Option<User>, R> => {\n // Otherwise every read would die deciding another set's guards.\n Option.map(enforced(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 enforced(entity)\n return 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: Match.valueTags(member.deny, {\n Redact: deny =>\n Option.some(\n Schema.encodeSync(\n (entity.members as Readonly<Record<string, { readonly schema: Schema.Top }>>)[\n member.member\n ]!.schema as unknown as Schema.Codec<unknown, unknown>,\n )(deny.value),\n ),\n NotFound: () => Option.none(),\n Omit: () => Option.none(),\n Forbidden: () => Option.none(),\n Explain: () => Option.none(),\n }),\n }))\n return {\n fields: [\n ...new Set([\n ...fields,\n ...members.flatMap(({ condition }) => Condition.members(condition)),\n ...Option.match(may, { onNone: () => [], onSome: ({ fields }) => fields }),\n ]),\n ],\n apply: record => {\n const values: Record<string, unknown> = { ...record.values }\n for (const { member, condition, redacted } of decided) {\n // Member rules carry no inherited Read: only a row's Read may inherit.\n if (\n Condition.holds(condition, record.values, input, () => false, policy.operators)\n )\n continue\n Option.match(redacted, {\n onNone: () => {\n delete values[member]\n },\n onSome: value => {\n values[member] = value\n },\n })\n }\n Option.map(may, ({ answer }) => {\n values.may = answer(record.values)\n })\n return { ...record, values }\n },\n }\n },\n ),\n policy,\n [entity],\n )\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. A Read rule that reads another row (a\n * path, an exists) is refused here: each stored row is judged alone, and\n * only a statement judges such a rule (`GuardDrizzle.visible`).\n */\n memory: <User>(policy: Policy<User>, entities: ReadonlyArray<AnyEntity>) => ({\n readable: rowRules.add(\n (\n principal: Option.Option<User>,\n row: (entity: string, id: string) => Option.Option<Readonly<Record<string, unknown>>>,\n ): Effect.Effect<MemoryReadable> =>\n Effect.map(\n Effect.forEach(entities, entity =>\n Effect.map(\n policy.readable(entity, principal),\n condition => [entity.name, condition] as const,\n ),\n ),\n (decided): MemoryReadable => {\n const conditions = new Map(decided)\n const input = policy.inputOf(principal)\n // `seen` stops a cycle of inherited Reads, which would otherwise never end.\n const holds = (\n entity: string,\n values: Readonly<Record<string, unknown>>,\n seen: ReadonlySet<string>,\n ): boolean => {\n const condition = conditions.get(entity)\n if (condition === undefined) return true\n return Condition.holds(\n condition,\n values,\n input,\n relation =>\n Option.match(refOf(values[relation]), {\n onNone: () => false,\n onSome: ref => {\n const key = `${ref.entity}:${ref.id}`\n if (seen.has(key)) return false\n return Option.match(row(ref.entity, ref.id), {\n onNone: () => false,\n onSome: target => holds(ref.entity, target, new Set([...seen, key])),\n })\n },\n }),\n policy.operators,\n )\n }\n return (entity, values) => holds(entity, values, new Set())\n },\n ),\n policy,\n readingOneRow(entities),\n ),\n filter: Object.fromEntries(\n entities.map(entity => [entity.name, GuardServer.filter(entity, policy)] as const),\n ),\n }),\n\n /**\n * `writer` with `entity`'s write rules checked before each write lands, for\n * `RemoteServer.write`. An update or a delete reads the row first under\n * the writer's own `read` (its Source's read rule): a row the writer may not\n * see is refused as one that is not there, and a delete of it changes\n * nothing. Then the row's rule for the command must hold over the row, each\n * member it sets must allow setting it, and each relation it points\n * elsewhere must allow the unlink and the link. An update's row rule holds\n * over the row as it would be after it too, so a write cannot move a row out\n * of its writer's reach. Each of its member and `Link` rules holds over the\n * row after with that one change undone (that member's value, or where that\n * relation pointed, as before): the change must be allowed given everything\n * else the write does, so one write cannot set together what each change\n * alone would be refused, while a rule reading its own member (\"only while\n * a draft\") still allows the change. An increment or a computed assignment\n * to a member is that member's own change. An `Unlink` rule holds over the\n * row before alone. A create's rules hold over the values it proposes, where a field the\n * create leaves unset matches no guard, not even one for an empty value. A refusal is\n * `Forbidden`, with the sentence an `explain` gave, or `Unauthenticated` for a\n * visitor; the write never runs.\n *\n * What the Entity sets from the write's context (`Entity.sets`: who asks,\n * when) reaches a create or an update already set by `RemoteServer.write`,\n * so a rule over it holds of the creator. A member rule over such a member\n * judges the server's value like any other: declare none there.\n *\n * `revision` names a field stored as a number, which the writer moves on by\n * one with each write it lands. An update or a delete then lands only on the\n * revision its rules were decided over (the writer's `expect`), so a change\n * between the check and the write is never written over; it is decided\n * again against the row as it now is, up to three times. A change that does\n * not move the revision (a handler's, `applyEdits`', raw SQL) is not seen.\n * Without `revision`, none is, and `validate` warns of an update, or a delete\n * of an Entity the server updates (an insert has no row). An input that expects a\n * revision the row read is not at is a `Conflict`, decided before any rule;\n * an input may expect only the field the writer pins.\n *\n * A delete that cascades (`Relation.one(…, { onDelete: 'cascade' })`) holds\n * each row it takes to that row's own `Delete` rule, for the same person, in\n * the statement that deletes (#348): one refused, and the whole delete is\n * `Forbidden`, naming the Entity, and nothing is removed. A relation declared\n * `authorizedBy: 'parent'` lets whoever may delete the row take the rows\n * pointing at it through that relation unjudged. The rules of an Entity\n * taken under its own are read from its guarded descriptor, given as\n * `children`; one missing is refused where the writer is made.\n *\n * ```ts\n * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))\n * GuardServer.writer(Post, Policy, writer(Db.Post), { children: [Like] })\n * ```\n */\n writer: <E extends AnyEntity, User, R, RW>(\n entity: E,\n policy: Policy<User, R>,\n writer: EntityWriter<Option.Option<User>, RW>,\n options: {\n readonly revision?: keyof E['fields'] & string\n /**\n * The guarded descriptor of each Entity a delete takes rows of under\n * their own `Delete` rule (`authorizedBy: 'child'`), whose rules judge them.\n */\n readonly children?: ReadonlyArray<AnyEntity>\n } = {},\n ): EntityWriter<Option.Option<User>, R | RW> => {\n const revision = options.revision\n if (revision !== undefined) {\n const field = Object.hasOwn(entity.fields, revision)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[revision]\n : undefined\n if (field === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${revision}\" for its revision`,\n )\n }\n // The writer moves it on by one in the statement it writes with, so it is stored as a number.\n if (!SchemaAST.isNumber(Schema.toEncoded(field.schema).ast)) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s revision \"${revision}\" is not stored as a number`,\n )\n }\n }\n if (writer.entity !== entity.name) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s rules over a writer for ${writer.entity}`,\n )\n }\n const read = writer.read\n if (read === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s writer reads no row as its writer may see it; bind it with a visible rule (GuardDrizzle.visible)`,\n )\n }\n // A rule reading another row is judged in the statement that writes: the writer must.\n const reaching = Option.match(enforced(entity), {\n onNone: () => [],\n onSome: attachment => [\n ...new Set([\n ...reachingRules(attachment, 'Update'),\n ...reachingRules(attachment, 'Delete'),\n ]),\n ],\n })\n if (reaching.length > 0 && writer.requires !== true) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s ${reaching.join(', ')} reads another row, which only a writer judging rules in its statement can hold it to (foldkit-remote-drizzle's writer); this writer does not`,\n )\n }\n ;(options.children ?? []).forEach(enforced)\n const judging = cascadeJudges(entity, options.children ?? [])\n if (judging.length > 0 && (writer.requires !== true || writer.cascades !== true)) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: a delete of ${entity.name} takes ${judging.map(child => child.name).join(', ')} rows under their own Delete rule, which only a writer judging rules in its statement and removing what cascades can hold it to (foldkit-remote-drizzle's writer); this writer does not`,\n )\n }\n const clearJudging = clearJudges(entity, options.children ?? [])\n if (clearJudging.length > 0 && (writer.requires !== true || writer.clears !== true)) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: a delete of ${entity.name} clears links of ${clearJudging.map(({ child }) => child.name).join(', ')} rows under their own Update rules, which only a writer judging rules in its statement and clearing links can hold it to (foldkit-remote-drizzle's writer); this writer does not`,\n )\n }\n const used = new Set([\n ...judging.map(child => child.identity.token),\n ...clearJudging.map(({ child }) => child.identity.token),\n ])\n const unused = (options.children ?? []).filter(child => !used.has(child.identity.token))\n if (unused.length > 0)\n throw new Error(\n `[foldkit-guard] GuardServer.writer: a delete of ${entity.name} takes no ${unused.map(child => child.name).join(', ')} rows under their own Delete rule, and clears no link of theirs, so children has nothing to judge them by`,\n )\n /**\n * The row rule over `values` as far as one row decides it: refused where it\n * fails, and otherwise what the writer's statement must still judge.\n */\n const rowRule = (\n rule: RowRule,\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ): Effect.Effect<Option.Option<WriteRequirement>, RemoteForbidden> => {\n const left = Condition.residual(\n rule.condition,\n values,\n policy.inputOf(principal),\n policy.operators,\n )\n return Match.valueTags(left, {\n Always: () => Effect.succeed(Option.none()),\n Never: () => Effect.fail(refused(rule.deny)),\n Row: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n Inherit: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n And: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n Or: () => Effect.succeed(Option.some(required(left, rule.deny, principal))),\n })\n }\n const required = (\n left: Condition,\n deny: Deny,\n principal: Option.Option<User>,\n ): WriteRequirement => ({\n holds: requirementOf(left, policy.inputOf(principal)),\n reason: explained(deny),\n })\n const holds = (\n rule: { readonly condition: Condition },\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Condition.holds(\n rule.condition,\n values,\n policy.inputOf(principal),\n () => false,\n policy.operators,\n )\n /** Fails with the first rule of `rules` that does not hold over `values`. */\n const require = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Option.match(Option.fromUndefinedOr(rules.find(rule => !holds(rule, values, principal))), {\n onNone: () => Effect.void,\n onSome: rule => Effect.fail(refused(rule.deny)),\n })\n type Links = Readonly<\n Record<string, Option.Option<{ readonly entity: string; readonly id: string }>>\n >\n /** Each relation `links` points: its rules for unlinking and for linking a row. */\n const linkRules = (principal: Option.Option<User>, links: Links) =>\n Effect.forEach(Object.entries(links), ([relation, target]) =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Unlink'),\n policy.linkable(entity, principal, relation, 'Link'),\n ]),\n ([unlink, link]) => ({ relation, now: linkKey(target), unlink, link }),\n ),\n )\n /**\n * The rules a change from what each relation was linked to, to what it now\n * points at, must meet; none `before` is a create, which unlinks nothing.\n * Where `exact` is false, `links` are the row as its writer sees it, where\n * a link to a row hidden from them reads as none: a relation seen unlinked\n * may be linked after all, so changing it unlinks too.\n */\n const linking = (\n rules: ReadonlyArray<{\n readonly relation: string\n readonly now: string | null\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n before: Option.Option<{\n readonly links: Readonly<Record<string, unknown>>\n readonly exact: boolean\n }>,\n ): ReadonlyArray<RowRule> =>\n rules.flatMap(({ relation, now, unlink, link }) =>\n Option.match(before, {\n onNone: () => (now === null ? [] : Option.toArray(link)),\n onSome: ({ links, exact }) => {\n const was = links[relation] ?? null\n if (was === now && (exact || was !== null)) return []\n return [\n ...(was === null && exact ? [] : Option.toArray(unlink)),\n ...(now === null ? [] : Option.toArray(link)),\n ]\n },\n }),\n )\n const ruleOf = (\n rules: ReadonlyArray<{\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n ) => rules.flatMap(({ unlink, link }) => [...Option.toArray(unlink), ...Option.toArray(link)])\n const fieldsOf = (\n rules: ReadonlyArray<{ readonly condition: Condition }>,\n more: Iterable<string>,\n ) => [\n ...new Set([\n 'id',\n ...more,\n ...rules.flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n type Expect = Option.Option<{ readonly field: string; readonly revision: unknown }>\n /** The fields that say which version of the row was read: the revision, and the input's. */\n const versionFields = (expect: Expect) => [\n ...(revision === undefined ? [] : [revision]),\n ...Option.match(expect, { onNone: () => [], onSome: ({ field }) => [field] }),\n ]\n /** Whether the row read is not at the revision the input expects. */\n const moved = (expect: Expect, before: Readonly<Record<string, unknown>>) =>\n Option.exists(expect, ({ field, revision }) => !sameStored(before[field], revision))\n /** The write held to the row its rules were decided over, where there is a revision. */\n const pin = (expect: Expect, before: Readonly<Record<string, unknown>>): Expect =>\n revision === undefined ? expect : Option.some({ field: revision, revision: before[revision] })\n /**\n * `attempt` run again while its pinned write misses: the row moved after it\n * was read, so it is decided again over the row as it now is. A write the\n * input pinned misses as a conflict, and is not run again.\n */\n const pinned = <A, E, RA>(\n id: string,\n expect: Expect,\n missed: (outcome: A) => boolean,\n attempt: () => Effect.Effect<A, E, RA>,\n ): Effect.Effect<A, E | RemoteServerError, RA> => {\n if (revision === undefined) return attempt()\n if (Option.isSome(expect)) {\n // The pin is the one revision the write moves on; another would stand still.\n return expect.value.field === revision\n ? attempt()\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s input expects \"${expect.value.field}\", but its writer pins \"${revision}\"`,\n }),\n )\n }\n const loop = (left: number): Effect.Effect<A, E | RemoteServerError, RA> =>\n Effect.flatMap(attempt(), outcome =>\n !missed(outcome)\n ? Effect.succeed(outcome)\n : left > 1\n ? loop(left - 1)\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name} ${id} changed while it was written`,\n }),\n ),\n )\n return loop(3)\n }\n const attachment = enforced(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. So is a write's\n // postcondition reading one, which only the write carrying it names.\n const readsRuled = (held: Invariant): boolean =>\n Option.exists(attachment, ruled =>\n [...held.before, ...held.after].some(key => readRuled(ruled, key)),\n )\n const unnamed = new Set(\n Entity.invariants(entity)\n .filter(readsRuled)\n .map(held => held.id),\n )\n const told =\n (ensures: Invariant | undefined) =>\n <E>(error: E | RemoteInvalid): E | RemoteInvalid =>\n error instanceof RemoteInvalid &&\n Option.exists(\n error.rule,\n rule =>\n unnamed.has(rule) ||\n (ensures !== undefined && rule === ensures.id && readsRuled(ensures)),\n )\n ? RemoteServer.invalid('The row would be invalid')\n : error\n /**\n * Fails a write whose `when` reads, whose `expect` names, or whose\n * computed assignment reads, a member with a Read rule: Unmet or written,\n * Conflict or not, and the computed value answered, would answer for it.\n * `validate` refuses the same at startup; this holds where it was not run.\n */\n const discloses = (\n expect: Expect,\n when: Option.Option<WriteWhen>,\n assignments: UpdateContext['assignments'] = {},\n ): Effect.Effect<void, RemoteServerError> =>\n Option.match(attachment, {\n onNone: () => Effect.void,\n onSome: ruled => {\n const read = Option.match(when, {\n onNone: () => [],\n onSome: ({ body }) => {\n const known = hiddenByBody.get(body)\n if (known !== undefined) return known\n const hidden = hiddenOf(ruled, Query.dependencies(body).predicate)\n hiddenByBody.set(body, hidden)\n return hidden\n },\n })\n const expected = Option.match(expect, {\n onNone: () => [],\n onSome: ({ field }) => (readRuled(ruled, field) ? [field] : []),\n })\n const computed = Write.boundReads({ increments: {}, assignments }).filter(field =>\n readRuled(ruled, field),\n )\n const hidden = [...new Set([...read, ...expected, ...computed])]\n return hidden.length === 0\n ? Effect.void\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write reads ${hidden.join(', ')}, which a Read rule hides from its writer`,\n }),\n )\n },\n })\n /**\n * The answer the writer's ledger holds for this operation, as `answered`\n * makes it, or else `write`: a retry of a write that landed is answered as\n * it landed, not decided again over a row, or a time, that has moved since.\n */\n const answeredOr = <A, E, RA>(\n context: {\n readonly id: string\n readonly operation: Option.Option<string>\n readonly request: string\n readonly principal: Option.Option<User>\n },\n answered: (answer: Readonly<Record<string, unknown>>) => A,\n write: () => Effect.Effect<A, E, RA>,\n ) => {\n const recorded = writer.recorded\n if (recorded === undefined || Option.isNone(context.operation)) return write()\n return Effect.flatMap(\n recorded({\n operation: context.operation.value,\n request: context.request,\n id: context.id,\n principal: context.principal,\n }),\n Option.match({ onSome: answer => Effect.succeed(answered(answer)), onNone: write }),\n )\n }\n // What an answer shows: the row as the writer may see it, members ruled.\n const memberRead = GuardServer.filter(entity, policy)\n // An update, step by step: admitted for what it declares, its rules chosen, the\n // row they read read, the rules decided over it as it is and as it would be, then\n // written pinned to that row. Each step refuses before the next can speak.\n type UpdateContext = Parameters<EntityWriter<Option.Option<User>, RW>['update']>[0]\n interface UpdateRules {\n readonly row: RowRule\n readonly members: ReadonlyArray<MemberRead>\n readonly relating: Effect.Success<ReturnType<typeof linkRules>>\n }\n /** Refused before any rule, for what the write declares rather than what the row holds. */\n const admitUpdate = (context: UpdateContext): Effect.Effect<void, RemoteServerError> =>\n Effect.andThen(discloses(context.expect, context.when, context.assignments), () =>\n // The rules judge a sum over the row read: unpinned, that is not the row written.\n Object.keys(context.increments).length + Object.keys(context.assignments).length > 0 &&\n Option.isNone(context.expect) &&\n revision === undefined\n ? Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write moves a field and expects no revision, and its writer pins none, so its rules would judge a value over a row that may move; give the writer a revision`,\n }),\n )\n : Effect.void,\n )\n /** The rules an update must meet: the row's, each member it sets, each relation it points. */\n const updateRules = (context: UpdateContext) =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Update')\n // A field moved or computed is set as surely as a written one: its Update rule holds.\n const members = yield* policy.writeMembers(\n entity,\n context.principal,\n [\n ...Object.keys(context.values),\n ...Object.keys(context.increments),\n ...Object.keys(context.assignments),\n ],\n 'Update',\n )\n const relating = yield* linkRules(context.principal, context.links)\n return { row, members, relating } satisfies UpdateRules\n })\n /**\n * The row as its writer may see it, with every field the rules and the\n * version read, and those the write's amounts and assignments read to\n * work out the row it leaves.\n */\n const readBefore = (context: UpdateContext, rules: UpdateRules) =>\n read({\n id: context.id,\n fields: fieldsOf(\n [rules.row, ...rules.members, ...ruleOf(rules.relating)],\n [\n ...Object.keys(context.links),\n ...versionFields(context.expect),\n ...Write.boundReads(context),\n // What its rule reads of the row by a path is compared with the row it leaves.\n ...Condition.reachedFrom(rules.row.condition, { entity: entity.name, id: context.id }),\n ],\n ),\n principal: context.principal,\n })\n /**\n * The memory table the row a write leaves is worked out by: the writer's,\n * so the rules judge the value its statement writes, else the policy's.\n */\n const computing = writer.operators ?? policy.operators\n /**\n * The row `context` would leave `before` as. An operator's refusal (text\n * holding NUL, an implementation that throws) is a server error, as the\n * writer answers what it cannot compile: reported here (`ComputeRefused`),\n * and never sent, since an implementation's own message may say anything.\n * So is a field it cannot\n * work out at all: judging its old value would let a rule over it pass.\n */\n const leaves = (before: Readonly<Record<string, unknown>>, context: UpdateContext) =>\n Effect.suspend(() => {\n const unworkable = Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write could not be worked out to judge its rules`,\n }),\n )\n try {\n const applied = Write.apply(before, context, { operators: computing })\n return applied.unknown.length === 0 ? Effect.succeed(applied.row) : unworkable\n } catch (error) {\n if (!(error instanceof QueryEvaluateError)) throw error\n return Diagnostics.report(computeRefused(entity.name, error)).pipe(\n Effect.andThen(unworkable),\n )\n }\n })\n /** The rules, over the row as it is and as the write would leave it. */\n const decideUpdate = (\n context: UpdateContext,\n rules: UpdateRules,\n before: Readonly<Record<string, unknown>>,\n ) =>\n Effect.gen(function* () {\n const { principal, links } = context\n const linked = Object.keys(links)\n const stored =\n writer.linked === undefined || linked.length === 0\n ? Option.none()\n : yield* writer.linked({ id: context.id, relations: linked })\n const was = Option.some(\n Option.match(stored, {\n onNone: () => ({ links: before, exact: false }),\n onSome: links => ({ links, exact: true }),\n }),\n )\n const relations = linking(rules.relating, was)\n // The rules over the row as stored refuse first: a writer they refuse learns\n // nothing of what its input would compute. What the row alone cannot decide\n // of its own rule is the statement's to judge, over the row it writes.\n const requires = yield* rowRule(rules.row, before, principal)\n yield* require([...rules.members, ...relations], before, principal)\n // What the writer will store, over the row read, which the pin keeps as the row\n // written: `Write.apply`'s, as the writer works it out.\n const after = {\n ...(yield* leaves(before, context)),\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n // Over the row it leaves, a rule reading another row is the statement's too,\n // which judges the stored row: so a write may not change what such a rule\n // reads of its own row, the one difference between the two.\n const leaving = yield* rowRule(rules.row, after, principal)\n if (Option.isSome(leaving)) {\n const read = Condition.reachedFrom(\n Condition.residual(\n rules.row.condition,\n after,\n policy.inputOf(principal),\n policy.operators,\n ),\n { entity: entity.name, id: context.id },\n )\n if (read.some(key => !sameStored(before[key], after[key]))) {\n return yield* Effect.fail(refused(rules.row.deny))\n }\n }\n // Each member's rule and each link's also over the row it leaves with that one\n // change undone: may it change, given all else the write does. Over the row before\n // alone, one write could set together what each change alone may not; over the\n // whole row after, \"only while a draft\" would refuse leaving the draft. An unlink is\n // of the row before, which the row after no longer points from.\n const undone = [\n ...rules.members.map(rule => ({ rule, key: rule.member })),\n ...rules.relating.flatMap(rule =>\n linking([{ ...rule, unlink: Option.none() }], was).map(link => ({\n rule: link,\n key: rule.relation,\n })),\n ),\n ]\n yield* Effect.forEach(\n undone,\n ({ rule, key }) => require([rule], { ...after, [key]: before[key] }, principal),\n { discard: true },\n )\n return requires\n })\n const guarded: EntityWriter<Option.Option<User>, R | RW> = {\n entity: writer.entity,\n // The precondition is the writer's to check, in the statement that writes.\n ...(writer.preconditions === true ? { preconditions: true } : {}),\n ...(writer.increments === true ? { increments: true } : {}),\n ...(writer.assignments === true ? { assignments: true } : {}),\n // With a revision every update lands over the row its rules read. Without one an\n // unpinned move is refused, so what the writer would say commutes is not passed on.\n ...(revision === undefined ? {} : { pins: true }),\n ...(writer.ledger === true ? { ledger: true } : {}),\n // Invariants are the writer's to judge, over the row its statement writes.\n ...(writer.invariants === true ? { invariants: true } : {}),\n // So is a write's postcondition, which reaches the writer in the context it is handed.\n ...(writer.postconditions === true ? { postconditions: true } : {}),\n // The rows a delete takes with it are the writer's to remove; the guard judges the row named.\n ...(writer.cascades === true ? { cascades: true } : {}),\n // So is refusing a row still pointed at, which only someone the rules let delete it learns.\n ...(writer.restricts === true ? { restricts: true } : {}),\n // So is clearing a link to it; the guard hands over each such row's Update rules.\n ...(writer.clears === true ? { clears: true } : {}),\n // What the store refuses, the store knows: the guard drops none of its reasons. It\n // adds one: its rules judge the row the write leaves, worked out by the policy's\n // table, so an assignment that table cannot run would be judged as its old value.\n refuses: write => [\n ...(writer.refuses?.(write) ?? []),\n ...write.assignments.flatMap(({ field, expr }) =>\n Expr.unsupported([expr], { operations: supported, operators: computing }).map(\n missing =>\n `its assignment to \"${field.key}\" calls ${missing}, which the guard cannot work out`,\n ),\n ),\n // Refused per request too (`admitUpdate`), for a caller that registers none.\n ...((write.increments.length > 0 || write.assignments.length > 0) &&\n write.expect === undefined &&\n revision === undefined\n ? [\n 'it moves a field and expects no revision, and the guarded writer pins none, so its rules would judge a value over a row that may move; give the writer a revision',\n ]\n : []),\n ],\n ...(writer.recorded === undefined ? {} : { recorded: writer.recorded }),\n read: ({ id, fields, principal }) =>\n seenRow(\n { filter: memberRead },\n seen => read({ id, fields: seen, principal }),\n principal,\n fields,\n id,\n ),\n update: context =>\n Effect.mapError(\n Effect.andThen(admitUpdate(context), () =>\n answeredOr(context, Option.some, () =>\n pinned(context.id, context.expect, Option.isNone, () =>\n Effect.gen(function* () {\n const rules = yield* updateRules(context)\n const current = yield* readBefore(context, rules)\n if (Option.isNone(current)) return yield* Effect.fail(refused(rules.row.deny))\n if (moved(context.expect, current.value)) return Option.none()\n const requires = yield* decideUpdate(context, rules, current.value)\n return yield* writer.update({\n ...context,\n expect: pin(context.expect, current.value),\n ...Option.match(requires, {\n onNone: () => ({}),\n onSome: held => ({ requires: held }),\n }),\n })\n }),\n ),\n ),\n ),\n told(context.ensures),\n ),\n insert: context =>\n answeredOr(context, identity, () =>\n Effect.gen(function* () {\n const { principal, values, links } = context\n const row = yield* policy.writable(entity, principal, 'Create')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n Object.keys(values),\n 'Create',\n )\n const relations = linking(yield* linkRules(principal, links), Option.none())\n const proposed = {\n ...values,\n id: context.id,\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n const rules = [row, ...members, ...relations]\n const ruled = rules.flatMap(({ condition }) => Condition.members(condition))\n const unset = new Set(ruled.filter(field => !Object.hasOwn(proposed, field)))\n yield* require(rules.map(rule => ({\n ...rule,\n condition: Condition.unsetting(rule.condition, unset),\n })), proposed, principal)\n return yield* Effect.mapError(writer.insert(context), told(context.ensures))\n }),\n ),\n delete: context =>\n Effect.andThen(discloses(context.expect, context.when), () =>\n pinned(context.id, context.expect, DeleteOutcome.$is('Moved'), () =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Delete')\n const current = yield* read({\n id: context.id,\n fields: fieldsOf([row], versionFields(context.expect)),\n principal: context.principal,\n })\n // Hidden or gone, the writer sees no row: there is nothing of theirs to delete.\n if (Option.isNone(current)) return DeleteOutcome.Absent()\n if (moved(context.expect, current.value)) return DeleteOutcome.Moved()\n const requires = yield* rowRule(row, current.value, context.principal)\n // Each row the cascade takes under its own rule, judged by the writer over the\n // rows as they are when it deletes, before it removes any.\n const cascading = yield* Effect.forEach(judging, child =>\n Effect.map(\n policy.writable(child, context.principal, 'Delete'),\n ({ condition, deny }): CascadeRequirement => ({\n entity: child.name,\n requires: required(condition, deny, context.principal),\n }),\n ),\n )\n // Each row whose link the delete clears, judged as an update unlinking it is:\n // the row's Update rule and the relation's Unlink rule, both of them.\n const clearing = yield* Effect.forEach(clearJudging, ({ child, relations }) =>\n Effect.gen(function* () {\n const row = yield* policy.writable(child, context.principal, 'Update')\n const unlinks = yield* Effect.forEach(relations, relation =>\n policy.linkable(child, context.principal, relation, 'Unlink'),\n )\n const rules = [row, ...unlinks.flatMap(Option.toArray)]\n const each = rules.map(rule =>\n required(rule.condition, rule.deny, context.principal),\n )\n return {\n entity: child.name,\n requires: {\n holds: RowRequirement.All({ of: each.map(({ holds }) => holds) }),\n reason: Option.firstSomeOf(each.map(({ reason }) => reason)),\n },\n } satisfies CascadeRequirement\n }),\n )\n return yield* writer.delete({\n ...context,\n expect: pin(context.expect, current.value),\n ...Option.match(requires, {\n onNone: () => ({}),\n onSome: held => ({ requires: held }),\n }),\n ...(judging.length === 0 ? {} : { cascading }),\n ...(clearJudging.length === 0 ? {} : { clearing }),\n })\n }),\n ),\n ),\n }\n const asked: EntityWriter<Option.Option<User>, R | RW> = {\n ...guarded,\n update: context => signInFirst(context.principal, guarded.update(context)),\n insert: context => signInFirst(context.principal, guarded.insert(context)),\n delete: context => signInFirst(context.principal, guarded.delete(context)),\n }\n pins.set(asked, Option.fromUndefinedOr(revision))\n return writeRules.add(asked, policy, [entity])\n },\n\n /**\n * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for\n * `interaction` checked before it runs. The row the input names (`id`) is\n * read through `source`, which must apply the Entity's Read rules, and the\n * rule must hold over it; a row its writer may not see is refused. With no\n * `id` (a create), the rule must hold of who is asking alone, a field it\n * reads matching no guard. `run` is given the row as read: its fields the\n * rule reads, its `id`, and `fields`. A refusal is `Forbidden`, or\n * `Unauthenticated` for a visitor; `run` never runs. What `run` writes is its own: check members it sets there. Each\n * row of `entity` its answer carries is read back through `source`, so the\n * answer shows its writer only what they may see, a row it hid from them\n * as deleted.\n *\n * A rule for `interaction` that reads another row (a path, an exists) is\n * refused here, where the handler is made: this check reads one row and\n * runs no statement. A declared write through `GuardServer.writer` is held\n * to such a rule.\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 // The check reads one row through `source` and runs no statement: a rule reading\n // another row would be judged by nothing, so it is refused here, not per request.\n const reaching = Option.match(enforced(entity), {\n onNone: () => [],\n onSome: attachment => reachingRules(attachment, interaction),\n })\n if (reaching.length > 0) {\n throw new Error(\n `[foldkit-guard] GuardServer.mutation: ${mutation.name} is checked against ${entity.name}'s ${interaction} rule, whose ${reaching.join(', ')} reads another row (a path or an exists), which a handler's check over the one row it reads cannot judge; declare the write (Mutation.write) and land it through GuardServer.writer over a writer that judges rules in its statement (foldkit-remote-drizzle's writer), or check ${interaction} by a rule over the row alone`,\n )\n }\n if (!rowRules.has(source.visible, policy, entity)) {\n throw new Error(\n `[foldkit-guard] GuardServer.mutation: ${mutation.name}'s Source does not apply ${entity.name}'s Read rules`,\n )\n }\n /**\n * The answer as its writer may now see it: each row of `entity` it carries\n * read back through `source`, and one the handler hid from them deleted.\n */\n const shown = (outcome: MutationOutcome<Output>, principal: Option.Option<User>) =>\n Effect.map(\n Effect.forEach(outcome.entities ?? [], patch =>\n patch.entity !== entity.name\n ? Effect.succeed(Option.some(patch))\n : Effect.map(\n seenRow(\n source,\n fields =>\n Effect.map(rowOf(source, principal, fields, patch.id), Option.fromUndefinedOr),\n principal,\n Object.keys(patch.values),\n patch.id,\n ),\n Option.map(seen => ({ ...patch, values: seen })),\n ),\n ),\n read => ({\n ...outcome,\n entities: read.flatMap(Option.toArray),\n deleted: [\n ...(outcome.deleted ?? []),\n ...(outcome.entities ?? [])\n .filter((_, index) => Option.isNone(read[index]!))\n .map(({ entity, id }) => ({ entity, id })),\n ],\n }),\n )\n return RemoteServer.mutation<Option.Option<User>, R | RS | RM, Name, Input, Output, Refused>(\n mutation,\n context =>\n Effect.gen(function* () {\n const { principal } = context\n // `context.input` was decoded against the mutation's Input before this runs.\n const target = Option.flatMap(Option.fromUndefinedOr(id), of => {\n const named = of(context.input)\n return typeof named === 'string' ? Option.some(named) : named\n })\n const rule = yield* policy.writable(\n entity,\n principal,\n id !== undefined && Option.isNone(target) ? 'Create' : interaction,\n )\n const ruled = Condition.members(rule.condition)\n const input = policy.inputOf(principal)\n if (Option.isNone(target)) {\n const unset = Condition.unsetting(rule.condition, new Set(ruled))\n if (!Condition.holds(unset, {}, input, () => false, policy.operators)) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row: Option.none() }), principal)\n }\n const fields = [...new Set(['id', ...ruled, ...(guard.fields ?? [])])]\n const row = Option.fromUndefinedOr(yield* rowOf(source, principal, fields, target.value))\n if (\n Option.isNone(row) ||\n !Condition.holds(rule.condition, row.value, input, () => false, policy.operators)\n ) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row }), principal)\n }).pipe(answered => signInFirst(context.principal, answered)),\n )\n },\n\n /**\n * Checks, at startup, that `server` applies the guards of `entities`, the\n * Entities as `Guards.attach` returned them: each one's Source and each\n * query listing it apply its row's Read rules (`GuardDrizzle.visible`, or\n * `GuardServer.memory`), its Source applies its members' and relations'\n * (`GuardServer.filter`), and each declared write of it lands through\n * `GuardServer.writer`, all built from `policy`; and that no query's body\n * filters or orders by a member with a Read rule, its own or one of a row it\n * reaches through a path or an exists, which would answer for the value it\n * hides. A hand-written Source over a guarded Entity would serve\n * every row, and a bare writer would take every write; this throws instead,\n * naming each. A handler (`RemoteServer.mutation`) writes what its code\n * writes, which no check at startup can read. A write a change can come\n * between, through a writer given no revision, is not refused but reported:\n * `UnpinnedWrites`, a warning, to `diagnostics`.\n *\n * ```ts\n * GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })\n * ```\n */\n validate: <User, R>(\n policy: Policy<User, R>,\n config: {\n readonly entities: ReadonlyArray<AnyEntity>\n /** The Remote domain the server answers, for which Entity each query lists. */\n readonly domain: {\n readonly registry: {\n readonly queries: ReadonlyMap<\n string,\n { readonly Result: unknown; readonly body?: AnyQuery | undefined }\n >\n }\n }\n readonly server: ServerDefinition<any, any>\n /** Where the `UnpinnedWrites` warning goes; `Diagnostics.Reporter`'s default, the log, when not given. */\n readonly diagnostics?: ReportDiagnostic | undefined\n },\n ): void => {\n const byName = new Map(config.entities.map(entity => [entity.name, entity]))\n /** Whether a reached member has a Read rule; one of an Entity not validated has none checked. */\n const hidesFromReach = ({ entity, key }: ReachedMember) =>\n Option.exists(\n Option.flatMap(Option.fromUndefinedOr(byName.get(entity)), enforced),\n attachment => readRuled(attachment, key),\n )\n /** Whether who may read the rows of `entity` depends on who is asking. */\n const rowsRuled = (entity: AnyEntity | undefined) =>\n Option.exists(Option.flatMap(Option.fromUndefinedOr(entity), enforced), 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(enforced(entity), {\n onNone: () => [],\n onSome: attachment => {\n const name = entity.name\n if (attachment.set !== policy.set) {\n return [`${name} carries the guards of ${attachment.set}, not ${policy.set}`]\n }\n // Every guarded Entity's, whether or not it has rules there yet: a rule\n // attached later is then applied, not served past.\n const source = Option.fromUndefinedOr(config.server.entities.get(name))\n const sourceProblems = Option.match(source, {\n onNone: () => [],\n onSome: ({ visible, filter }) => [\n ...(rowRules.has(visible, policy, entity)\n ? []\n : [`${name}'s Source does not apply its Read rules`]),\n ...(memberRules.has(filter, policy, entity)\n ? []\n : [`${name}'s Source does not apply its members' Read rules`]),\n ],\n })\n const queryProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, query]) => {\n const listed = config.server.queries.get(queryName)\n return listed !== undefined &&\n lists(query.Result, name) &&\n !rowRules.has(listed.visible, policy, entity)\n ? [`query ${queryName} lists ${name} without its Read rules`]\n : []\n },\n )\n // A row the reader may see with a member it may not still answers a\n // filter or an order on that member: `cost < $max`, halved twenty\n // times, reads the cost the row came back without.\n const bodyProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, { body }]) => {\n if (body === undefined || body.entity.name !== name) return []\n const { predicate, order, reaches } = Query.dependencies(body)\n const reached = [\n ...new Set(\n reachedMembers(reaches)\n .filter(hidesFromReach)\n .map(\n ({ entity, key }) =>\n `query ${queryName} reaches ${entity}'s ${key}, which has a Read rule`,\n ),\n ),\n ]\n return [\n ...hiddenOf(attachment, predicate).map(\n member =>\n `query ${queryName} filters ${name} by ${member}, which has a Read rule`,\n ),\n ...hiddenOf(attachment, order).map(\n member => `query ${queryName} orders ${name} by ${member}, which has a Read rule`,\n ),\n ...reached,\n ]\n },\n )\n const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => {\n if (source.writes === undefined || source.writes.entity !== name) return []\n if (!writeRules.has(source.writes.writer, policy, entity)) {\n return [`write ${mutation} writes ${name} without its write rules`]\n }\n const { write, writer } = source.writes\n const interaction = Match.valueTags(write, {\n Insert: () => 'Create',\n Update: () => 'Update',\n Delete: () => 'Delete',\n })\n // Left without a rule under 'allow', a served write is anyone's: that is\n // written down as `Guards.anyone`, never left to a forgotten rule.\n const open =\n attachment.unguarded === 'allow' &&\n Option.isNone(surfaceOf(attachment, { _tag: 'Row', interaction }))\n ? [\n `write ${mutation} ${interaction === 'Create' ? 'creates' : `${interaction.toLowerCase()}s`} ${name}, which has no ${interaction} rule, so unguarded: 'allow' lets anyone; give it one, or [Guards.anyone] to say anyone may`,\n ]\n : []\n // Unmet or written, Conflict or not, answers for a member its writer may not read.\n const when = Option.match(write.when, {\n onNone: () => [],\n onSome: body => hiddenOf(attachment, Query.dependencies(body).predicate),\n })\n const computed = write.assignments.flatMap(assignment =>\n hiddenOf(attachment, dependenciesOf(assignment.expr).fields).map(\n member =>\n `write ${mutation} computes ${name}'s ${assignment.field.key} from its ${member}, which has a Read rule`,\n ),\n )\n const expected = write.expect?.field.key\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n return [\n ...open,\n ...when.map(\n member =>\n `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`,\n ),\n ...computed,\n ...(expected !== undefined && readRuled(attachment, expected)\n ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`]\n : []),\n ...(expected !== undefined &&\n pin !== undefined &&\n Option.exists(pin, field => field !== expected)\n ? [\n `write ${mutation} expects ${name}'s ${expected}, but its writer pins ${Option.getOrThrow(pin)}`,\n ]\n : []),\n ]\n })\n // A shared field goes to every live subscriber as written: no rule may tell them apart.\n const shared: ReadonlyArray<string> = Option.match(source, {\n onNone: () => [],\n onSome: source => [...(source.shared ?? [])],\n })\n const sharedProblems = [\n ...(shared.length > 0 && readRowsRuled(attachment)\n ? [`${name}'s Source shares ${shared.join(', ')}, but its rows have a Read rule`]\n : []),\n // Each reader's own answer, whoever may read the row.\n ...(shared.includes('may') && asksMay(entity, ['may'])\n ? [`${name}'s Source shares may, which is answered for each reader`]\n : []),\n ...shared.flatMap(member => {\n const own = readRuled(attachment, member)\n ? [`${name}'s Source shares ${member}, which has a Read rule`]\n : []\n if (!Object.hasOwn(entity.relations, member)) return own\n const target = entity.relations[member]!.target().name\n if (!byName.has(target))\n return [\n ...own,\n `${name}'s Source shares ${member}, whose ${target} is not validated`,\n ]\n return rowsRuled(byName.get(target))\n ? [...own, `${name}'s Source shares ${member}, whose rows have a Read rule`]\n : own\n }),\n ]\n // A rule calling an operator the policy's table does not run would fail when\n // asked, so the server does not start with one (expr-operations-DESIGN §5.6).\n const operatorProblems = attachedRules(attachment).flatMap(rule =>\n Match.value(rule).pipe(\n Match.tag('RowGuard', guard =>\n Query.unsupported(guard.query, supported, policy.operators).map(\n missing =>\n `${name}'s ${guard.name} calls ${missing}, which the policy does not run`,\n ),\n ),\n Match.orElse(() => []),\n ),\n )\n // A live Source sends what it reads: only one reading through the Source\n // checked above is known to send what a read would.\n const live = Option.fromUndefinedOr(config.server.live.get(name))\n const liveProblems = Option.exists(\n live,\n ({ reads }) => !Option.exists(source, checked => checked === reads),\n )\n ? [\n `${name}'s live Source does not read through its guarded Source; poll through that Source (pollLive) or serve changes through a live hub`,\n ]\n : []\n return [\n ...sourceProblems,\n ...queryProblems,\n ...bodyProblems,\n ...writeProblems,\n ...sharedProblems,\n ...operatorProblems,\n ...liveProblems,\n ]\n },\n }),\n )\n const problems = [...undeclared, ...entityProblems]\n if (problems.length > 0) {\n throw new Error(`[foldkit-guard] GuardServer.validate: ${problems.join('; ')}`)\n }\n // Not refused yet: a writer given no revision is how every writer was made before it.\n // Named only where a change between the check and the write can happen: an update\n // always, a delete where the server updates that Entity, an insert, with no row, never.\n const updated = new Set(\n [...config.server.mutations.values()]\n .flatMap(source => (source.writes === undefined ? [] : [source.writes]))\n .filter(writes => writes.write._tag === 'Update')\n .map(writes => writes.entity),\n )\n const unpinned = [...config.server.mutations].flatMap(([mutation, source]) => {\n const writes = source.writes\n if (writes === undefined) return []\n const writer = writes.writer\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n if (pin === undefined || Option.isSome(pin)) return []\n const races = Match.valueTags(writes.write, {\n Update: () => true,\n Delete: () => updated.has(writes.entity),\n Insert: () => false,\n })\n return races ? [mutation] : []\n })\n if (unpinned.length > 0) {\n // A startup check runs before any Effect of the server's, so the reporter is an option.\n const report = Diagnostics.report(unpinnedWrites(unpinned))\n const { diagnostics } = config\n Effect.runFork(\n diagnostics === undefined\n ? report\n : Effect.provideService(report, Diagnostics.Reporter, diagnostics),\n )\n }\n },\n}\n\n/**\n * `entities`, refused where one's Read rule reads another row: a memory\n * server's `readable` judges each stored row alone and runs no statement, so\n * such a rule would fail every read of the Entity.\n */\nconst readingOneRow = (entities: ReadonlyArray<AnyEntity>): ReadonlyArray<AnyEntity> => {\n for (const entity of entities) {\n const reaching = Option.match(enforced(entity), {\n onNone: () => [],\n onSome: attachment => reachingRules(attachment, 'Read'),\n })\n if (reaching.length > 0) {\n throw new Error(\n `[foldkit-guard] GuardServer.memory: ${entity.name}'s Read rule's ${reaching.join(', ')} reads another row (a path or an exists), which a memory server, judging each stored row alone, cannot judge; serve ${entity.name} from a table whose statement judges it (GuardDrizzle.visible), or rule Read over the row alone`,\n )\n }\n }\n return entities\n}\n\n/** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */\nconst asksMay = (entity: AnyEntity, fields: ReadonlyArray<string>) =>\n fields.includes('may') && Object.hasOwn(entity.derived, 'may')\n\n/** How one principal's `may` is answered: the fields its rules read, and the answer over a row. */\ninterface MayPlan {\n readonly fields: ReadonlyArray<string>\n readonly answer: (values: Readonly<Record<string, unknown>>) => MayAnswer\n}\n\n/**\n * `may` for `principal`: each row interaction's rule, each member's own\n * `Update`, each relation's `Link` and `Unlink`, decided once and held over\n * each row as a write's check would hold them over it as it is.\n */\nconst mayOf = <User, R>(\n entity: AnyEntity,\n policy: Policy<User, R>,\n principal: Option.Option<User>,\n): Effect.Effect<MayPlan, never, R> =>\n Effect.map(\n mayRules(entity, {\n // A named one was attached as an `InteractionKey`; its key is the name.\n row: interaction => policy.writable(entity, principal, interaction as InteractionKey),\n members: members => policy.writeMembers(entity, principal, members, 'Update'),\n relation: (relation, interaction) =>\n policy.linkable(entity, principal, relation, interaction),\n }),\n (rules): MayPlan => {\n const input = policy.inputOf(principal)\n return {\n // `id` too, so a row is read when its rules read none of it (an admin's).\n fields: ['id', ...new Set(mayConditions(rules).flatMap(Condition.members))],\n // A rule reading another row is the write's statement's to judge: not answered here.\n answer: values =>\n answerOf(rules, condition =>\n Condition.decided(Condition.residual(condition, values, input, policy.operators)),\n ),\n }\n },\n )\n\n/** A refused write as the client receives it: the sentence an `explain` gave, or none. */\n/** The words a refusal gives: an `explain`'s, or none. */\nconst explained = (deny: Deny): Option.Option<string> =>\n Match.valueTags(deny, {\n Explain: ({ reason }) => Option.some(reason),\n Forbidden: () => Option.none(),\n NotFound: () => Option.none(),\n Omit: () => Option.none(),\n Redact: () => Option.none(),\n })\n\n/**\n * The guarded descriptor of each Entity a delete of `root`'s row takes rows of\n * under their own `Delete` rule (`authorizedBy: 'child'`), followed through\n * every cascade, `root` itself for a cascade into its own Entity. Refused\n * where one is not among `children`, and where a child is given that no\n * such cascade reaches, so the option cannot quietly say nothing.\n */\nconst cascadeJudges = (\n root: AnyEntity,\n children: ReadonlyArray<AnyEntity>,\n): ReadonlyArray<AnyEntity> => {\n const given = new Map(children.map(child => [child.identity.token, child]))\n given.set(root.identity.token, root)\n const judged = new Map<symbol, AnyEntity>()\n const seen = new Set([root.identity.token])\n const queue: Array<AnyEntity> = [root]\n for (let next = queue.shift(); next !== undefined; next = queue.shift())\n for (const { relation, owner } of Entity.cascading(next)) {\n const token = owner.identity.token\n const own = Option.getOrElse(relation.authorizedBy, () => 'child' as const) === 'child'\n if (own && !judged.has(token)) {\n const guarded = given.get(token)\n if (guarded === undefined)\n throw new Error(\n `[foldkit-guard] GuardServer.writer: a delete of ${root.name} takes ${owner.name} rows under their own Delete rule (${owner.name}.${relation.key}); give ${owner.name}'s guarded Entity as children: [${owner.name}], or declare the relation authorizedBy: 'parent'`,\n )\n judged.set(token, guarded)\n }\n if (!seen.has(token)) {\n seen.add(token)\n queue.push(owner)\n }\n }\n return [...judged.values()]\n}\n\n/**\n * The guarded descriptor of each Entity whose link a delete of `root`'s row\n * clears (`onDelete: 'setNull'`, #467), with the relations it clears: each\n * such row is held to its own `Update` rules over the link. Refused where one\n * is not among `children`.\n */\nconst clearJudges = (\n root: AnyEntity,\n children: ReadonlyArray<AnyEntity>,\n): ReadonlyArray<{ readonly child: AnyEntity; readonly relations: ReadonlyArray<string> }> => {\n const given = new Map(children.map(child => [child.identity.token, child]))\n given.set(root.identity.token, root)\n const judged = new Map<symbol, { child: AnyEntity; relations: Array<string> }>()\n for (const { relation, owner } of Entity.clearing(root)) {\n const token = owner.identity.token\n const guarded = given.get(token)\n if (guarded === undefined)\n throw new Error(\n `[foldkit-guard] GuardServer.writer: a delete of ${root.name} clears ${owner.name}.${relation.key} under ${owner.name}'s own Update rules; give ${owner.name}'s guarded Entity as children: [${owner.name}]`,\n )\n const known = judged.get(token) ?? { child: guarded, relations: [] }\n known.relations.push(relation.key)\n judged.set(token, known)\n }\n return [...judged.values()]\n}\n\n/**\n * What is left of a condition, as a writer's statement judges it: each row\n * guard a body over the row, its input the principal's (`G.inputOf`), and its\n * context the one it was decided for. An inherited Read, which a writer\n * refuses, requires what no row holds.\n */\nconst requirementOf = (\n condition: Condition,\n input: Readonly<Record<string, unknown>>,\n): RowRequirement =>\n Match.valueTags(condition, {\n Always: () => RowRequirement.All({ of: [] }),\n Never: () => RowRequirement.Any({ of: [] }),\n Row: ({ guard, context }) => RowRequirement.Body({ query: guard.query, input, context }),\n Inherit: () => RowRequirement.Any({ of: [] }),\n And: ({ conditions }) =>\n RowRequirement.All({ of: conditions.map(each => requirementOf(each, input)) }),\n Or: ({ conditions }) =>\n RowRequirement.Any({ of: conditions.map(each => requirementOf(each, input)) }),\n })\n\n/**\n * A visitor's refused write as a sign-in it needs: `Unauthenticated`, never\n * `Forbidden`, so a client tells a session that ended (its cookie gone, it\n * asks as a visitor) from a person refused, and a durable write waits for the\n * sign-in rather than failing (#403). A refusal's words go with it.\n */\nconst signInFirst = <User, A, E, R>(\n principal: Option.Option<User>,\n write: Effect.Effect<A, E, R>,\n): Effect.Effect<A, E | RemoteUnauthenticated, R> =>\n Option.isSome(principal)\n ? write\n : Effect.mapError(write, error =>\n error instanceof RemoteForbidden ? RemoteServer.unauthenticated(error.reason) : error,\n )\n\nconst refused = (deny: Deny) =>\n Match.valueTags(deny, {\n Explain: ({ reason }) => RemoteServer.forbid(reason),\n Forbidden: () => RemoteServer.forbid(),\n NotFound: () => RemoteServer.forbid(),\n Omit: () => RemoteServer.forbid(),\n Redact: () => RemoteServer.forbid(),\n })\n\n/** One row, by id, as `principal` may read it through `source`. */\nconst rowOf = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n) =>\n Effect.map(\n source.read({ ids: [id], fields: [...fields], principal }),\n records => records.find(record => record.id === id)?.values,\n )\n\n/**\n * Row `id` of `fields` as `principal` may see it, through `see`'s `authorize`\n * and `filter` as a Source applies them, and no more than was asked: what an\n * answer shows its writer. None when the row is not there to them.\n */\nconst seenRow = <P, R, RS>(\n see: Pick<EntitySource<P, RS>, 'authorize' | 'filter'>,\n read: (\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n): Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R | RS> =>\n Effect.gen(function* () {\n const allowed = see.authorize === undefined ? fields : see.authorize(principal, [...fields])\n const plan: ReadPlan =\n see.filter === undefined\n ? { fields: allowed, apply: noMembers }\n : yield* see.filter(principal, allowed)\n // The id too: a row asked for nothing else is still there or not.\n const row = yield* read([...new Set(['id', ...plan.fields])])\n return Option.map(row, values => {\n const shown = plan.apply({ id, values }).values\n return Object.fromEntries(\n allowed.filter(field => Object.hasOwn(shown, field)).map(field => [field, shown[field]]),\n )\n })\n })\n\n/** A link's value as a row holds it: the ref's key, or `null` for none. */\nconst linkKey = (link: Option.Option<{ readonly entity: string; readonly id: string }>) =>\n Option.match(link, { onNone: () => null, onSome: ref => `${ref.entity}:${ref.id}` })\n\n/** Whether a query's result is a connection over `entity`. */\nconst lists = (result: unknown, entity: string): boolean =>\n typeof result === 'object' && result !== null && 'entity' in result && result.entity === entity\n"],"mappings":";;;;;;;;;;AAOA,MAAM,SAAS;AA0Bf,MAAa,kBAAkB,QAAgB,WAAkC;CAC/E,MAAM;CACN;CACA,OAAO;CACP,SAAS,GAAG,OAAO,qEAAqE,MAAM,QAAQ;CACtG;CACA;AACF;AAEA,MAAa,kBAAkB,eAAsD;CACnF,MAAM;CACN;CACA,OAAO;CACP,SAAS,yBAAyB,UAAU,KAAK,IAAI,EAAE,GAAG,UAAU,WAAW,IAAI,WAAW,QAAQ;CACtG;AACF;;;;;;;;;ACkBA,MAAM,aAAa,WAAyB;;AAG5C,MAAM,cAAc,MAAe,UACjC,KAAK,UAAU,IAAI,MAAM,KAAK,UAAU,KAAK;;AAG/C,MAAM,YACJ,YACA,WAC0B,CAC1B,GAAG,IAAI,IAAI,OAAO,KAAI,UAAS,MAAM,GAAG,CAAC,CAAC,QAAO,QAAO,UAAU,YAAY,GAAG,CAAC,CAAC,CACrF;;;;;;;AAcA,MAAM,kBACJ,YAEA,QAAQ,SAAQ,YAAW;CACzB,MAAM,MAAM,QAAQ,IAAI,KAAI,cAAa;EAAE,QAAQ,SAAS,MAAM;EAAM,KAAK,SAAS;CAAI,EAAE;CAC5F,OAAO,MAAM,UAAU,SAAS;EAC9B,OAAO,EAAE,YAAY,CAAC,GAAG,KAAK;GAAE,QAAQ,MAAM,MAAM;GAAM,KAAK,MAAM;EAAI,CAAC;EAC1E,aAAa,EAAE,YAAY,CAAC,GAAG,KAAK;GAAE,QAAQ,MAAM,MAAM;GAAM,KAAK,MAAM;EAAI,CAAC;EAChF,SAAS,EAAE,UAAU,YAAY;GAC/B,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MAAM;CAAG;AAAU,CAAC,IACzD,YAAW,QAAQ,MAAK,WAAU,OAAO,OAAO,EAAE,CAAC,EAAE,MACvD;;;;;;AAOF,MAAM,WACJ,KACA,MAGA,WACA,QACA,OAEA,OAAO,IAAI,aAAa;CACtB,MAAM,UAAU,IAAI,cAAc,KAAA,IAAY,SAAS,IAAI,UAAU,WAAW,CAAC,GAAG,MAAM,CAAC;CAC3F,MAAM,OACJ,IAAI,WAAW,KAAA,IACX;EAAE,QAAQ;EAAS,OAAO;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/dist/sync.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { C as PrincipalGuard, S as Policy } from "./attach-CJl-GtbN.mjs";
1
+ import { C as PrincipalGuard, S as Policy } from "./attach-CER19mzk.mjs";
2
2
  import { Effect, Option } from "effect";
3
3
  import { AnyEntity } from "foldkit-entity";
4
4
  import { EntitySource } from "foldkit-remote-server";
@@ -22,8 +22,10 @@ export declare const GuardSync: {
22
22
  * field of the Entity, a member with a Read rule
23
23
  * of its own (its value would reach a reader the rule hides it from), a
24
24
  * reader the row's Read rule does not name (it would receive edits to rows
25
- * it cannot read), a guarded row with no readers, and `always` rules that
26
- * read the row (no reader could be shown to pass them).
25
+ * it cannot read), a guarded row with no readers, `always` rules that
26
+ * read the row (no reader could be shown to pass them), and an `Update`
27
+ * rule that reads another row (an edit is admitted over the one row read,
28
+ * by no statement).
27
29
  *
28
30
  * ```ts
29
31
  * const Edits = GuardSync.document(ProductEdits, { readers: [G.isStaff] })
@@ -1 +1 @@
1
- {"version":3,"file":"sync.d.mts","names":[],"sources":["../src/sync.ts"],"mappings":";;;;;;iBAyBiB;WACN;WACA;WACA;;;iBAIM,gBAAgB;WACtB,QAAQ;WACR,SAAS;WACT,SAAS,cAAc,eAAe;;qBAqCpC;;;;;;;;;;;;;;EAcX,WAAW,MAAI;aACK,QAAQ;aAAoB,SAAS;KAAuB;aAC1D,SAAS,cAAc,eAAe;QACzD,gBAAgB;;;;;;EAsCnB,QAAQ,MAAI,QACF,OAAO,OAAK,UACV,gBAAgB,OAAK,WACpB,OAAO,OAAO,UACxB,OAAO;;;;;;;;;;;EA2BV,YACG,MAAI,QAAU,OAAO,OAAK,UAAY,gBAAgB,WAAK;aAEjD,WAAW,OAAO,OAAO;aACzB;eAAoB,SAAS,cAAc;;QAClD;;;;;;;;;;;;;;;;EA8BN,QACG,MAAM,GAAC,QACE,OAAO,OAAK,UACV,gBAAgB,OAAK;aAEpB,WAAW,OAAO,OAAO;aACzB,QAAQ,aAAa,OAAO,OAAO,OAAO;aAC1C,YAAY,WAAW,cAAc,cAAc;SAC7D,WAES,cAAY,OAAO,OAAO,4BAA4B"}
1
+ {"version":3,"file":"sync.d.mts","names":[],"sources":["../src/sync.ts"],"mappings":";;;;;;iBAyBiB;WACN;WACA;WACA;;;iBAIM,gBAAgB;WACtB,QAAQ;WACR,SAAS;WACT,SAAS,cAAc,eAAe;;qBAqCpC;;;;;;;;;;;;;;;;EAgBX,WAAW,MAAI;aACK,QAAQ;aAAoB,SAAS;KAAuB;aAC1D,SAAS,cAAc,eAAe;QACzD,gBAAgB;;;;;;EA4CnB,QAAQ,MAAI,QACF,OAAO,OAAK,UACV,gBAAgB,OAAK,WACpB,OAAO,OAAO,UACxB,OAAO;;;;;;;;;;;EA2BV,YACG,MAAI,QAAU,OAAO,OAAK,UAAY,gBAAgB,WAAK;aAEjD,WAAW,OAAO,OAAO;aACzB;eAAoB,SAAS,cAAc;;QAClD;;;;;;;;;;;;;;;;EA8BN,QACG,MAAM,GAAC,QACE,OAAO,OAAK,UACV,gBAAgB,OAAK;aAEpB,WAAW,OAAO,OAAO;aACzB,QAAQ,aAAa,OAAO,OAAO,OAAO;aAC1C,YAAY,WAAW,cAAc,cAAc;SAC7D,WAES,cAAY,OAAO,OAAO,4BAA4B"}
package/dist/sync.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { d as surfaceOf, r as attached, s as isAnyone, u as restricts } from "./attach-CEGlbWu5.mjs";
2
- import { t as Condition } from "./condition-dNSbUHzE.mjs";
1
+ import { c as isAnyone, m as surfaceOf, o as enforced, p as restricts, u as reachingRules } from "./attach-DlrBpxOl.mjs";
2
+ import { t as Condition } from "./condition-VNIr9gDe.mjs";
3
3
  import { Effect, Match, Option, Schema } from "effect";
4
4
  // src/sync.ts
5
5
  /**
@@ -46,8 +46,10 @@ const GuardSync = {
46
46
  * field of the Entity, a member with a Read rule
47
47
  * of its own (its value would reach a reader the rule hides it from), a
48
48
  * reader the row's Read rule does not name (it would receive edits to rows
49
- * it cannot read), a guarded row with no readers, and `always` rules that
50
- * read the row (no reader could be shown to pass them).
49
+ * it cannot read), a guarded row with no readers, `always` rules that
50
+ * read the row (no reader could be shown to pass them), and an `Update`
51
+ * rule that reads another row (an edit is admitted over the one row read,
52
+ * by no statement).
51
53
  *
52
54
  * ```ts
53
55
  * const Edits = GuardSync.document(ProductEdits, { readers: [G.isStaff] })
@@ -59,7 +61,7 @@ const GuardSync = {
59
61
  throw new Error(`[foldkit-guard] GuardSync.document of ${entity.name}: ${why}`);
60
62
  };
61
63
  for (const member of members) if (!Object.hasOwn(entity.fields, member)) fail(`${member} is not a field of it`);
62
- Option.map(attached(entity), (attachment) => {
64
+ Option.map(enforced(entity), (attachment) => {
63
65
  for (const member of members) if (restricts(surfaceOf(attachment, {
64
66
  _tag: "Member",
65
67
  member,
@@ -74,6 +76,8 @@ const GuardSync = {
74
76
  for (const reader of options.readers) if (!read.value.rules.some((rule) => rule._tag === "PrincipalGuard" && rule.name === reader.name && rule.set === reader.set)) fail(`${reader.name} is not in its rows' Read rule, so may not read them`);
75
77
  }
76
78
  if (attachment.always.some((rule) => rule._tag !== "PrincipalGuard" && !isAnyone(rule))) fail("its `always` rules read the row, which no reader can be shown to pass");
79
+ const reaching = reachingRules(attachment, "Update");
80
+ if (reaching.length > 0) fail(`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`);
77
81
  });
78
82
  return Object.freeze({
79
83
  entity,
@@ -87,7 +91,7 @@ const GuardSync = {
87
91
  * `journalExchange`'s `opens`.
88
92
  */
89
93
  opens: (policy, document, principal) => {
90
- const always = Option.match(attached(document.entity), {
94
+ const always = Option.match(enforced(document.entity), {
91
95
  onNone: () => [],
92
96
  onSome: ({ always }) => always.filter((rule) => rule._tag === "PrincipalGuard")
93
97
  });