foldkit-guard 0.3.1 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +73 -7
- package/dist/agent.d.mts +1 -3
- package/dist/agent.d.mts.map +1 -1
- package/dist/agent.mjs +2 -3
- package/dist/{attach-BVG6LsFf.d.mts → attach-BnP9_Uca.d.mts} +18 -15
- package/dist/attach-BnP9_Uca.d.mts.map +1 -0
- package/dist/{attach-BZyVvs7H.mjs → attach-CRCF5XHS.mjs} +16 -4
- package/dist/attach-CRCF5XHS.mjs.map +1 -0
- package/dist/{condition-Dunujvzy.mjs → condition-Bl1UgEpM.mjs} +6 -6
- package/dist/condition-Bl1UgEpM.mjs.map +1 -0
- package/dist/drizzle.d.mts +8 -5
- package/dist/drizzle.d.mts.map +1 -1
- package/dist/drizzle.mjs +11 -14
- package/dist/drizzle.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +12 -11
- package/dist/index.mjs.map +1 -1
- package/dist/{may-DK-2lomO.mjs → may-DzCAt_5M.mjs} +2 -3
- package/dist/{may-DK-2lomO.mjs.map → may-DzCAt_5M.mjs.map} +1 -1
- package/dist/{me-DeSZOGt3.mjs → me-BYpuVqJE.mjs} +4 -5
- package/dist/{me-DeSZOGt3.mjs.map → me-BYpuVqJE.mjs.map} +1 -1
- package/dist/media.d.mts +1 -3
- package/dist/media.d.mts.map +1 -1
- package/dist/media.mjs +1 -2
- package/dist/{origin-CN6ThFTp.mjs → origin-igJoiz74.mjs} +2 -3
- package/dist/{origin-CN6ThFTp.mjs.map → origin-igJoiz74.mjs.map} +1 -1
- package/dist/{placed-CkyMqxFw.mjs → placed-BvdNmZJu.mjs} +4 -5
- package/dist/{placed-CkyMqxFw.mjs.map → placed-BvdNmZJu.mjs.map} +1 -1
- package/dist/server.d.mts +12 -3
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +211 -67
- package/dist/server.mjs.map +1 -1
- package/dist/sync.d.mts +1 -3
- package/dist/sync.d.mts.map +1 -1
- package/dist/sync.mjs +4 -5
- package/dist/sync.mjs.map +1 -1
- package/package.json +14 -14
- package/dist/attach-BVG6LsFf.d.mts.map +0 -1
- package/dist/attach-BZyVvs7H.mjs.map +0 -1
- package/dist/condition-Dunujvzy.mjs.map +0 -1
package/dist/server.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.mjs","names":[],"sources":["../src/server.ts"],"sourcesContent":["/**\n * A guard set's read rules as `foldkit-remote-server`'s seams: an\n * `EntitySource.filter` from each member's Read rule, and `RemoteServer.memory`'s\n * `readable` and `filter` from the row's, and a check at startup that a server\n * applies them. A subpath, so the shared declaration the browser imports never\n * brings the server along.\n */\nimport { Effect, Match, Option, Schema } from 'effect'\nimport { Query, type AnyEntity, type AnyQuery } from 'foldkit-entity'\nimport type { MutationDescriptor, RemoteForbidden } from 'foldkit-remote'\nimport {\n RemoteServer,\n RemoteServerError,\n type EntityRecord,\n type EntitySource,\n type EntityWriter,\n type MutationOutcome,\n type MutationRefused,\n type MutationSource,\n type MemoryReadable,\n type ReadPlan,\n type ServerDefinition,\n} from 'foldkit-remote-server'\nimport { attached, readRowsRuled, readRuled, type Deny, type InteractionKey } from './attach.js'\nimport { Condition, type RowRule } from './condition.js'\nimport type { Policy } from './index.js'\nimport type { MayAnswer } from './may.js'\nimport { ME, type MeEntity } from './me.js'\nimport { memberRules, rowRules, writeRules } from './placed.js'\n\nconst noMembers = (record: EntityRecord) => record\n\n/** A ref key's two halves, `Entity:id`; `none` for anything else. */\nconst refOf = (value: unknown): Option.Option<{ readonly entity: string; readonly id: string }> => {\n if (typeof value !== 'string') return Option.none()\n const split = value.indexOf(':')\n return split <= 0\n ? Option.none()\n : Option.some({ entity: value.slice(0, split), id: value.slice(split + 1) })\n}\n\nexport const GuardServer = {\n /**\n * `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`\n * answered by `policy`. `signedIn` is whether the server answered as\n * someone; `key` is their `key`. Any other id is no row.\n *\n * ```ts\n * RemoteServer.make({ entities: [GuardServer.me(Me, Policy), …] })\n * ```\n */\n me: <User, R>(\n entity: MeEntity,\n policy: Policy<User, R>,\n ): EntitySource<Option.Option<User>, R> => {\n // Otherwise every read would die deciding another set's guards.\n Option.map(attached(entity), ({ set }) => {\n if (set !== policy.set) {\n throw new Error(\n `[foldkit-guard] GuardServer.me: Me carries the guards of ${set}, not ${policy.set}`,\n )\n }\n })\n return {\n ...RemoteServer.entity<Option.Option<User>, R>(entity, {\n read: ({ ids, principal }) =>\n Effect.succeed(\n ids\n .filter(id => id === ME)\n .map(id => ({\n id,\n values: {\n signedIn: Option.isSome(principal),\n // Encoded, as a Source answers: `null` for a visitor.\n key: Option.match(principal, {\n onNone: () => null,\n onSome: policy.key,\n }),\n },\n })),\n ),\n filter: GuardServer.filter(entity, policy),\n }),\n // Its Read rule as this Source applies it: only the asker's own row,\n // which `Guards.me` lets anyone read. One per call: the registry is keyed\n // by it, and another call is for another Policy.\n visible: rowRules.add(Object.freeze({ reads: 'the asker’s own row' }), policy, [entity]),\n }\n },\n\n /**\n * An `EntitySource.filter` for `entity`: each requested member with a Read\n * rule is decided per record, omitted or redacted where the rule refuses.\n * The fields a rule reads are read too, so it can be decided.\n *\n * ```ts\n * RemoteServer.entity(Todo, { read, filter: GuardServer.filter(Todo, Policy) })\n * ```\n */\n filter: <User, R>(entity: AnyEntity, policy: Policy<User, R>) =>\n memberRules.add(\n (\n principal: Option.Option<User>,\n fields: readonly string[],\n ): Effect.Effect<ReadPlan, never, R> =>\n Effect.map(\n Effect.all([\n policy.readMembers(entity, principal, fields),\n // `may` is answered here, where the row is read as its principal sees it.\n asksMay(entity, fields)\n ? Effect.map(mayOf(entity, policy, principal), Option.some)\n : Effect.succeed(Option.none<MayPlan>()),\n ]),\n ([members, may]): ReadPlan => {\n if (members.length === 0 && Option.isNone(may)) return { fields, apply: noMembers }\n const input = policy.inputOf(principal)\n const decided = members.map(member => ({\n ...member,\n // A redacted value is a decoded one; the record holds what the store holds.\n redacted:\n member.deny._tag === 'Redact'\n ? Option.some(\n Schema.encodeSync(\n (\n entity.members as Readonly<\n Record<string, { readonly schema: Schema.Top }>\n >\n )[member.member]!.schema as unknown as Schema.Codec<unknown, unknown>,\n )(member.deny.value),\n )\n : Option.none(),\n }))\n return {\n fields: [\n ...new Set([\n ...fields,\n ...members.flatMap(({ condition }) => Condition.members(condition)),\n ...Option.match(may, { onNone: () => [], onSome: ({ fields }) => fields }),\n ]),\n ],\n apply: record => {\n const values: Record<string, unknown> = { ...record.values }\n for (const { member, condition, redacted } of decided) {\n // Member rules carry no inherited Read: only a row's Read may inherit.\n if (Condition.holds(condition, record.values, input, () => false)) continue\n Option.match(redacted, {\n onNone: () => {\n delete values[member]\n },\n onSome: value => {\n values[member] = value\n },\n })\n }\n Option.map(may, ({ answer }) => {\n values.may = answer(record.values)\n })\n return { id: record.id, values }\n },\n }\n },\n ),\n policy,\n [entity],\n ),\n\n /**\n * `RemoteServer.memory`'s `readable` and `filter` for `entities`, the\n * Entities as `Guards.attach` returned them. A row's Read is decided per\n * stored row, an inherited Read by looking the related row up; an Entity\n * not listed is read by everyone.\n */\n memory: <User>(policy: Policy<User>, entities: ReadonlyArray<AnyEntity>) => ({\n readable: rowRules.add(\n (\n principal: Option.Option<User>,\n row: (entity: string, id: string) => Option.Option<Readonly<Record<string, unknown>>>,\n ): Effect.Effect<MemoryReadable> =>\n Effect.map(\n Effect.forEach(entities, entity =>\n Effect.map(\n policy.readable(entity, principal),\n condition => [entity.name, condition] as const,\n ),\n ),\n (decided): MemoryReadable => {\n const conditions = new Map(decided)\n const input = policy.inputOf(principal)\n // `seen` stops a cycle of inherited Reads, which would otherwise never end.\n const holds = (\n entity: string,\n values: Readonly<Record<string, unknown>>,\n seen: ReadonlySet<string>,\n ): boolean => {\n const condition = conditions.get(entity)\n if (condition === undefined) return true\n return Condition.holds(condition, values, input, relation =>\n Option.match(refOf(values[relation]), {\n onNone: () => false,\n onSome: ref => {\n const key = `${ref.entity}:${ref.id}`\n if (seen.has(key)) return false\n return Option.match(row(ref.entity, ref.id), {\n onNone: () => false,\n onSome: target => holds(ref.entity, target, new Set([...seen, key])),\n })\n },\n }),\n )\n }\n return (entity, values) => holds(entity, values, new Set())\n },\n ),\n policy,\n entities,\n ),\n filter: Object.fromEntries(\n entities.map(entity => [entity.name, GuardServer.filter(entity, policy)] as const),\n ),\n }),\n\n /**\n * `writer` with `entity`'s write rules checked before each write lands, for\n * `RemoteServer.write`. An update or a delete reads the row first under\n * the writer's own `read` (its Source's read rule): a row the writer may not\n * see is refused as one that is not there, and a delete of it changes\n * nothing. Then the row's rule for the command must hold over the row (an\n * update's over the row as it would be after it too, so a write cannot move\n * a row out of its writer's reach), each member it sets must allow setting\n * it, and each relation it points elsewhere must allow the unlink and the\n * link. A create's rules hold over the values it proposes, where a field the\n * create leaves unset matches no guard, not even one for an empty value. A refusal is\n * `Forbidden`, with the sentence an `explain` gave; the write never runs.\n *\n * `presets` are fields a create takes from who is asking, never from the\n * client (`ownerId: user => user.id`): set before the rules are checked, so\n * a rule over them holds of the creator. A visitor has nothing to preset\n * from, and a create whose input sets a preset field is a mistake of the\n * server's, refused.\n *\n * ```ts\n * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))\n * ```\n */\n writer: <E extends AnyEntity, User, R, RW>(\n entity: E,\n policy: Policy<User, R>,\n writer: EntityWriter<Option.Option<User>, RW>,\n options: {\n readonly presets?: {\n readonly [K in keyof E['fields']]?: (user: User) => E['fields'][K]['schema']['Type']\n }\n } = {},\n ): EntityWriter<Option.Option<User>, R | RW> => {\n const presets = Object.entries(options.presets ?? {}).map(([field, preset]) => {\n const declared = Object.hasOwn(entity.fields, field)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[field]\n : undefined\n if (declared === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${field}\" to preset`,\n )\n }\n const encode = Schema.encodeUnknownSync(\n declared.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n return { field, value: (user: User) => encode((preset as (user: User) => unknown)(user)) }\n })\n if (writer.entity !== entity.name) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s rules over a writer for ${writer.entity}`,\n )\n }\n const read = writer.read\n if (read === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s writer reads no row as its writer may see it; bind it with a visible rule (GuardDrizzle.visible)`,\n )\n }\n const holds = (\n rule: { readonly condition: Condition },\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) => Condition.holds(rule.condition, values, policy.inputOf(principal), () => false)\n /** Fails with the first rule of `rules` that does not hold over `values`. */\n const require = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\n Option.match(Option.fromUndefinedOr(rules.find(rule => !holds(rule, values, principal))), {\n onNone: () => Effect.void,\n onSome: rule => Effect.fail(refused(rule.deny)),\n })\n type Links = Readonly<\n Record<string, Option.Option<{ readonly entity: string; readonly id: string }>>\n >\n /** Each relation `links` points: its rules for unlinking and for linking a row. */\n const linkRules = (principal: Option.Option<User>, links: Links) =>\n Effect.forEach(Object.entries(links), ([relation, target]) =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Unlink'),\n policy.linkable(entity, principal, relation, 'Link'),\n ]),\n ([unlink, link]) => ({ relation, now: linkKey(target), unlink, link }),\n ),\n )\n /**\n * The rules a change from what each relation was linked to, to what it now\n * points at, must meet; none `before` is a create, which unlinks nothing.\n * Where `exact` is false, `links` are the row as its writer sees it, where\n * a link to a row hidden from them reads as none: a relation seen unlinked\n * may be linked after all, so changing it unlinks too.\n */\n const linking = (\n rules: ReadonlyArray<{\n readonly relation: string\n readonly now: string | null\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n before: Option.Option<{\n readonly links: Readonly<Record<string, unknown>>\n readonly exact: boolean\n }>,\n ): ReadonlyArray<RowRule> =>\n rules.flatMap(({ relation, now, unlink, link }) =>\n Option.match(before, {\n onNone: () => (now === null ? [] : Option.toArray(link)),\n onSome: ({ links, exact }) => {\n const was = links[relation] ?? null\n if (was === now && (exact || was !== null)) return []\n return [\n ...(was === null && exact ? [] : Option.toArray(unlink)),\n ...(now === null ? [] : Option.toArray(link)),\n ]\n },\n }),\n )\n const ruleOf = (\n rules: ReadonlyArray<{\n readonly unlink: Option.Option<RowRule>\n readonly link: Option.Option<RowRule>\n }>,\n ) => rules.flatMap(({ unlink, link }) => [...Option.toArray(unlink), ...Option.toArray(link)])\n const fieldsOf = (\n rules: ReadonlyArray<{ readonly condition: Condition }>,\n more: Iterable<string>,\n ) => [\n ...new Set([\n 'id',\n ...more,\n ...rules.flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n // What an answer shows: the row as the writer may see it, members ruled.\n const memberRead = GuardServer.filter(entity, policy)\n const guarded: EntityWriter<Option.Option<User>, R | RW> = {\n entity: writer.entity,\n read: ({ id, fields, principal }) =>\n seenRow(\n { filter: memberRead },\n seen => read({ id, fields: seen, principal }),\n principal,\n fields,\n id,\n ),\n update: context =>\n Effect.gen(function* () {\n const { principal, values, links } = context\n const row = yield* policy.writable(entity, principal, 'Update')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n Object.keys(values),\n 'Update',\n )\n const relating = yield* linkRules(principal, links)\n const fields = fieldsOf([row, ...members, ...ruleOf(relating)], Object.keys(links))\n const current = yield* read({ id: context.id, fields, principal })\n if (Option.isNone(current)) return yield* Effect.fail(refused(row.deny))\n const before = current.value\n const linked = Object.keys(links)\n const stored =\n writer.linked === undefined || linked.length === 0\n ? Option.none()\n : yield* writer.linked({ id: context.id, relations: linked })\n const relations = linking(\n relating,\n Option.some(\n Option.match(stored, {\n onNone: () => ({ links: before, exact: false }),\n onSome: links => ({ links, exact: true }),\n }),\n ),\n )\n const after = {\n ...before,\n ...values,\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n yield* require([row, ...members, ...relations], before, principal)\n yield* require([row], after, principal)\n return yield* writer.update(context)\n }),\n insert: given =>\n Effect.gen(function* () {\n const preset = presets.find(({ field }) => Object.hasOwn(given.values, field))\n if (preset !== undefined) {\n return yield* new RemoteServerError({\n message: `${entity.name}'s \"${preset.field}\" is preset by the server; the input may not set it`,\n })\n }\n if (presets.length > 0 && Option.isNone(given.principal)) {\n return yield* Effect.fail(RemoteServer.forbid())\n }\n const context = Option.match(given.principal, {\n onNone: () => given,\n onSome: user => ({\n ...given,\n values: {\n ...given.values,\n ...Object.fromEntries(presets.map(({ field, value }) => [field, value(user)])),\n },\n }),\n })\n const { principal, values, links } = context\n const row = yield* policy.writable(entity, principal, 'Create')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n Object.keys(values),\n 'Create',\n )\n const relations = linking(yield* linkRules(principal, links), Option.none())\n const proposed = {\n ...values,\n id: context.id,\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n const rules = [row, ...members, ...relations]\n const ruled = rules.flatMap(({ condition }) => Condition.members(condition))\n const unset = new Set(ruled.filter(field => !Object.hasOwn(proposed, field)))\n yield* require(rules.map(rule => ({\n ...rule,\n condition: Condition.unsetting(rule.condition, unset),\n })), proposed, principal)\n return yield* writer.insert(context)\n }),\n delete: context =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Delete')\n const current = yield* read({\n id: context.id,\n fields: fieldsOf([row], []),\n principal: context.principal,\n })\n // Hidden or gone, the writer sees no row: there is nothing of theirs to delete.\n if (Option.isNone(current)) return 'absent' as const\n yield* require([row], current.value, context.principal)\n return yield* writer.delete(context)\n }),\n }\n return writeRules.add(guarded, policy, [entity])\n },\n\n /**\n * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for\n * `interaction` checked before it runs. The row the input names (`id`) is\n * read through `source`, which must apply the Entity's Read rules, and the\n * rule must hold over it; a row its writer may not see is refused. With no\n * `id` (a create), the rule must hold of who is asking alone, a field it\n * reads matching no guard. `run` is given the row as read: its fields the\n * rule reads, its `id`, and `fields`. A refusal is `Forbidden`; `run` never\n * runs. What `run` writes is its own: check members it sets there. Each\n * row of `entity` its answer carries is read back through `source`, so the\n * answer shows its writer only what they may see, a row it hid from them\n * as deleted.\n *\n * ```ts\n * GuardServer.mutation(ArchiveTodo, {\n * entity: Todo, policy: Policy, interaction: Archive.key,\n * id: input => input.id, source: source(Db.Todo),\n * }, ({ input, row }) => …)\n * ```\n */\n mutation: <User, R, RS, RM, Name extends string, Input, Output, Refused>(\n mutation: MutationDescriptor<Name, Input, Output, Refused>,\n guard: {\n readonly entity: AnyEntity\n readonly policy: Policy<User, R>\n readonly interaction: 'Create' | 'Update' | 'Delete' | InteractionKey\n /**\n * The row the input acts on; none for a create. An input whose id may be\n * absent (`Option`, as one editor's for create and edit) creates when it\n * is, checked against `Create`.\n */\n readonly id?: ((input: Input) => string | Option.Option<string>) | undefined\n /** Reads the row as its writer may see it: the Entity's guarded Source. */\n readonly source: EntitySource<Option.Option<User>, RS>\n /** More of the row for `run`, beside what the rule reads. */\n readonly fields?: ReadonlyArray<string> | undefined\n },\n run: (context: {\n readonly input: Input\n readonly principal: Option.Option<User>\n readonly requestId: string\n readonly row: Option.Option<Readonly<Record<string, unknown>>>\n }) => Effect.Effect<\n MutationOutcome<Output>,\n RemoteServerError | MutationRefused | RemoteForbidden,\n RM\n >,\n ): MutationSource<Option.Option<User>, R | RS | RM> => {\n const { entity, policy, interaction, id, source } = guard\n if (!rowRules.has(source.visible, policy, entity)) {\n throw new Error(\n `[foldkit-guard] GuardServer.mutation: ${mutation.name}'s Source does not apply ${entity.name}'s Read rules`,\n )\n }\n /**\n * The answer as its writer may now see it: each row of `entity` it carries\n * read back through `source`, and one the handler hid from them deleted.\n */\n const shown = (outcome: MutationOutcome<Output>, principal: Option.Option<User>) =>\n Effect.map(\n Effect.forEach(outcome.entities ?? [], patch =>\n patch.entity !== entity.name\n ? Effect.succeed(Option.some(patch))\n : Effect.map(\n seenRow(\n source,\n fields =>\n Effect.map(rowOf(source, principal, fields, patch.id), Option.fromUndefinedOr),\n principal,\n Object.keys(patch.values),\n patch.id,\n ),\n Option.map(seen => ({ ...patch, values: seen })),\n ),\n ),\n read => ({\n ...outcome,\n entities: read.flatMap(Option.toArray),\n deleted: [\n ...(outcome.deleted ?? []),\n ...(outcome.entities ?? [])\n .filter((_, index) => Option.isNone(read[index]!))\n .map(({ entity, id }) => ({ entity, id })),\n ],\n }),\n )\n return RemoteServer.mutation<Option.Option<User>, R | RS | RM, Name, Input, Output, Refused>(\n mutation,\n context =>\n Effect.gen(function* () {\n const { principal } = context\n // `context.input` was decoded against the mutation's Input before this runs.\n const target = Option.flatMap(Option.fromUndefinedOr(id), of => {\n const named = of(context.input)\n return typeof named === 'string' ? Option.some(named) : named\n })\n const rule = yield* policy.writable(\n entity,\n principal,\n id !== undefined && Option.isNone(target) ? 'Create' : interaction,\n )\n const ruled = Condition.members(rule.condition)\n const input = policy.inputOf(principal)\n if (Option.isNone(target)) {\n const unset = Condition.unsetting(rule.condition, new Set(ruled))\n if (!Condition.holds(unset, {}, input, () => false)) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row: Option.none() }), principal)\n }\n const fields = [...new Set(['id', ...ruled, ...(guard.fields ?? [])])]\n const row = Option.fromUndefinedOr(yield* rowOf(source, principal, fields, target.value))\n if (\n Option.isNone(row) ||\n !Condition.holds(rule.condition, row.value, input, () => false)\n ) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row }), principal)\n }),\n )\n },\n\n /**\n * Checks, at startup, that `server` applies the guards of `entities`, the\n * Entities as `Guards.attach` returned them: each one's Source and each\n * query listing it apply its row's Read rules (`GuardDrizzle.visible`, or\n * `GuardServer.memory`), its Source applies its members' and relations'\n * (`GuardServer.filter`), and each declared write of it lands through\n * `GuardServer.writer`, all built from `policy`; and that no query's body\n * filters or orders by a member with a Read rule, which would answer for the\n * value it hides. A hand-written Source over a guarded Entity would serve\n * every row, and a bare writer would take every write; this throws instead,\n * naming each. A handler (`RemoteServer.mutation`) writes what its code\n * writes, which no check at startup can read.\n *\n * ```ts\n * GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })\n * ```\n */\n validate: <User, R>(\n policy: Policy<User, R>,\n config: {\n readonly entities: ReadonlyArray<AnyEntity>\n /** The Remote domain the server answers, for which Entity each query lists. */\n readonly domain: {\n readonly registry: {\n readonly queries: ReadonlyMap<\n string,\n { readonly Result: unknown; readonly body?: AnyQuery | undefined }\n >\n }\n }\n readonly server: ServerDefinition<any, any>\n },\n ): void => {\n const byName = new Map(config.entities.map(entity => [entity.name, entity]))\n /** Whether who may read the rows of `entity` depends on who is asking. */\n const rowsRuled = (entity: AnyEntity | undefined) =>\n Option.exists(Option.flatMap(Option.fromUndefinedOr(entity), attached), attachment =>\n readRowsRuled(attachment),\n )\n // A query the domain does not declare lists an Entity no one can name.\n const undeclared = [...config.server.queries.keys()]\n .filter(query => !config.domain.registry.queries.has(query))\n .map(query => `query ${query} is served, but the domain does not declare it`)\n const entityProblems = config.entities.flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => {\n const name = entity.name\n if (attachment.set !== policy.set) {\n return [`${name} carries the guards of ${attachment.set}, not ${policy.set}`]\n }\n // Every guarded Entity's, whether or not it has rules there yet: a rule\n // attached later is then applied, not served past.\n const source = Option.fromUndefinedOr(config.server.entities.get(name))\n const sourceProblems = Option.match(source, {\n onNone: () => [],\n onSome: ({ visible, filter }) => [\n ...(rowRules.has(visible, policy, entity)\n ? []\n : [`${name}'s Source does not apply its Read rules`]),\n ...(memberRules.has(filter, policy, entity)\n ? []\n : [`${name}'s Source does not apply its members' Read rules`]),\n ],\n })\n const queryProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, query]) => {\n const listed = config.server.queries.get(queryName)\n return listed !== undefined &&\n lists(query.Result, name) &&\n !rowRules.has(listed.visible, policy, entity)\n ? [`query ${queryName} lists ${name} without its Read rules`]\n : []\n },\n )\n // A row the reader may see with a member it may not still answers a\n // filter or an order on that member: `cost < $max`, halved twenty\n // times, reads the cost the row came back without.\n const bodyProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, { body }]) => {\n if (body === undefined || body.entity.name !== name) return []\n const { predicate, order } = Query.dependencies(body)\n const hidden = (fields: typeof predicate) => [\n ...new Set(\n fields.map(field => field.key).filter(key => readRuled(attachment, key)),\n ),\n ]\n return [\n ...hidden(predicate).map(\n member =>\n `query ${queryName} filters ${name} by ${member}, which has a Read rule`,\n ),\n ...hidden(order).map(\n member => `query ${queryName} orders ${name} by ${member}, which has a Read rule`,\n ),\n ]\n },\n )\n const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) =>\n source.writes !== undefined &&\n source.writes.entity === name &&\n !writeRules.has(source.writes.writer, policy, entity)\n ? [`write ${mutation} writes ${name} without its write rules`]\n : [],\n )\n // A shared field goes to every live subscriber as written: no rule may tell them apart.\n const shared = Option.match(source, {\n onNone: () => [],\n onSome: source => [...(source.shared ?? [])],\n })\n const sharedProblems = [\n ...(shared.length > 0 && readRowsRuled(attachment)\n ? [`${name}'s Source shares ${shared.join(', ')}, but its rows have a Read rule`]\n : []),\n ...shared.flatMap(member => {\n const own = readRuled(attachment, member)\n ? [`${name}'s Source shares ${member}, which has a Read rule`]\n : []\n if (!Object.hasOwn(entity.relations, member)) return own\n const target = entity.relations[member]!.target().name\n if (!byName.has(target))\n return [\n ...own,\n `${name}'s Source shares ${member}, whose ${target} is not validated`,\n ]\n return rowsRuled(byName.get(target))\n ? [...own, `${name}'s Source shares ${member}, whose rows have a Read rule`]\n : own\n }),\n ]\n // A live Source of its own streams whatever it reads: nothing here can check it.\n const liveProblems = config.server.live.has(name)\n ? [`${name} has a live Source of its own; serve its changes through a live hub`]\n : []\n return [\n ...sourceProblems,\n ...queryProblems,\n ...bodyProblems,\n ...writeProblems,\n ...sharedProblems,\n ...liveProblems,\n ]\n },\n }),\n )\n const problems = [...undeclared, ...entityProblems]\n if (problems.length > 0) {\n throw new Error(`[foldkit-guard] GuardServer.validate: ${problems.join('; ')}`)\n }\n },\n}\n\n/** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */\nconst asksMay = (entity: AnyEntity, fields: ReadonlyArray<string>) =>\n fields.includes('may') && Object.hasOwn(entity.derived, 'may')\n\n/** How one principal's `may` is answered: the fields its rules read, and the answer over a row. */\ninterface MayPlan {\n readonly fields: ReadonlyArray<string>\n readonly answer: (values: Readonly<Record<string, unknown>>) => MayAnswer\n}\n\n/** The interactions a row answers `may` for: `Update`, `Delete`, and each one the set named. */\nconst builtInRow = new Set(['Read', 'Create', 'Update', 'Delete'])\n\n/**\n * `may` for `principal`: each row interaction's rule, each member's own\n * `Update`, each relation's `Link` and `Unlink`, decided once and held over\n * each row as a write's check would hold them over it as it is.\n */\nconst mayOf = <User, R>(\n entity: AnyEntity,\n policy: Policy<User, R>,\n principal: Option.Option<User>,\n): Effect.Effect<MayPlan, never, R> => {\n const attachment = attached(entity)\n const named = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ row }) => Object.keys(row).filter(interaction => !builtInRow.has(interaction)),\n })\n const ruledMembers = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ members }) => Object.keys(members),\n })\n const ruledRelations = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ relations }) => Object.keys(relations),\n })\n return Effect.map(\n Effect.all([\n Effect.forEach(['Update', 'Delete', ...named], interaction =>\n Effect.map(\n // A named one was attached as an `InteractionKey`; its key is the name.\n policy.writable(entity, principal, interaction as InteractionKey),\n rule => [interaction, rule] as const,\n ),\n ),\n policy.writeMembers(entity, principal, ruledMembers, 'Update'),\n Effect.forEach(ruledRelations, relation =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Link'),\n policy.linkable(entity, principal, relation, 'Unlink'),\n ]),\n ([link, unlink]) => ({ relation, link, unlink }),\n ),\n ),\n ]),\n ([rows, members, relations]): MayPlan => {\n const input = policy.inputOf(principal)\n const holds = (condition: Condition, values: Readonly<Record<string, unknown>>) =>\n Condition.holds(condition, values, input, () => false)\n // A relation without a rule for one direction leaves it to the row's Update.\n const allows = (rule: Option.Option<RowRule>, values: Readonly<Record<string, unknown>>) =>\n Option.match(rule, {\n onNone: () => true,\n onSome: ({ condition }) => holds(condition, values),\n })\n const conditions = [\n ...rows.map(([, { condition }]) => condition),\n ...members.map(({ condition }) => condition),\n ...relations.flatMap(({ link, unlink }) =>\n [...Option.toArray(link), ...Option.toArray(unlink)].map(({ condition }) => condition),\n ),\n ]\n return {\n // `id` too, so a row is read when its rules read none of it (an admin's).\n fields: ['id', ...new Set(conditions.flatMap(Condition.members))],\n answer: values => ({\n row: Object.fromEntries(\n rows.map(([interaction, { condition }]) => [interaction, holds(condition, values)]),\n ),\n // Only an `explain`'s sentence is for whoever asked.\n reasons: Object.fromEntries(\n rows.flatMap(([interaction, { condition, deny }]) =>\n holds(condition, values)\n ? []\n : Match.valueTags(deny, {\n Explain: ({ reason }) => [[interaction, reason] as const],\n Forbidden: () => [],\n NotFound: () => [],\n Omit: () => [],\n Redact: () => [],\n }),\n ),\n ),\n members: Object.fromEntries(\n members.map(({ member, condition }) => [member, holds(condition, values)]),\n ),\n relations: Object.fromEntries(\n relations.map(({ relation, link, unlink }) => [\n relation,\n { Link: allows(link, values), Unlink: allows(unlink, values) },\n ]),\n ),\n }),\n }\n },\n )\n}\n\n/** A refused write as the client receives it: the sentence an `explain` gave, or none. */\nconst refused = (deny: Deny) =>\n Match.valueTags(deny, {\n Explain: ({ reason }) => RemoteServer.forbid(reason),\n Forbidden: () => RemoteServer.forbid(),\n NotFound: () => RemoteServer.forbid(),\n Omit: () => RemoteServer.forbid(),\n Redact: () => RemoteServer.forbid(),\n })\n\n/** One row, by id, as `principal` may read it through `source`. */\nconst rowOf = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n) =>\n Effect.map(\n source.read({ ids: [id], fields: [...fields], principal }),\n records => records.find(record => record.id === id)?.values,\n )\n\n/**\n * Row `id` of `fields` as `principal` may see it, through `see`'s `authorize`\n * and `filter` as a Source applies them, and no more than was asked: what an\n * answer shows its writer. None when the row is not there to them.\n */\nconst seenRow = <P, R, RS>(\n see: Pick<EntitySource<P, RS>, 'authorize' | 'filter'>,\n read: (\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n): Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R | RS> =>\n Effect.gen(function* () {\n const allowed = see.authorize === undefined ? fields : see.authorize(principal, [...fields])\n const plan: ReadPlan =\n see.filter === undefined\n ? { fields: allowed, apply: noMembers }\n : yield* see.filter(principal, allowed)\n // The id too: a row asked for nothing else is still there or not.\n const row = yield* read([...new Set(['id', ...plan.fields])])\n return Option.map(row, values => {\n const shown = plan.apply({ id, values }).values\n return Object.fromEntries(\n allowed.filter(field => Object.hasOwn(shown, field)).map(field => [field, shown[field]]),\n )\n })\n })\n\n/** A link's value as a row holds it: the ref's key, or `null` for none. */\nconst linkKey = (link: Option.Option<{ readonly entity: string; readonly id: string }>) =>\n Option.match(link, { onNone: () => null, onSome: ref => `${ref.entity}:${ref.id}` })\n\n/** Whether a query's result is a connection over `entity`. */\nconst lists = (result: unknown, entity: string): boolean =>\n typeof result === 'object' && result !== null && 'entity' in result && result.entity === entity\n"],"mappings":";;;;;;;;;;;;;;;AA8BA,MAAM,aAAa,WAAyB;;AAG5C,MAAM,SAAS,UAAoF;CACjG,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,KAAK;CAClD,MAAM,QAAQ,MAAM,QAAQ,GAAG;CAC/B,OAAO,SAAS,IACZ,OAAO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sourcesContent":["/**\n * A guard set's read rules as `foldkit-remote-server`'s seams: an\n * `EntitySource.filter` from each member's Read rule, and `RemoteServer.memory`'s\n * `readable` and `filter` from the row's, and a check at startup that a server\n * applies them. A subpath, so the shared declaration the browser imports never\n * brings the server along.\n */\nimport { Effect, Match, Option, Schema, SchemaAST } from 'effect'\nimport { Entity, Query, supported, type AnyEntity, type AnyQuery } from 'foldkit-entity'\nimport type { MutationDescriptor, RemoteForbidden } from 'foldkit-remote'\nimport {\n RemoteInvalid,\n RemoteServer,\n RemoteServerError,\n type EntityRecord,\n type EntitySource,\n type EntityWriter,\n type MutationOutcome,\n type MutationRefused,\n type MutationSource,\n type MemoryReadable,\n type ReadPlan,\n type ServerDefinition,\n type WriteWhen,\n} from 'foldkit-remote-server'\nimport {\n attached,\n attachedRules,\n readRowsRuled,\n readRuled,\n type Attachment,\n type Deny,\n type InteractionKey,\n} from './attach.js'\nimport { Condition, type RowRule } from './condition.js'\nimport type { Policy } from './index.js'\nimport type { MayAnswer } from './may.js'\nimport { ME, type MeEntity } from './me.js'\nimport { memberRules, rowRules, writeRules } from './placed.js'\n\nconst noMembers = (record: EntityRecord) => record\n\n/** Two stored values, which are JSON: equal when they encode the same. */\nconst sameStored = (left: unknown, right: unknown): boolean =>\n JSON.stringify(left) === JSON.stringify(right)\n\n/** The members of `fields` that have a Read rule, once each. */\nconst hiddenOf = (\n attachment: Attachment,\n fields: ReadonlyArray<{ readonly key: string }>,\n): ReadonlyArray<string> => [\n ...new Set(fields.map(field => field.key).filter(key => readRuled(attachment, key))),\n]\n\n/** Each guarded writer's `revision`, or none: one a change can fall between check and write of. */\nconst pins = new WeakMap<object, Option.Option<string>>()\n\n/** A ref key's two halves, `Entity:id`; `none` for anything else. */\nconst refOf = (value: unknown): Option.Option<{ readonly entity: string; readonly id: string }> => {\n if (typeof value !== 'string') return Option.none()\n const split = value.indexOf(':')\n return split <= 0\n ? Option.none()\n : Option.some({ entity: value.slice(0, split), id: value.slice(split + 1) })\n}\n\nexport const GuardServer = {\n /**\n * `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`\n * answered by `policy`. `signedIn` is whether the server answered as\n * someone; `key` is their `key`. Any other id is no row.\n *\n * ```ts\n * RemoteServer.make({ entities: [GuardServer.me(Me, Policy), …] })\n * ```\n */\n me: <User, R>(\n entity: MeEntity,\n policy: Policy<User, R>,\n ): EntitySource<Option.Option<User>, R> => {\n // Otherwise every read would die deciding another set's guards.\n Option.map(attached(entity), ({ set }) => {\n if (set !== policy.set) {\n throw new Error(\n `[foldkit-guard] GuardServer.me: Me carries the guards of ${set}, not ${policy.set}`,\n )\n }\n })\n return {\n ...RemoteServer.entity<Option.Option<User>, R>(entity, {\n read: ({ ids, principal }) =>\n Effect.succeed(\n ids\n .filter(id => id === ME)\n .map(id => ({\n id,\n values: {\n signedIn: Option.isSome(principal),\n // Encoded, as a Source answers: `null` for a visitor.\n key: Option.match(principal, {\n onNone: () => null,\n onSome: policy.key,\n }),\n },\n })),\n ),\n filter: GuardServer.filter(entity, policy),\n }),\n // Its Read rule as this Source applies it: only the asker's own row,\n // which `Guards.me` lets anyone read. One per call: the registry is keyed\n // by it, and another call is for another Policy.\n visible: rowRules.add(Object.freeze({ reads: 'the asker’s own row' }), policy, [entity]),\n }\n },\n\n /**\n * An `EntitySource.filter` for `entity`: each requested member with a Read\n * rule is decided per record, omitted or redacted where the rule refuses.\n * The fields a rule reads are read too, so it can be decided.\n *\n * ```ts\n * RemoteServer.entity(Todo, { read, filter: GuardServer.filter(Todo, Policy) })\n * ```\n */\n filter: <User, R>(entity: AnyEntity, policy: Policy<User, R>) =>\n memberRules.add(\n (\n principal: Option.Option<User>,\n fields: readonly string[],\n ): Effect.Effect<ReadPlan, never, R> =>\n Effect.map(\n Effect.all([\n policy.readMembers(entity, principal, fields),\n // `may` is answered here, where the row is read as its principal sees it.\n asksMay(entity, fields)\n ? Effect.map(mayOf(entity, policy, principal), Option.some)\n : Effect.succeed(Option.none<MayPlan>()),\n ]),\n ([members, may]): ReadPlan => {\n if (members.length === 0 && Option.isNone(may)) return { fields, apply: noMembers }\n const input = policy.inputOf(principal)\n const decided = members.map(member => ({\n ...member,\n // A redacted value is a decoded one; the record holds what the store holds.\n redacted:\n member.deny._tag === 'Redact'\n ? Option.some(\n Schema.encodeSync(\n (\n entity.members as Readonly<\n Record<string, { readonly schema: Schema.Top }>\n >\n )[member.member]!.schema as unknown as Schema.Codec<unknown, unknown>,\n )(member.deny.value),\n )\n : Option.none(),\n }))\n return {\n fields: [\n ...new Set([\n ...fields,\n ...members.flatMap(({ condition }) => Condition.members(condition)),\n ...Option.match(may, { onNone: () => [], onSome: ({ fields }) => fields }),\n ]),\n ],\n apply: record => {\n const values: Record<string, unknown> = { ...record.values }\n for (const { member, condition, redacted } of decided) {\n // Member rules carry no inherited Read: only a row's Read may inherit.\n if (\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 (an\n * update's over the row as it would be after it too, so a write cannot move\n * a row out of its writer's reach), each member it sets must allow setting\n * it, and each relation it points elsewhere must allow the unlink and the\n * link. A create's rules hold over the values it proposes, where a field the\n * create leaves unset matches no guard, not even one for an empty value. A refusal is\n * `Forbidden`, with the sentence an `explain` gave; the write never runs.\n *\n * `presets` are fields a create takes from who is asking, never from the\n * client (`ownerId: user => user.id`): set before the rules are checked, so\n * a rule over them holds of the creator. A visitor has nothing to preset\n * from, and a create whose input sets a preset field is a mistake of the\n * server's, refused.\n *\n * `revision` names a field stored as a number, which the writer moves on by\n * one with each write it lands. An update or a delete then lands only on the\n * revision its rules were decided over (the writer's `expect`), so a change\n * between the check and the write is never written over; it is decided\n * again against the row as it now is, up to three times. A change that does\n * not move the revision (a handler's, `applyEdits`', raw SQL) is not seen.\n * Without `revision`, none is, and `validate` warns. An input that expects a\n * revision the row read is not at is a `Conflict`, decided before any rule;\n * an input may expect only the field the writer pins.\n *\n * ```ts\n * RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))\n * ```\n */\n writer: <E extends AnyEntity, User, R, RW>(\n entity: E,\n policy: Policy<User, R>,\n writer: EntityWriter<Option.Option<User>, RW>,\n options: {\n readonly presets?: {\n readonly [K in keyof E['fields']]?: (user: User) => E['fields'][K]['schema']['Type']\n }\n readonly revision?: keyof E['fields'] & string\n } = {},\n ): EntityWriter<Option.Option<User>, R | RW> => {\n const revision = options.revision\n if (revision !== undefined) {\n const field = Object.hasOwn(entity.fields, revision)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[revision]\n : undefined\n if (field === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${revision}\" for its revision`,\n )\n }\n // The writer moves it on by one in the statement it writes with, so it is stored as a number.\n if (!SchemaAST.isNumber(Schema.toEncoded(field.schema).ast)) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s revision \"${revision}\" is not stored as a number`,\n )\n }\n }\n const presets = Object.entries(options.presets ?? {}).map(([field, preset]) => {\n const declared = Object.hasOwn(entity.fields, field)\n ? (entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>)[field]\n : undefined\n if (declared === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name} has no field \"${field}\" to preset`,\n )\n }\n const encode = Schema.encodeUnknownSync(\n declared.schema as unknown as Schema.Codec<unknown, unknown>,\n )\n return { field, value: (user: User) => encode((preset as (user: User) => unknown)(user)) }\n })\n if (writer.entity !== entity.name) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s rules over a writer for ${writer.entity}`,\n )\n }\n const read = writer.read\n if (read === undefined) {\n throw new Error(\n `[foldkit-guard] GuardServer.writer: ${entity.name}'s writer reads no row as its writer may see it; bind it with a visible rule (GuardDrizzle.visible)`,\n )\n }\n const holds = (\n rule: { readonly condition: Condition },\n values: Readonly<Record<string, unknown>>,\n principal: Option.Option<User>,\n ) =>\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, or whose `expect` names, a member with\n * a Read rule: Unmet or written, Conflict or not, would answer for it.\n * `validate` refuses the same at startup; this holds where it was not run.\n */\n const discloses = (\n expect: Expect,\n when: Option.Option<WriteWhen>,\n ): Effect.Effect<void, RemoteServerError> =>\n Option.match(attachment, {\n onNone: () => Effect.void,\n onSome: ruled => {\n const read = Option.match(when, {\n onNone: () => [],\n onSome: ({ body }) => {\n const known = hiddenByBody.get(body)\n if (known !== undefined) return known\n const hidden = hiddenOf(ruled, Query.dependencies(body).predicate)\n hiddenByBody.set(body, hidden)\n return hidden\n },\n })\n const expected = Option.match(expect, {\n onNone: () => [],\n onSome: ({ field }) => (readRuled(ruled, field) ? [field] : []),\n })\n const hidden = [...new Set([...read, ...expected])]\n return hidden.length === 0\n ? Effect.void\n : Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s write reads ${hidden.join(', ')}, which a Read rule hides from its writer`,\n }),\n )\n },\n })\n /**\n * The answer the writer's ledger holds for this operation, or else `write`:\n * a retry of a write that landed is answered as it landed, not decided\n * again over a row that may have moved since.\n */\n const answeredOr = <E, RA>(\n context: {\n readonly id: string\n readonly operation: Option.Option<string>\n readonly principal: Option.Option<User>\n },\n write: () => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, E, RA>,\n ) => {\n const recorded = writer.recorded\n if (recorded === undefined || Option.isNone(context.operation)) return write()\n return Effect.flatMap(\n recorded({\n operation: context.operation.value,\n id: context.id,\n principal: context.principal,\n }),\n Option.match({ onSome: answer => Effect.succeed(Option.some(answer)), onNone: write }),\n )\n }\n // What an answer shows: the row as the writer may see it, members ruled.\n const memberRead = GuardServer.filter(entity, policy)\n // An update, step by step: admitted for what it declares, its rules chosen, the\n // row they read read, the rules decided over it as it is and as it would be, then\n // written pinned to that row. Each step refuses before the next can speak.\n type UpdateContext = Parameters<EntityWriter<Option.Option<User>, RW>['update']>[0]\n interface UpdateRules {\n readonly row: RowRule\n readonly members: ReadonlyArray<RowRule>\n readonly relating: Effect.Success<ReturnType<typeof linkRules>>\n }\n /** Refused before any rule, for what the write declares rather than what the row holds. */\n const admitUpdate = (context: UpdateContext): Effect.Effect<void, RemoteServerError> =>\n Effect.andThen(discloses(context.expect, context.when), () =>\n // The rules judge a sum over the row read: unpinned, that is not the row written.\n Object.keys(context.increments).length > 0 &&\n Option.isNone(context.expect) &&\n revision === undefined\n ? Effect.fail(\n new RemoteServerError({\n message: `${entity.name}'s increment expects no revision and its writer pins none, so its rules would judge a sum over a row that may move; give the writer a revision`,\n }),\n )\n : Effect.void,\n )\n /** The rules an update must meet: the row's, each member it sets, each relation it points. */\n const updateRules = (context: UpdateContext) =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Update')\n // An incremented field is set as surely as a written one: its Update rule holds.\n const members = yield* policy.writeMembers(\n entity,\n context.principal,\n [...Object.keys(context.values), ...Object.keys(context.increments)],\n 'Update',\n )\n const relating = yield* linkRules(context.principal, context.links)\n return { row, members, relating } satisfies UpdateRules\n })\n /** The row as its writer may see it, with every field the rules and the version read. */\n const readBefore = (context: UpdateContext, rules: UpdateRules) =>\n read({\n id: context.id,\n fields: fieldsOf(\n [rules.row, ...rules.members, ...ruleOf(rules.relating)],\n [...Object.keys(context.links), ...versionFields(context.expect)],\n ),\n principal: context.principal,\n })\n /** The rules, over the row as it is and as the write would leave it. */\n const decideUpdate = (\n context: UpdateContext,\n rules: UpdateRules,\n before: Readonly<Record<string, unknown>>,\n ) =>\n Effect.gen(function* () {\n const { principal, values, increments, links } = context\n const linked = Object.keys(links)\n const stored =\n writer.linked === undefined || linked.length === 0\n ? Option.none()\n : yield* writer.linked({ id: context.id, relations: linked })\n const relations = linking(\n rules.relating,\n Option.some(\n Option.match(stored, {\n onNone: () => ({ links: before, exact: false }),\n onSome: links => ({ links, exact: true }),\n }),\n ),\n )\n // The sum the writer will store, over the row read, which the pin keeps as the row\n // written. Only a rule reads it, and `fieldsOf` read every field a rule reads.\n const after = {\n ...before,\n ...values,\n ...Object.fromEntries(\n Object.entries(increments).map(([field, amount]) => [\n field,\n Number(before[field]) + amount,\n ]),\n ),\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n yield* require([rules.row, ...rules.members, ...relations], before, principal)\n yield* require([rules.row], after, principal)\n })\n const guarded: EntityWriter<Option.Option<User>, R | RW> = {\n entity: writer.entity,\n // The precondition is the writer's to check, in the statement that writes.\n ...(writer.preconditions === true ? { preconditions: true } : {}),\n ...(writer.increments === true ? { increments: true } : {}),\n ...(writer.ledger === true ? { ledger: true } : {}),\n // Invariants are the writer's to judge, over the row its statement writes.\n ...(writer.invariants === true ? { invariants: true } : {}),\n // What the store refuses, the store knows: the guard adds no reason and drops none.\n ...(writer.refuses === undefined ? {} : { refuses: writer.refuses }),\n ...(writer.recorded === undefined ? {} : { recorded: writer.recorded }),\n read: ({ id, fields, principal }) =>\n seenRow(\n { filter: memberRead },\n seen => read({ id, fields: seen, principal }),\n principal,\n fields,\n id,\n ),\n update: context =>\n Effect.mapError(\n Effect.andThen(admitUpdate(context), () =>\n answeredOr(context, () =>\n pinned(context.id, context.expect, Option.isNone, () =>\n Effect.gen(function* () {\n const rules = yield* updateRules(context)\n const current = yield* readBefore(context, rules)\n if (Option.isNone(current)) return yield* Effect.fail(refused(rules.row.deny))\n if (moved(context.expect, current.value)) return Option.none()\n yield* decideUpdate(context, rules, current.value)\n return yield* writer.update({\n ...context,\n expect: pin(context.expect, current.value),\n })\n }),\n ),\n ),\n ),\n told,\n ),\n insert: given =>\n Effect.gen(function* () {\n const preset = presets.find(({ field }) => Object.hasOwn(given.values, field))\n if (preset !== undefined) {\n return yield* new RemoteServerError({\n message: `${entity.name}'s \"${preset.field}\" is preset by the server; the input may not set it`,\n })\n }\n if (presets.length > 0 && Option.isNone(given.principal)) {\n return yield* Effect.fail(RemoteServer.forbid())\n }\n const context = Option.match(given.principal, {\n onNone: () => given,\n onSome: user => ({\n ...given,\n values: {\n ...given.values,\n ...Object.fromEntries(presets.map(({ field, value }) => [field, value(user)])),\n },\n }),\n })\n const { principal, values, links } = context\n const row = yield* policy.writable(entity, principal, 'Create')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n Object.keys(values),\n 'Create',\n )\n const relations = linking(yield* linkRules(principal, links), Option.none())\n const proposed = {\n ...values,\n id: context.id,\n ...Object.fromEntries(\n Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]),\n ),\n }\n const rules = [row, ...members, ...relations]\n const ruled = rules.flatMap(({ condition }) => Condition.members(condition))\n const unset = new Set(ruled.filter(field => !Object.hasOwn(proposed, field)))\n yield* require(rules.map(rule => ({\n ...rule,\n condition: Condition.unsetting(rule.condition, unset),\n })), proposed, principal)\n return yield* Effect.mapError(writer.insert(context), told)\n }),\n delete: context =>\n Effect.andThen(discloses(context.expect, context.when), () =>\n pinned(\n context.id,\n context.expect,\n outcome => outcome === 'moved',\n () =>\n Effect.gen(function* () {\n const row = yield* policy.writable(entity, context.principal, 'Delete')\n const current = yield* read({\n id: context.id,\n fields: fieldsOf([row], versionFields(context.expect)),\n principal: context.principal,\n })\n // Hidden or gone, the writer sees no row: there is nothing of theirs to delete.\n if (Option.isNone(current)) return 'absent' as const\n if (moved(context.expect, current.value)) return 'moved' as const\n yield* require([row], current.value, context.principal)\n return yield* writer.delete({\n ...context,\n expect: pin(context.expect, current.value),\n })\n }),\n ),\n ),\n }\n pins.set(guarded, Option.fromUndefinedOr(revision))\n return writeRules.add(guarded, policy, [entity])\n },\n\n /**\n * A handler's Source (`RemoteServer.mutation`'s) with `entity`'s rule for\n * `interaction` checked before it runs. The row the input names (`id`) is\n * read through `source`, which must apply the Entity's Read rules, and the\n * rule must hold over it; a row its writer may not see is refused. With no\n * `id` (a create), the rule must hold of who is asking alone, a field it\n * reads matching no guard. `run` is given the row as read: its fields the\n * rule reads, its `id`, and `fields`. A refusal is `Forbidden`; `run` never\n * runs. What `run` writes is its own: check members it sets there. Each\n * row of `entity` its answer carries is read back through `source`, so the\n * answer shows its writer only what they may see, a row it hid from them\n * as deleted.\n *\n * ```ts\n * GuardServer.mutation(ArchiveTodo, {\n * entity: Todo, policy: Policy, interaction: Archive.key,\n * id: input => input.id, source: source(Db.Todo),\n * }, ({ input, row }) => …)\n * ```\n */\n mutation: <User, R, RS, RM, Name extends string, Input, Output, Refused>(\n mutation: MutationDescriptor<Name, Input, Output, Refused>,\n guard: {\n readonly entity: AnyEntity\n readonly policy: Policy<User, R>\n readonly interaction: 'Create' | 'Update' | 'Delete' | InteractionKey\n /**\n * The row the input acts on; none for a create. An input whose id may be\n * absent (`Option`, as one editor's for create and edit) creates when it\n * is, checked against `Create`.\n */\n readonly id?: ((input: Input) => string | Option.Option<string>) | undefined\n /** Reads the row as its writer may see it: the Entity's guarded Source. */\n readonly source: EntitySource<Option.Option<User>, RS>\n /** More of the row for `run`, beside what the rule reads. */\n readonly fields?: ReadonlyArray<string> | undefined\n },\n run: (context: {\n readonly input: Input\n readonly principal: Option.Option<User>\n readonly requestId: string\n readonly row: Option.Option<Readonly<Record<string, unknown>>>\n }) => Effect.Effect<\n MutationOutcome<Output>,\n RemoteServerError | MutationRefused | RemoteForbidden,\n RM\n >,\n ): MutationSource<Option.Option<User>, R | RS | RM> => {\n const { entity, policy, interaction, id, source } = guard\n if (!rowRules.has(source.visible, policy, entity)) {\n throw new Error(\n `[foldkit-guard] GuardServer.mutation: ${mutation.name}'s Source does not apply ${entity.name}'s Read rules`,\n )\n }\n /**\n * The answer as its writer may now see it: each row of `entity` it carries\n * read back through `source`, and one the handler hid from them deleted.\n */\n const shown = (outcome: MutationOutcome<Output>, principal: Option.Option<User>) =>\n Effect.map(\n Effect.forEach(outcome.entities ?? [], patch =>\n patch.entity !== entity.name\n ? Effect.succeed(Option.some(patch))\n : Effect.map(\n seenRow(\n source,\n fields =>\n Effect.map(rowOf(source, principal, fields, patch.id), Option.fromUndefinedOr),\n principal,\n Object.keys(patch.values),\n patch.id,\n ),\n Option.map(seen => ({ ...patch, values: seen })),\n ),\n ),\n read => ({\n ...outcome,\n entities: read.flatMap(Option.toArray),\n deleted: [\n ...(outcome.deleted ?? []),\n ...(outcome.entities ?? [])\n .filter((_, index) => Option.isNone(read[index]!))\n .map(({ entity, id }) => ({ entity, id })),\n ],\n }),\n )\n return RemoteServer.mutation<Option.Option<User>, R | RS | RM, Name, Input, Output, Refused>(\n mutation,\n context =>\n Effect.gen(function* () {\n const { principal } = context\n // `context.input` was decoded against the mutation's Input before this runs.\n const target = Option.flatMap(Option.fromUndefinedOr(id), of => {\n const named = of(context.input)\n return typeof named === 'string' ? Option.some(named) : named\n })\n const rule = yield* policy.writable(\n entity,\n principal,\n id !== undefined && Option.isNone(target) ? 'Create' : interaction,\n )\n const ruled = Condition.members(rule.condition)\n const input = policy.inputOf(principal)\n if (Option.isNone(target)) {\n const unset = Condition.unsetting(rule.condition, new Set(ruled))\n if (!Condition.holds(unset, {}, input, () => false, policy.operators)) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row: Option.none() }), principal)\n }\n const fields = [...new Set(['id', ...ruled, ...(guard.fields ?? [])])]\n const row = Option.fromUndefinedOr(yield* rowOf(source, principal, fields, target.value))\n if (\n Option.isNone(row) ||\n !Condition.holds(rule.condition, row.value, input, () => false, policy.operators)\n ) {\n return yield* Effect.fail(refused(rule.deny))\n }\n return yield* shown(yield* run({ ...context, row }), principal)\n }),\n )\n },\n\n /**\n * Checks, at startup, that `server` applies the guards of `entities`, the\n * Entities as `Guards.attach` returned them: each one's Source and each\n * query listing it apply its row's Read rules (`GuardDrizzle.visible`, or\n * `GuardServer.memory`), its Source applies its members' and relations'\n * (`GuardServer.filter`), and each declared write of it lands through\n * `GuardServer.writer`, all built from `policy`; and that no query's body\n * filters or orders by a member with a Read rule, which would answer for the\n * value it hides. A hand-written Source over a guarded Entity would serve\n * every row, and a bare writer would take every write; this throws instead,\n * naming each. A handler (`RemoteServer.mutation`) writes what its code\n * writes, which no check at startup can read.\n *\n * ```ts\n * GuardServer.validate(Policy, { entities: [Todo, Project], domain: Data, server: Server })\n * ```\n */\n validate: <User, R>(\n policy: Policy<User, R>,\n config: {\n readonly entities: ReadonlyArray<AnyEntity>\n /** The Remote domain the server answers, for which Entity each query lists. */\n readonly domain: {\n readonly registry: {\n readonly queries: ReadonlyMap<\n string,\n { readonly Result: unknown; readonly body?: AnyQuery | undefined }\n >\n }\n }\n readonly server: ServerDefinition<any, any>\n },\n ): void => {\n const byName = new Map(config.entities.map(entity => [entity.name, entity]))\n /** Whether who may read the rows of `entity` depends on who is asking. */\n const rowsRuled = (entity: AnyEntity | undefined) =>\n Option.exists(Option.flatMap(Option.fromUndefinedOr(entity), attached), attachment =>\n readRowsRuled(attachment),\n )\n // A query the domain does not declare lists an Entity no one can name.\n const undeclared = [...config.server.queries.keys()]\n .filter(query => !config.domain.registry.queries.has(query))\n .map(query => `query ${query} is served, but the domain does not declare it`)\n const entityProblems = config.entities.flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => {\n const name = entity.name\n if (attachment.set !== policy.set) {\n return [`${name} carries the guards of ${attachment.set}, not ${policy.set}`]\n }\n // Every guarded Entity's, whether or not it has rules there yet: a rule\n // attached later is then applied, not served past.\n const source = Option.fromUndefinedOr(config.server.entities.get(name))\n const sourceProblems = Option.match(source, {\n onNone: () => [],\n onSome: ({ visible, filter }) => [\n ...(rowRules.has(visible, policy, entity)\n ? []\n : [`${name}'s Source does not apply its Read rules`]),\n ...(memberRules.has(filter, policy, entity)\n ? []\n : [`${name}'s Source does not apply its members' Read rules`]),\n ],\n })\n const queryProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, query]) => {\n const listed = config.server.queries.get(queryName)\n return listed !== undefined &&\n lists(query.Result, name) &&\n !rowRules.has(listed.visible, policy, entity)\n ? [`query ${queryName} lists ${name} without its Read rules`]\n : []\n },\n )\n // A row the reader may see with a member it may not still answers a\n // filter or an order on that member: `cost < $max`, halved twenty\n // times, reads the cost the row came back without.\n const bodyProblems = [...config.domain.registry.queries].flatMap(\n ([queryName, { body }]) => {\n if (body === undefined || body.entity.name !== name) return []\n const { predicate, order } = Query.dependencies(body)\n return [\n ...hiddenOf(attachment, predicate).map(\n member =>\n `query ${queryName} filters ${name} by ${member}, which has a Read rule`,\n ),\n ...hiddenOf(attachment, order).map(\n member => `query ${queryName} orders ${name} by ${member}, which has a Read rule`,\n ),\n ]\n },\n )\n const writeProblems = [...config.server.mutations].flatMap(([mutation, source]) => {\n if (source.writes === undefined || source.writes.entity !== name) return []\n if (!writeRules.has(source.writes.writer, policy, entity)) {\n return [`write ${mutation} writes ${name} without its write rules`]\n }\n const { write, writer } = source.writes\n // Unmet or written, Conflict or not, answers for a member its writer may not read.\n const when = Option.match(write.when, {\n onNone: () => [],\n onSome: body => hiddenOf(attachment, Query.dependencies(body).predicate),\n })\n const expected = write.expect?.field.key\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n return [\n ...when.map(\n member =>\n `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`,\n ),\n ...(expected !== undefined && readRuled(attachment, expected)\n ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`]\n : []),\n ...(expected !== undefined &&\n pin !== undefined &&\n Option.exists(pin, field => field !== expected)\n ? [\n `write ${mutation} expects ${name}'s ${expected}, but its writer pins ${Option.getOrThrow(pin)}`,\n ]\n : []),\n ]\n })\n // A shared field goes to every live subscriber as written: no rule may tell them apart.\n const shared = Option.match(source, {\n onNone: () => [],\n onSome: source => [...(source.shared ?? [])],\n })\n const sharedProblems = [\n ...(shared.length > 0 && readRowsRuled(attachment)\n ? [`${name}'s Source shares ${shared.join(', ')}, but its rows have a Read rule`]\n : []),\n ...shared.flatMap(member => {\n const own = readRuled(attachment, member)\n ? [`${name}'s Source shares ${member}, which has a Read rule`]\n : []\n if (!Object.hasOwn(entity.relations, member)) return own\n const target = entity.relations[member]!.target().name\n if (!byName.has(target))\n return [\n ...own,\n `${name}'s Source shares ${member}, whose ${target} is not validated`,\n ]\n return rowsRuled(byName.get(target))\n ? [...own, `${name}'s Source shares ${member}, whose rows have a Read rule`]\n : own\n }),\n ]\n // A rule calling an operator the policy's table does not run would fail when\n // asked, so the server does not start with one (expr-operations-DESIGN §5.6).\n const operatorProblems = attachedRules(attachment).flatMap(rule =>\n rule._tag === 'RowGuard'\n ? Query.unsupported(rule.query, supported, policy.operators).map(\n missing =>\n `${name}'s ${rule.name} calls ${missing}, which the policy does not run`,\n )\n : [],\n )\n // A live Source of its own streams whatever it reads: nothing here can check it.\n const liveProblems = config.server.live.has(name)\n ? [`${name} has a live Source of its own; serve its changes through a live hub`]\n : []\n return [\n ...sourceProblems,\n ...queryProblems,\n ...bodyProblems,\n ...writeProblems,\n ...sharedProblems,\n ...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 const unpinnedWrites = [...config.server.mutations].flatMap(([mutation, source]) => {\n const writer = source.writes?.writer\n const pin = typeof writer === 'object' && writer !== null ? pins.get(writer) : undefined\n return pin !== undefined && Option.isNone(pin) ? [mutation] : []\n })\n if (unpinnedWrites.length > 0) {\n console.warn(\n `[foldkit-guard] GuardServer.validate: ${unpinnedWrites.join(', ')} ${unpinnedWrites.length === 1 ? 'writes' : 'write'} through a GuardServer.writer with no revision, so a change between its check and its write is not seen; pass { revision }`,\n )\n }\n },\n}\n\n/** Whether a read asks for `may`, of an Entity that has it (`Guards.may`). */\nconst asksMay = (entity: AnyEntity, fields: ReadonlyArray<string>) =>\n fields.includes('may') && Object.hasOwn(entity.derived, 'may')\n\n/** How one principal's `may` is answered: the fields its rules read, and the answer over a row. */\ninterface MayPlan {\n readonly fields: ReadonlyArray<string>\n readonly answer: (values: Readonly<Record<string, unknown>>) => MayAnswer\n}\n\n/** The interactions a row answers `may` for: `Update`, `Delete`, and each one the set named. */\nconst builtInRow = new Set(['Read', 'Create', 'Update', 'Delete'])\n\n/**\n * `may` for `principal`: each row interaction's rule, each member's own\n * `Update`, each relation's `Link` and `Unlink`, decided once and held over\n * each row as a write's check would hold them over it as it is.\n */\nconst mayOf = <User, R>(\n entity: AnyEntity,\n policy: Policy<User, R>,\n principal: Option.Option<User>,\n): Effect.Effect<MayPlan, never, R> => {\n const attachment = attached(entity)\n const named = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ row }) => Object.keys(row).filter(interaction => !builtInRow.has(interaction)),\n })\n const ruledMembers = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ members }) => Object.keys(members),\n })\n const ruledRelations = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ relations }) => Object.keys(relations),\n })\n return Effect.map(\n Effect.all([\n Effect.forEach(['Update', 'Delete', ...named], interaction =>\n Effect.map(\n // A named one was attached as an `InteractionKey`; its key is the name.\n policy.writable(entity, principal, interaction as InteractionKey),\n rule => [interaction, rule] as const,\n ),\n ),\n policy.writeMembers(entity, principal, ruledMembers, 'Update'),\n Effect.forEach(ruledRelations, relation =>\n Effect.map(\n Effect.all([\n policy.linkable(entity, principal, relation, 'Link'),\n policy.linkable(entity, principal, relation, 'Unlink'),\n ]),\n ([link, unlink]) => ({ relation, link, unlink }),\n ),\n ),\n ]),\n ([rows, members, relations]): MayPlan => {\n const input = policy.inputOf(principal)\n const holds = (condition: Condition, values: Readonly<Record<string, unknown>>) =>\n Condition.holds(condition, values, input, () => false, policy.operators)\n // A relation without a rule for one direction leaves it to the row's Update.\n const allows = (rule: Option.Option<RowRule>, values: Readonly<Record<string, unknown>>) =>\n Option.match(rule, {\n onNone: () => true,\n onSome: ({ condition }) => holds(condition, values),\n })\n const conditions = [\n ...rows.map(([, { condition }]) => condition),\n ...members.map(({ condition }) => condition),\n ...relations.flatMap(({ link, unlink }) =>\n [...Option.toArray(link), ...Option.toArray(unlink)].map(({ condition }) => condition),\n ),\n ]\n return {\n // `id` too, so a row is read when its rules read none of it (an admin's).\n fields: ['id', ...new Set(conditions.flatMap(Condition.members))],\n answer: values => ({\n row: Object.fromEntries(\n rows.map(([interaction, { condition }]) => [interaction, holds(condition, values)]),\n ),\n // Only an `explain`'s sentence is for whoever asked.\n reasons: Object.fromEntries(\n rows.flatMap(([interaction, { condition, deny }]) =>\n holds(condition, values)\n ? []\n : Match.valueTags(deny, {\n Explain: ({ reason }) => [[interaction, reason] as const],\n Forbidden: () => [],\n NotFound: () => [],\n Omit: () => [],\n Redact: () => [],\n }),\n ),\n ),\n members: Object.fromEntries(\n members.map(({ member, condition }) => [member, holds(condition, values)]),\n ),\n relations: Object.fromEntries(\n relations.map(({ relation, link, unlink }) => [\n relation,\n { Link: allows(link, values), Unlink: allows(unlink, values) },\n ]),\n ),\n }),\n }\n },\n )\n}\n\n/** A refused write as the client receives it: the sentence an `explain` gave, or none. */\nconst refused = (deny: Deny) =>\n Match.valueTags(deny, {\n Explain: ({ reason }) => RemoteServer.forbid(reason),\n Forbidden: () => RemoteServer.forbid(),\n NotFound: () => RemoteServer.forbid(),\n Omit: () => RemoteServer.forbid(),\n Redact: () => RemoteServer.forbid(),\n })\n\n/** One row, by id, as `principal` may read it through `source`. */\nconst rowOf = <P, R>(\n source: EntitySource<P, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n) =>\n Effect.map(\n source.read({ ids: [id], fields: [...fields], principal }),\n records => records.find(record => record.id === id)?.values,\n )\n\n/**\n * Row `id` of `fields` as `principal` may see it, through `see`'s `authorize`\n * and `filter` as a Source applies them, and no more than was asked: what an\n * answer shows its writer. None when the row is not there to them.\n */\nconst seenRow = <P, R, RS>(\n see: Pick<EntitySource<P, RS>, 'authorize' | 'filter'>,\n read: (\n fields: ReadonlyArray<string>,\n ) => Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R>,\n principal: P,\n fields: ReadonlyArray<string>,\n id: string,\n): Effect.Effect<Option.Option<Readonly<Record<string, unknown>>>, RemoteServerError, R | RS> =>\n Effect.gen(function* () {\n const allowed = see.authorize === undefined ? fields : see.authorize(principal, [...fields])\n const plan: ReadPlan =\n see.filter === undefined\n ? { fields: allowed, apply: noMembers }\n : yield* see.filter(principal, allowed)\n // The id too: a row asked for nothing else is still there or not.\n const row = yield* read([...new Set(['id', ...plan.fields])])\n return Option.map(row, values => {\n const shown = plan.apply({ id, values }).values\n return Object.fromEntries(\n allowed.filter(field => Object.hasOwn(shown, field)).map(field => [field, shown[field]]),\n )\n })\n })\n\n/** A link's value as a row holds it: the ref's key, or `null` for none. */\nconst linkKey = (link: Option.Option<{ readonly entity: string; readonly id: string }>) =>\n Option.match(link, { onNone: () => null, onSome: ref => `${ref.entity}:${ref.id}` })\n\n/** Whether a query's result is a connection over `entity`. */\nconst lists = (result: unknown, entity: string): boolean =>\n typeof result === 'object' && result !== null && 'entity' in result && result.entity === entity\n"],"mappings":";;;;;;;;;;;;;;;AAwCA,MAAM,aAAa,WAAyB;;AAG5C,MAAM,cAAc,MAAe,UACjC,KAAK,UAAU,IAAI,MAAM,KAAK,UAAU,KAAK;;AAG/C,MAAM,YACJ,YACA,WAC0B,CAC1B,GAAG,IAAI,IAAI,OAAO,KAAI,UAAS,MAAM,GAAG,CAAC,CAAC,QAAO,QAAO,UAAU,YAAY,GAAG,CAAC,CAAC,CACrF;;AAGA,MAAM,uBAAO,IAAI,QAAuC;;AAGxD,MAAM,SAAS,UAAoF;CACjG,IAAI,OAAO,UAAU,UAAU,OAAO,OAAO,KAAK;CA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
2
2
|
import { Effect, Option } from "effect";
|
|
3
3
|
import { AnyEntity } from "foldkit-entity";
|
|
4
4
|
import { EntitySource } from "foldkit-remote-server";
|
|
5
5
|
import { AuthorizeDecision, Operation } from "foldkit-sync";
|
|
6
|
-
//#region src/sync.d.ts
|
|
7
6
|
/** One cell's change, as `foldkit-sync/entity`'s `Change` carries it. */
|
|
8
7
|
export interface CellChange {
|
|
9
8
|
readonly id: unknown;
|
|
@@ -77,5 +76,4 @@ export declare const GuardSync: {
|
|
|
77
76
|
readonly changesOf: (operation: Operation) => ReadonlyArray<CellChange>;
|
|
78
77
|
}) => (operation: Operation) => Effect.Effect<AuthorizeDecision, unknown, R>;
|
|
79
78
|
};
|
|
80
|
-
//#endregion
|
|
81
79
|
//# sourceMappingURL=sync.d.mts.map
|
package/dist/sync.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync.d.mts","names":[],"sources":["../src/sync.ts"],"mappings":"
|
|
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;;;;;;;;;;;;;;EA4BN,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,7 +1,7 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as Condition } from "./condition-
|
|
1
|
+
import { d as surfaceOf, r as attached, s as isAnyone, u as restricts } from "./attach-CRCF5XHS.mjs";
|
|
2
|
+
import { t as Condition } from "./condition-Bl1UgEpM.mjs";
|
|
3
3
|
import { Effect, Match, Option, Schema } from "effect";
|
|
4
|
-
|
|
4
|
+
// src/sync.ts
|
|
5
5
|
/**
|
|
6
6
|
* `foldkit-guard/sync`: a guard set's rules on `foldkit-sync`'s edits to a
|
|
7
7
|
* server-owned Entity. A cell edit is a write to a member of a row, through
|
|
@@ -142,7 +142,7 @@ const GuardSync = {
|
|
|
142
142
|
const members = yield* policy.writeMembers(entity, principal, [...new Set(changes.map((change) => change.member))], "Update");
|
|
143
143
|
const input = policy.inputOf(principal);
|
|
144
144
|
const fields = [.../* @__PURE__ */ new Set(["id", ...[row, ...members].flatMap(({ condition }) => Condition.members(condition))])];
|
|
145
|
-
const holdsOver = (values) => (condition) => Condition.holds(condition, values, input, () => false);
|
|
145
|
+
const holdsOver = (values) => (condition) => Condition.holds(condition, values, input, () => false, policy.operators);
|
|
146
146
|
const byRow = /* @__PURE__ */ new Map();
|
|
147
147
|
for (const { id, member, value } of encoded.value) byRow.set(id, {
|
|
148
148
|
...byRow.get(id),
|
|
@@ -168,7 +168,6 @@ const GuardSync = {
|
|
|
168
168
|
return true;
|
|
169
169
|
})
|
|
170
170
|
};
|
|
171
|
-
//#endregion
|
|
172
171
|
export { GuardSync };
|
|
173
172
|
|
|
174
173
|
//# sourceMappingURL=sync.mjs.map
|
package/dist/sync.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"sync.mjs","names":[],"sources":["../src/sync.ts"],"sourcesContent":["/**\n * `foldkit-guard/sync`: a guard set's rules on `foldkit-sync`'s edits to a\n * server-owned Entity. A cell edit is a write to a member of a row, through\n * the journal instead of a Remote mutation, so it answers to the same rules.\n *\n * Writes are checked in two halves, by where each can run. What needs only\n * the principal (`always`, the row's and each member's `Update` principal\n * guards) is the journal's `authorize`, under its lock. What reads the row is\n * the exchange's `admit`, before the journal sees the edit, reading the row\n * through the Entity's guarded Source.\n *\n * Reads are one audience: every replica that opens a document receives every\n * edit committed to it. So a document names its `readers`, who alone may open\n * it, and is refused where it is declared when an edit could carry a value to\n * someone the Entity's Read rules would not show it to.\n */\nimport { Effect, Match, Option, Schema } from 'effect'\nimport type { AnyEntity } from 'foldkit-entity'\nimport type { EntitySource } from 'foldkit-remote-server'\nimport type { AuthorizeDecision, Operation } from 'foldkit-sync'\nimport { attached, isAnyone, restricts, surfaceOf, type Deny } from './attach.js'\nimport { Condition } from './condition.js'\nimport type { Policy, PrincipalGuard } from './index.js'\n\n/** One cell's change, as `foldkit-sync/entity`'s `Change` carries it. */\nexport interface CellChange {\n readonly id: unknown\n readonly member: string\n readonly value: unknown\n}\n\n/** A document of edits to an Entity's members, and who may open it. */\nexport interface GuardedDocument<User> {\n readonly entity: AnyEntity\n readonly members: ReadonlyArray<string>\n readonly readers: ReadonlyArray<PrincipalGuard<User>>\n}\n\nconst refusal = (deny: Deny): AuthorizeDecision =>\n Match.valueTags(deny, {\n Explain: ({ reason }): AuthorizeDecision => ({ allowed: false, reason }),\n Forbidden: () => false,\n NotFound: () => false,\n Omit: () => false,\n Redact: () => false,\n })\n\n/** The first rule of `rules` that does not hold over `values`, as the decision it makes. */\nconst first = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n holds: (condition: Condition) => boolean,\n): AuthorizeDecision =>\n Option.match(Option.fromUndefinedOr(rules.find(({ condition }) => !holds(condition))), {\n onNone: () => true,\n onSome: ({ deny }) => refusal(deny),\n })\n\nconst isNever = (condition: Condition) => condition === Condition.never\n\n/** The schema of `member` when the document edits it: none for a name it does not own. */\nconst memberOf = <User>(\n entity: AnyEntity,\n document: GuardedDocument<User>,\n member: string,\n): Option.Option<Schema.Codec<unknown, unknown>> => {\n const fields = entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>\n // `document` refused a member that is not a field, so one it names is one.\n return document.members.includes(member)\n ? Option.some(fields[member]!.schema as unknown as Schema.Codec<unknown, unknown>)\n : Option.none()\n}\n\nexport const GuardSync = {\n /**\n * A document of edits to `edits.entity`'s `edits.members`, opened by any of\n * `readers`. Refused here, not discovered later: a member that is not a\n * field of the Entity, a member with a Read rule\n * of its own (its value would reach a reader the rule hides it from), a\n * reader the row's Read rule does not name (it would receive edits to rows\n * it cannot read), a guarded row with no readers, and `always` rules that\n * read the row (no reader could be shown to pass them).\n *\n * ```ts\n * const Edits = GuardSync.document(ProductEdits, { readers: [G.isStaff] })\n * ```\n */\n document: <User>(\n edits: { readonly entity: AnyEntity; readonly members: ReadonlyArray<string> },\n options: { readonly readers: ReadonlyArray<PrincipalGuard<User>> },\n ): GuardedDocument<User> => {\n const { entity, members } = edits\n const fail = (why: string): never => {\n throw new Error(`[foldkit-guard] GuardSync.document of ${entity.name}: ${why}`)\n }\n for (const member of members) {\n if (!Object.hasOwn(entity.fields, member)) fail(`${member} is not a field of it`)\n }\n Option.map(attached(entity), attachment => {\n for (const member of members) {\n if (restricts(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })))\n fail(`${member} has a Read rule of its own, and every reader receives every edit`)\n }\n const read = surfaceOf(attachment, { _tag: 'Row', interaction: 'Read' })\n if (Option.isSome(read) && restricts(read)) {\n if (options.readers.length === 0)\n fail('its rows have a Read rule, so the document names its readers')\n for (const reader of options.readers) {\n const named = read.value.rules.some(\n rule =>\n rule._tag === 'PrincipalGuard' &&\n rule.name === reader.name &&\n rule.set === reader.set,\n )\n if (!named) fail(`${reader.name} is not in its rows' Read rule, so may not read them`)\n }\n }\n if (attachment.always.some(rule => rule._tag !== 'PrincipalGuard' && !isAnyone(rule)))\n fail('its `always` rules read the row, which no reader can be shown to pass')\n })\n return Object.freeze({ entity, members, readers: options.readers })\n },\n\n /**\n * Whether `principal` may open the document: any of its readers (anyone,\n * when it names none), and every `always` rule of the Entity. For\n * `journalExchange`'s `opens`.\n */\n opens: <User>(\n policy: Policy<User>,\n document: GuardedDocument<User>,\n principal: Option.Option<User>,\n ): Effect.Effect<boolean> => {\n const always = Option.match(attached(document.entity), {\n onNone: () => [],\n onSome: ({ always }) => always.filter(rule => rule._tag === 'PrincipalGuard'),\n }) as ReadonlyArray<PrincipalGuard<User>>\n const decided = (guards: ReadonlyArray<PrincipalGuard<User>>) =>\n Effect.forEach(guards, guard =>\n Effect.map(policy.decide(guard, { principal, interaction: 'Read' }), d => d === true),\n )\n return Effect.map(\n Effect.all([decided(document.readers), decided(always)]),\n // No readers named: its rows have no Read rule, so it is everyone's.\n ([readers, rules]) =>\n (document.readers.length === 0 || readers.some(Boolean)) && rules.every(Boolean),\n )\n },\n\n /**\n * The journal's `authorize` for a Message of cell edits: refuses one whose\n * row's `Update` or a changed member's `Update` the principal guards settle\n * as refused, with an `explain`'s sentence. It runs under the journal's\n * lock, so it reads no row (`admit` does), and its bodies must not suspend.\n *\n * ```ts\n * authorize: { EditedProducts: GuardSync.authorize(Policy, Edits) }\n * ```\n */\n authorize:\n <User>(policy: Policy<User>, document: GuardedDocument<User>) =>\n (request: {\n readonly principal: Option.Option<User>\n readonly message: { readonly changes: ReadonlyArray<CellChange> }\n }): AuthorizeDecision => {\n const { principal, message } = request\n const row = Effect.runSync(policy.writable(document.entity, principal, 'Update'))\n if (isNever(row.condition)) return refusal(row.deny)\n const members = Effect.runSync(\n policy.writeMembers(\n document.entity,\n principal,\n [...new Set(message.changes.map(change => change.member))],\n 'Update',\n ),\n )\n return first(members, condition => !isNever(condition))\n },\n\n /**\n * The exchange's `admit` for `principal`: each row an operation's edits\n * name is read through `source` (the Entity's guarded Source) and must let\n * the principal update it, as it is and as it would be after all of the\n * operation's edits to it, and each changed member must too. A row the\n * principal cannot see is refused, as is an edit to a member outside the\n * document or a value its member cannot encode. `changesOf` reads the edits\n * from an operation; one with none is admitted.\n *\n * The row is read from the table, which takes an edit only once its exchange\n * settles: an edit that changes what a rule reads lets another, admitted\n * before it lands, be judged against the row as it was.\n */\n admit:\n <User, R>(\n policy: Policy<User>,\n document: GuardedDocument<User>,\n options: {\n readonly principal: Option.Option<User>\n readonly source: EntitySource<Option.Option<User>, R>\n readonly changesOf: (operation: Operation) => ReadonlyArray<CellChange>\n },\n ) =>\n (operation: Operation): Effect.Effect<AuthorizeDecision, unknown, R> =>\n Effect.gen(function* () {\n const { principal, source } = options\n const changes = options.changesOf(operation)\n if (changes.length === 0) return true\n const { entity } = document\n // A member is a client's word: only the document's own, by own key.\n const encoded = Option.all(\n changes.map(change =>\n Option.flatMap(memberOf(entity, document, change.member), schema =>\n Option.map(Schema.encodeUnknownOption(schema)(change.value), value => ({\n id: String(change.id),\n member: change.member,\n value,\n })),\n ),\n ),\n )\n if (Option.isNone(encoded)) return false\n const row = yield* policy.writable(entity, principal, 'Update')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n [...new Set(changes.map(change => change.member))],\n 'Update',\n )\n const input = policy.inputOf(principal)\n const fields = [\n ...new Set([\n 'id',\n ...[row, ...members].flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n const holdsOver = (values: Readonly<Record<string, unknown>>) => (condition: Condition) =>\n Condition.holds(condition, values, input, () => false)\n // Every edit to one row is judged together: two may each keep it in reach, and both not.\n const byRow = new Map<string, Record<string, unknown>>()\n for (const { id, member, value } of encoded.value) {\n byRow.set(id, { ...byRow.get(id), [member]: value })\n }\n for (const [id, edits] of byRow) {\n const records = yield* source.read({ ids: [id], fields, principal })\n const current = Option.fromUndefinedOr(records.find(record => record.id === id)?.values)\n if (Option.isNone(current)) return refusal(row.deny)\n const changed = new Set(Object.keys(edits))\n const before = first(\n [row, ...members.filter(({ member }) => changed.has(member))],\n holdsOver(current.value),\n )\n if (before !== true) return before\n const moved = first([row], holdsOver({ ...current.value, ...edits }))\n if (moved !== true) return moved\n }\n return true\n }),\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,WAAW,SACf,MAAM,UAAU,MAAM;CACpB,UAAU,EAAE,cAAiC;EAAE,SAAS;EAAO;CAAO;CACtE,iBAAiB;CACjB,gBAAgB;CAChB,YAAY;CACZ,cAAc;AAChB,CAAC;;AAGH,MAAM,SACJ,OACA,UAEA,OAAO,MAAM,OAAO,gBAAgB,MAAM,MAAM,EAAE,gBAAgB,CAAC,MAAM,SAAS,CAAC,CAAC,GAAG;CACrF,cAAc;CACd,SAAS,EAAE,WAAW,QAAQ,IAAI;AACpC,CAAC;AAEH,MAAM,WAAW,cAAyB,cAAc,UAAU;;AAGlE,MAAM,YACJ,QACA,UACA,WACkD;CAClD,MAAM,SAAS,OAAO;CAEtB,OAAO,SAAS,QAAQ,SAAS,MAAM,IACnC,OAAO,KAAK,OAAO,OAAO,CAAE,MAAmD,IAC/E,OAAO,KAAK;AAClB;AAEA,MAAa,YAAY;;;;;;;;;;;;;;CAcvB,WACE,OACA,YAC0B;EAC1B,MAAM,EAAE,QAAQ,YAAY;EAC5B,MAAM,QAAQ,QAAuB;GACnC,MAAM,IAAI,MAAM,yCAAyC,OAAO,KAAK,IAAI,KAAK;EAChF;EACA,KAAK,MAAM,UAAU,SACnB,IAAI,CAAC,OAAO,OAAO,OAAO,QAAQ,MAAM,GAAG,KAAK,GAAG,OAAO,sBAAsB;EAElF,OAAO,IAAI,SAAS,MAAM,IAAG,eAAc;GACzC,KAAK,MAAM,UAAU,SACnB,IAAI,UAAU,UAAU,YAAY;IAAE,MAAM;IAAU;IAAQ,aAAa;GAAO,CAAC,CAAC,GAClF,KAAK,GAAG,OAAO,kEAAkE;GAErF,MAAM,OAAO,UAAU,YAAY;IAAE,MAAM;IAAO,aAAa;GAAO,CAAC;GACvE,IAAI,OAAO,OAAO,IAAI,KAAK,UAAU,IAAI,GAAG;IAC1C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CAAC;EAErD,KAAK,MAAM,CAAC,IAAI,UAAU,OAAO;GAC/B,MAAM,UAAU,OAAO,OAAO,KAAK;IAAE,KAAK,CAAC,EAAE;IAAG;IAAQ;GAAU,CAAC;GACnE,MAAM,UAAU,OAAO,gBAAgB,QAAQ,MAAK,WAAU,OAAO,OAAO,EAAE,CAAC,EAAE,MAAM;GACvF,IAAI,OAAO,OAAO,OAAO,GAAG,OAAO,QAAQ,IAAI,IAAI;GACnD,MAAM,UAAU,IAAI,IAAI,OAAO,KAAK,KAAK,CAAC;GAC1C,MAAM,SAAS,MACb,CAAC,KAAK,GAAG,QAAQ,QAAQ,EAAE,aAAa,QAAQ,IAAI,MAAM,CAAC,CAAC,GAC5D,UAAU,QAAQ,KAAK,CACzB;GACA,IAAI,WAAW,MAAM,OAAO;GAC5B,MAAM,QAAQ,MAAM,CAAC,GAAG,GAAG,UAAU;IAAE,GAAG,QAAQ;IAAO,GAAG;GAAM,CAAC,CAAC;GACpE,IAAI,UAAU,MAAM,OAAO;EAC7B;EACA,OAAO;CACT,CAAC;AACP"}
|
|
1
|
+
{"version":3,"file":"sync.mjs","names":[],"sources":["../src/sync.ts"],"sourcesContent":["/**\n * `foldkit-guard/sync`: a guard set's rules on `foldkit-sync`'s edits to a\n * server-owned Entity. A cell edit is a write to a member of a row, through\n * the journal instead of a Remote mutation, so it answers to the same rules.\n *\n * Writes are checked in two halves, by where each can run. What needs only\n * the principal (`always`, the row's and each member's `Update` principal\n * guards) is the journal's `authorize`, under its lock. What reads the row is\n * the exchange's `admit`, before the journal sees the edit, reading the row\n * through the Entity's guarded Source.\n *\n * Reads are one audience: every replica that opens a document receives every\n * edit committed to it. So a document names its `readers`, who alone may open\n * it, and is refused where it is declared when an edit could carry a value to\n * someone the Entity's Read rules would not show it to.\n */\nimport { Effect, Match, Option, Schema } from 'effect'\nimport type { AnyEntity } from 'foldkit-entity'\nimport type { EntitySource } from 'foldkit-remote-server'\nimport type { AuthorizeDecision, Operation } from 'foldkit-sync'\nimport { attached, isAnyone, restricts, surfaceOf, type Deny } from './attach.js'\nimport { Condition } from './condition.js'\nimport type { Policy, PrincipalGuard } from './index.js'\n\n/** One cell's change, as `foldkit-sync/entity`'s `Change` carries it. */\nexport interface CellChange {\n readonly id: unknown\n readonly member: string\n readonly value: unknown\n}\n\n/** A document of edits to an Entity's members, and who may open it. */\nexport interface GuardedDocument<User> {\n readonly entity: AnyEntity\n readonly members: ReadonlyArray<string>\n readonly readers: ReadonlyArray<PrincipalGuard<User>>\n}\n\nconst refusal = (deny: Deny): AuthorizeDecision =>\n Match.valueTags(deny, {\n Explain: ({ reason }): AuthorizeDecision => ({ allowed: false, reason }),\n Forbidden: () => false,\n NotFound: () => false,\n Omit: () => false,\n Redact: () => false,\n })\n\n/** The first rule of `rules` that does not hold over `values`, as the decision it makes. */\nconst first = (\n rules: ReadonlyArray<{ readonly condition: Condition; readonly deny: Deny }>,\n holds: (condition: Condition) => boolean,\n): AuthorizeDecision =>\n Option.match(Option.fromUndefinedOr(rules.find(({ condition }) => !holds(condition))), {\n onNone: () => true,\n onSome: ({ deny }) => refusal(deny),\n })\n\nconst isNever = (condition: Condition) => condition === Condition.never\n\n/** The schema of `member` when the document edits it: none for a name it does not own. */\nconst memberOf = <User>(\n entity: AnyEntity,\n document: GuardedDocument<User>,\n member: string,\n): Option.Option<Schema.Codec<unknown, unknown>> => {\n const fields = entity.fields as Readonly<Record<string, { readonly schema: Schema.Top }>>\n // `document` refused a member that is not a field, so one it names is one.\n return document.members.includes(member)\n ? Option.some(fields[member]!.schema as unknown as Schema.Codec<unknown, unknown>)\n : Option.none()\n}\n\nexport const GuardSync = {\n /**\n * A document of edits to `edits.entity`'s `edits.members`, opened by any of\n * `readers`. Refused here, not discovered later: a member that is not a\n * field of the Entity, a member with a Read rule\n * of its own (its value would reach a reader the rule hides it from), a\n * reader the row's Read rule does not name (it would receive edits to rows\n * it cannot read), a guarded row with no readers, and `always` rules that\n * read the row (no reader could be shown to pass them).\n *\n * ```ts\n * const Edits = GuardSync.document(ProductEdits, { readers: [G.isStaff] })\n * ```\n */\n document: <User>(\n edits: { readonly entity: AnyEntity; readonly members: ReadonlyArray<string> },\n options: { readonly readers: ReadonlyArray<PrincipalGuard<User>> },\n ): GuardedDocument<User> => {\n const { entity, members } = edits\n const fail = (why: string): never => {\n throw new Error(`[foldkit-guard] GuardSync.document of ${entity.name}: ${why}`)\n }\n for (const member of members) {\n if (!Object.hasOwn(entity.fields, member)) fail(`${member} is not a field of it`)\n }\n Option.map(attached(entity), attachment => {\n for (const member of members) {\n if (restricts(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })))\n fail(`${member} has a Read rule of its own, and every reader receives every edit`)\n }\n const read = surfaceOf(attachment, { _tag: 'Row', interaction: 'Read' })\n if (Option.isSome(read) && restricts(read)) {\n if (options.readers.length === 0)\n fail('its rows have a Read rule, so the document names its readers')\n for (const reader of options.readers) {\n const named = read.value.rules.some(\n rule =>\n rule._tag === 'PrincipalGuard' &&\n rule.name === reader.name &&\n rule.set === reader.set,\n )\n if (!named) fail(`${reader.name} is not in its rows' Read rule, so may not read them`)\n }\n }\n if (attachment.always.some(rule => rule._tag !== 'PrincipalGuard' && !isAnyone(rule)))\n fail('its `always` rules read the row, which no reader can be shown to pass')\n })\n return Object.freeze({ entity, members, readers: options.readers })\n },\n\n /**\n * Whether `principal` may open the document: any of its readers (anyone,\n * when it names none), and every `always` rule of the Entity. For\n * `journalExchange`'s `opens`.\n */\n opens: <User>(\n policy: Policy<User>,\n document: GuardedDocument<User>,\n principal: Option.Option<User>,\n ): Effect.Effect<boolean> => {\n const always = Option.match(attached(document.entity), {\n onNone: () => [],\n onSome: ({ always }) => always.filter(rule => rule._tag === 'PrincipalGuard'),\n }) as ReadonlyArray<PrincipalGuard<User>>\n const decided = (guards: ReadonlyArray<PrincipalGuard<User>>) =>\n Effect.forEach(guards, guard =>\n Effect.map(policy.decide(guard, { principal, interaction: 'Read' }), d => d === true),\n )\n return Effect.map(\n Effect.all([decided(document.readers), decided(always)]),\n // No readers named: its rows have no Read rule, so it is everyone's.\n ([readers, rules]) =>\n (document.readers.length === 0 || readers.some(Boolean)) && rules.every(Boolean),\n )\n },\n\n /**\n * The journal's `authorize` for a Message of cell edits: refuses one whose\n * row's `Update` or a changed member's `Update` the principal guards settle\n * as refused, with an `explain`'s sentence. It runs under the journal's\n * lock, so it reads no row (`admit` does), and its bodies must not suspend.\n *\n * ```ts\n * authorize: { EditedProducts: GuardSync.authorize(Policy, Edits) }\n * ```\n */\n authorize:\n <User>(policy: Policy<User>, document: GuardedDocument<User>) =>\n (request: {\n readonly principal: Option.Option<User>\n readonly message: { readonly changes: ReadonlyArray<CellChange> }\n }): AuthorizeDecision => {\n const { principal, message } = request\n const row = Effect.runSync(policy.writable(document.entity, principal, 'Update'))\n if (isNever(row.condition)) return refusal(row.deny)\n const members = Effect.runSync(\n policy.writeMembers(\n document.entity,\n principal,\n [...new Set(message.changes.map(change => change.member))],\n 'Update',\n ),\n )\n return first(members, condition => !isNever(condition))\n },\n\n /**\n * The exchange's `admit` for `principal`: each row an operation's edits\n * name is read through `source` (the Entity's guarded Source) and must let\n * the principal update it, as it is and as it would be after all of the\n * operation's edits to it, and each changed member must too. A row the\n * principal cannot see is refused, as is an edit to a member outside the\n * document or a value its member cannot encode. `changesOf` reads the edits\n * from an operation; one with none is admitted.\n *\n * The row is read from the table, which takes an edit only once its exchange\n * settles: an edit that changes what a rule reads lets another, admitted\n * before it lands, be judged against the row as it was.\n */\n admit:\n <User, R>(\n policy: Policy<User>,\n document: GuardedDocument<User>,\n options: {\n readonly principal: Option.Option<User>\n readonly source: EntitySource<Option.Option<User>, R>\n readonly changesOf: (operation: Operation) => ReadonlyArray<CellChange>\n },\n ) =>\n (operation: Operation): Effect.Effect<AuthorizeDecision, unknown, R> =>\n Effect.gen(function* () {\n const { principal, source } = options\n const changes = options.changesOf(operation)\n if (changes.length === 0) return true\n const { entity } = document\n // A member is a client's word: only the document's own, by own key.\n const encoded = Option.all(\n changes.map(change =>\n Option.flatMap(memberOf(entity, document, change.member), schema =>\n Option.map(Schema.encodeUnknownOption(schema)(change.value), value => ({\n id: String(change.id),\n member: change.member,\n value,\n })),\n ),\n ),\n )\n if (Option.isNone(encoded)) return false\n const row = yield* policy.writable(entity, principal, 'Update')\n const members = yield* policy.writeMembers(\n entity,\n principal,\n [...new Set(changes.map(change => change.member))],\n 'Update',\n )\n const input = policy.inputOf(principal)\n const fields = [\n ...new Set([\n 'id',\n ...[row, ...members].flatMap(({ condition }) => Condition.members(condition)),\n ]),\n ]\n const holdsOver = (values: Readonly<Record<string, unknown>>) => (condition: Condition) =>\n Condition.holds(condition, values, input, () => false, policy.operators)\n // Every edit to one row is judged together: two may each keep it in reach, and both not.\n const byRow = new Map<string, Record<string, unknown>>()\n for (const { id, member, value } of encoded.value) {\n byRow.set(id, { ...byRow.get(id), [member]: value })\n }\n for (const [id, edits] of byRow) {\n const records = yield* source.read({ ids: [id], fields, principal })\n const current = Option.fromUndefinedOr(records.find(record => record.id === id)?.values)\n if (Option.isNone(current)) return refusal(row.deny)\n const changed = new Set(Object.keys(edits))\n const before = first(\n [row, ...members.filter(({ member }) => changed.has(member))],\n holdsOver(current.value),\n )\n if (before !== true) return before\n const moved = first([row], holdsOver({ ...current.value, ...edits }))\n if (moved !== true) return moved\n }\n return true\n }),\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAsCA,MAAM,WAAW,SACf,MAAM,UAAU,MAAM;CACpB,UAAU,EAAE,cAAiC;EAAE,SAAS;EAAO;CAAO;CACtE,iBAAiB;CACjB,gBAAgB;CAChB,YAAY;CACZ,cAAc;AAChB,CAAC;;AAGH,MAAM,SACJ,OACA,UAEA,OAAO,MAAM,OAAO,gBAAgB,MAAM,MAAM,EAAE,gBAAgB,CAAC,MAAM,SAAS,CAAC,CAAC,GAAG;CACrF,cAAc;CACd,SAAS,EAAE,WAAW,QAAQ,IAAI;AACpC,CAAC;AAEH,MAAM,WAAW,cAAyB,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QAAQ,KAAK,CACzB;GACA,IAAI,WAAW,MAAM,OAAO;GAC5B,MAAM,QAAQ,MAAM,CAAC,GAAG,GAAG,UAAU;IAAE,GAAG,QAAQ;IAAO,GAAG;GAAM,CAAC,CAAC;GACpE,IAAI,UAAU,MAAM,OAAO;EAC7B;EACA,OAAO;CACT,CAAC;AACP"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "foldkit-guard",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.5.0",
|
|
4
4
|
"description": "Who may do what, declared once on a Foldkit Plus domain: principal guards implemented on the server, row guards as query expressions.",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"foldkit",
|
|
@@ -61,17 +61,17 @@
|
|
|
61
61
|
"LICENSE"
|
|
62
62
|
],
|
|
63
63
|
"dependencies": {
|
|
64
|
-
"foldkit-entity": "0.
|
|
64
|
+
"foldkit-entity": "0.12.0",
|
|
65
65
|
"foldkit-metadata": "0.1.0"
|
|
66
66
|
},
|
|
67
67
|
"peerDependencies": {
|
|
68
68
|
"drizzle-orm": "1.0.0-rc.5",
|
|
69
69
|
"effect": "^4.0.0",
|
|
70
|
-
"foldkit-media": "^0.
|
|
71
|
-
"foldkit-remote": "^0.
|
|
72
|
-
"foldkit-remote-drizzle": "^0.
|
|
73
|
-
"foldkit-
|
|
74
|
-
"foldkit-
|
|
70
|
+
"foldkit-media": "^0.3.0",
|
|
71
|
+
"foldkit-remote": "^0.20.0",
|
|
72
|
+
"foldkit-remote-drizzle": "^0.14.0",
|
|
73
|
+
"foldkit-remote-server": "^0.17.0",
|
|
74
|
+
"foldkit-sync": "^0.12.3"
|
|
75
75
|
},
|
|
76
76
|
"peerDependenciesMeta": {
|
|
77
77
|
"drizzle-orm": {
|
|
@@ -99,13 +99,13 @@
|
|
|
99
99
|
"foldkit": "0.169.0",
|
|
100
100
|
"tsdown": "^0.23.1",
|
|
101
101
|
"typescript": "7.0.2",
|
|
102
|
-
"foldkit-media": "0.
|
|
103
|
-
"foldkit-
|
|
104
|
-
"foldkit-
|
|
105
|
-
"foldkit-remote": "0.
|
|
106
|
-
"foldkit-remote-server": "0.
|
|
107
|
-
"foldkit-surface": "0.10.
|
|
108
|
-
"foldkit-sync": "0.12.
|
|
102
|
+
"foldkit-media": "0.3.0",
|
|
103
|
+
"foldkit-agent": "0.8.3",
|
|
104
|
+
"foldkit-remote": "0.20.0",
|
|
105
|
+
"foldkit-remote-drizzle": "0.14.0",
|
|
106
|
+
"foldkit-remote-server": "0.17.0",
|
|
107
|
+
"foldkit-surface": "0.10.2",
|
|
108
|
+
"foldkit-sync": "0.12.3"
|
|
109
109
|
},
|
|
110
110
|
"scripts": {
|
|
111
111
|
"build": "tsdown",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"attach-BVG6LsFf.d.mts","names":["MemberKeys","_$__attach_js0.Attach","_$__attach_js0.AnyRule","_$__attach_js0.Inherit","_$__attach_js0.All","_$__attach_js0.Redact","_$__attach_js0.Explain","_$__attach_js0.On"],"sources":["../src/condition.ts","../src/may.ts","../src/me.ts","../src/index.ts","../src/attach.ts"],"mappings":";;;KAWY;WACG;;WACA;;WACA;WAAsB,OAAO,cAAc;;;;WAE3C;WAA0B;;WAC1B;WAAsB,YAAY,cAAc;;WAChD;WAAqB,YAAY,cAAc;;;cAMxD,MAAG,YAAgB,cAAc,eAAa;;cAY9C,KAAE,YAAgB,cAAc,eAAa;cAWtC;;aAnCQ;;;aACA;;;;;;;;;EA8CN,QAAA,WAAA,WAAS,QACZ,SAAS,0BAAwB,OAClC,SAAS,0BAAwB,UAC9B;;;;;;;EAoBW,YAAA,WAAA,WAAS,OAAS,wBAAsB;;EAiB1C,UAAA,WAAA,cAAY;;;UAelB;WACN;WACA,WAAW;WACX,MAAM;;;UAwDA;WACN,WAAW;WACX,MAAM;;;;;;;;;;cC/JJ,WAAS,OAAA;;;;;;;;;KASV,mBAAmB,UAAU;KAEpCA,aA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c,QAAQ,MAAM,KAAK,aAAa,QAAQ,aAAa;aAC1E,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;;aAEtC,QAAQ,UAAU,QAAQ,MAAM,KAAK;;;;;;;;WAQvC;cACG,GAAG,iBAAiB,UAAU,QAAQ,MAAM,KAAK;;;WAGpD,sBACG,KAAK,WAAW;aACf,OAAO,KAAK,QAAQ,MAAM,KAAK,YAAY,OAAO,OAAO,GAAG;;aAE5D,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;;WAG1C,wBACG,WAAW;aACV,OAAO,cAAc,QAAQ,MAAM,KAAK;aACxC,OAAO,UAAU,QAAQ,MAAM,KAAK;aACpC,SAAS,UAAU,QAAQ,MAAM,KAAK;;;WAI1C,SAAS,cAAc,QAAQ,MAAM,KAAK;;;UAIpC;WACN,OAAO,cAAc;WACrB,MAAM,OAAO,OAAO;;KAG1B,WAAW,SAAS,eAAe;;UAGvB;WACN;WACA;WACA,KAAK;WACL,SAAS,SAAS,eAAe;WACjC,WAAW,SAAS,eAAe;WACnC,QAAQ,cAAc;;cA4PpB,WAAQ,QAAY,cAAY,OAAO,OAAO"}
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"attach-BZyVvs7H.mjs","names":[],"sources":["../src/attach.ts"],"sourcesContent":["/**\n * Attaching a guard set's guards to an Entity, per surface and interaction,\n * as metadata only `foldkit-guard` reads. See `guard-DESIGN.md` §3.2.\n */\nimport { Match, Option, type Schema } from 'effect'\nimport { Entity, Query, ReadFilter, type AnyEntity } from 'foldkit-entity'\nimport { Metadata } from 'foldkit-metadata'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\ndeclare const InteractionBrand: unique symbol\n\n/** An interaction the application names, used as a computed key: `[Archive.key]`. */\nexport type InteractionKey<Name extends string = string> = Name & {\n readonly [InteractionBrand]: Name\n}\n\nexport interface Interaction<Name extends string> {\n readonly name: Name\n readonly key: InteractionKey<Name>\n}\n\n/** The interactions every row has, and the ones a relation member has. */\nconst builtIn = ['Read', 'Create', 'Update', 'Delete', 'Write', 'Link', 'Unlink'] as const\n\nexport const Interaction = {\n /** An interaction beyond Read, Create, Update and Delete, such as `Archive`. */\n make: <const Name extends string>(name: Name): Interaction<Name> => {\n if ((builtIn as ReadonlyArray<string>).includes(name)) {\n throw new Error(`[foldkit-guard] Interaction.make: \"${name}\" is an interaction already`)\n }\n return Object.freeze({ name, key: name as InteractionKey<Name> })\n },\n}\n\n/** Every guard of `Rules` must allow, as one guard: `Guards.all(signedIn, isOwner)`. */\nexport interface All<Rules> {\n readonly _tag: 'All'\n readonly rules: ReadonlyArray<Rules>\n}\n\n/** This row's Read is the Read of the row its `one` relation points at. */\nexport interface Inherit<Relation extends string> {\n readonly _tag: 'Inherit'\n readonly relation: Relation\n}\n\n/** What a member hidden by its Read guards reads as instead of its value. */\nexport interface Redact<A> {\n readonly _tag: 'Redact'\n readonly value: A\n}\n\n/** A refused write's sentence, for the application's own users. */\nexport interface Explain {\n readonly _tag: 'Explain'\n readonly reason: string\n}\n\n/**\n * What a refusal looks like. The defaults need no constructor: a row Read\n * answers `NotFound`, a member or relation Read `Omit`, a write `Forbidden`.\n */\nexport type Deny =\n | { readonly _tag: 'NotFound' }\n | { readonly _tag: 'Omit' }\n | Redact<unknown>\n | { readonly _tag: 'Forbidden' }\n | Explain\n\n/** A surface's guards with a refusal other than its default. */\nexport interface On<Rules, D extends Deny> {\n readonly _tag: 'On'\n readonly rules: ReadonlyArray<Rules>\n readonly deny: D\n}\n\n/** Anything a surface's list may hold, of any guard set. */\nexport type AnyRule =\n | PrincipalGuard<any, string>\n | RowGuard<any, AnyEntity, string>\n | All<any>\n | Inherit<string>\n\n/**\n * What a surface of the Entity named `Name` accepts from the guard set `Set`:\n * its principal guards, its row guards over that Entity, and conjunctions of\n * both. A row guard over another Entity, or a guard of another set, is refused.\n */\nexport type RuleFor<User, Set extends string, Name extends string> =\n | PrincipalGuard<User, Set>\n | RowGuard<User, Entity<Name, any, any, any>, Set>\n | All<RuleFor<User, Set, Name>>\n\ntype Slot<Rule, D extends Deny> = ReadonlyArray<Rule> | On<Rule, D>\n\ntype WriteSlot<Rule> = Slot<Rule, Explain>\n\ntype OneRelations<E extends AnyEntity> = {\n [K in keyof E['relations']]: E['relations'][K] extends { readonly cardinality: 'one' } ? K : never\n}[keyof E['relations']] &\n string\n\ntype MemberKeys<E extends AnyEntity> = (keyof E['fields'] | keyof E['derived']) & string\n\ntype TypeOf<E extends AnyEntity, K extends keyof E['members']> = E['members'][K]['schema']['Type']\n\n/** What `Guards.attach` takes for the Entity `E`, every key checked against it. */\nexport type Attach<User, Set extends string, E extends AnyEntity> = {\n readonly row?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']> | Inherit<OneRelations<E>>>\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Delete?: WriteSlot<RuleFor<User, Set, E['name']>>\n /** The same guards on Create, Update and Delete. */\n readonly Write?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /**\n * The row's interactions the application named, by key:\n * `{ [Archive.key]: [G.isAdmin] }`. Apart from `row`, whose `Read` may\n * inherit: a literal with a computed key is typed as an index signature,\n * which `Read`'s rules would have to fit too.\n */\n readonly interactions?: {\n readonly [K: InteractionKey]: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /** Narrow a field or derived member: a member is reachable only if its row is. */\n readonly members?: {\n readonly [K in MemberKeys<E>]?: {\n readonly Read?: Slot<RuleFor<User, Set, E['name']>, Redact<TypeOf<E, K>>>\n /** When absent, `Update`'s guards govern setting the member on creation too. */\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n readonly relations?: {\n readonly [K in keyof E['relations']]?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n readonly Link?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Unlink?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n /** ANDed with every surface's guards, and never out-voted by them. */\n readonly always?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n}\n\n/** One surface's guards as attached: a disjunction, and a refusal if one was chosen. */\nexport interface Surface {\n readonly rules: ReadonlyArray<AnyRule>\n readonly deny: Option.Option<Deny>\n}\n\ntype Surfaces = Readonly<Record<string, Surface>>\n\n/** An Entity's guards, every attachment merged. */\nexport interface Attachment {\n readonly set: string\n readonly unguarded: 'allow' | 'deny'\n readonly row: Surfaces\n readonly members: Readonly<Record<string, Surfaces>>\n readonly relations: Readonly<Record<string, Surfaces>>\n readonly always: ReadonlyArray<AnyRule>\n}\n\n/** Which surface a rule is asked about. */\ntype Target =\n | { readonly _tag: 'Row'; readonly interaction: string }\n | { readonly _tag: 'Member'; readonly member: string; readonly interaction: string }\n | { readonly _tag: 'Relation'; readonly relation: string; readonly interaction: string }\n\nconst record = <A>(): Record<string, A> => Object.create(null)\n\nconst appendSurface = (into: Record<string, Surface>, interaction: string, added: Surface) => {\n const before = into[interaction]\n into[interaction] =\n before === undefined\n ? added\n : {\n rules: [...before.rules, ...added.rules],\n deny: Option.orElse(added.deny, () => before.deny),\n }\n}\n\nconst appendSurfaces = (into: Record<string, Surface>, added: Surfaces) => {\n for (const [interaction, surface] of Object.entries(added)) {\n appendSurface(into, interaction, surface)\n }\n}\n\nconst freezeSurfaces = (surfaces: Record<string, Surfaces>) => {\n for (const key of Object.keys(surfaces)) Object.freeze(surfaces[key])\n return Object.freeze(surfaces)\n}\n\n/** Later attachments append to each surface's disjunction and replace its refusal. */\nconst mergeAttachments = (attachments: ReadonlyArray<Attachment>): Attachment => {\n const row = record<Surface>()\n const members = record<Record<string, Surface>>()\n const relations = record<Record<string, Surface>>()\n const always: Array<AnyRule> = []\n for (const attachment of attachments) {\n appendSurfaces(row, attachment.row)\n for (const [key, surfaces] of Object.entries(attachment.members)) {\n appendSurfaces((members[key] ??= record()), surfaces)\n }\n for (const [key, surfaces] of Object.entries(attachment.relations)) {\n appendSurfaces((relations[key] ??= record()), surfaces)\n }\n always.push(...attachment.always)\n }\n const { set, unguarded } = attachments[0]!\n return Object.freeze({\n set,\n unguarded,\n row: Object.freeze(row),\n members: freezeSurfaces(members),\n relations: freezeSurfaces(relations),\n always: Object.freeze(always),\n })\n}\n\nconst showRule = (rule: AnyRule): string =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => name,\n RowGuard: ({ name }) => name,\n All: ({ rules }) => (rules.length === 0 ? 'anyone' : `all(${rules.map(showRule).join(', ')})`),\n Inherit: ({ relation }) => `inherit(${relation})`,\n })\n\nconst showDeny = (deny: Deny): string =>\n Match.valueTags(deny, {\n NotFound: () => 'not_found',\n Omit: () => 'omit',\n Redact: ({ value }) => `redact(${JSON.stringify(value)})`,\n Forbidden: () => 'forbidden',\n Explain: ({ reason }) => `explain(${JSON.stringify(reason)})`,\n })\n\nconst notFound: Deny = Object.freeze({ _tag: 'NotFound' })\nconst omit: Deny = Object.freeze({ _tag: 'Omit' })\nconst forbidden: Deny = Object.freeze({ _tag: 'Forbidden' })\n\n/** The refusal a surface takes when none was chosen. */\nexport const defaultDeny = (target: Target): Deny =>\n target.interaction === 'Read'\n ? Match.valueTags(target, { Row: () => notFound, Member: () => omit, Relation: () => omit })\n : forbidden\n\n/** The guards a surface carries; `none` where it falls to the set's `unguarded`. */\nexport const surfaceOf = (attachment: Attachment, target: Target): Option.Option<Surface> =>\n Match.valueTags(target, {\n Row: ({ interaction }) => Option.fromUndefinedOr(attachment.row[interaction]),\n Member: ({ member, interaction }) => {\n const surfaces = attachment.members[member]\n if (surfaces === undefined) return Option.none()\n const own = surfaces[interaction]\n // A member a caller may not change is rarely one it may set freely on creation.\n return Option.fromUndefinedOr(\n own === undefined && interaction === 'Create' ? surfaces['Update'] : own,\n )\n },\n Relation: ({ relation, interaction }) =>\n Option.fromUndefinedOr(attachment.relations[relation]?.[interaction]),\n })\n\n/** Whether who may read the rows depends on who is asking: a row Read rule, or `always`. */\n/** `Guards.anyone`: a conjunction of nothing, which every principal passes. */\nexport const isAnyone = (rule: AnyRule): boolean => rule._tag === 'All' && rule.rules.length === 0\n\n/** Whether a surface's rules restrict who passes: not when one of them is `anyone`. */\nexport const restricts = (surface: Option.Option<Surface>): boolean =>\n Option.exists(surface, ({ rules }) => !rules.some(isAnyone))\n\nexport const readRowsRuled = (attachment: Attachment): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Row', interaction: 'Read' })) ||\n attachment.always.some(rule => !isAnyone(rule))\n\n/** Whether `member`, a field or a relation, has a Read rule of its own. */\nexport const readRuled = (attachment: Attachment, member: string): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })) ||\n restricts(surfaceOf(attachment, { _tag: 'Relation', relation: member, interaction: 'Read' }))\n\nconst key = Metadata.key<Attachment>('foldkit-guard/attachment', {\n merge: attachments => [mergeAttachments(attachments)],\n summarize: attachment =>\n linesOf(attachment)\n .map(([where, rule]) => `${where}: ${rule}`)\n .join('; '),\n})\n\n/** The rows of an attachment's matrix: each surface it decides, and how. */\nconst linesOf = (attachment: Attachment): ReadonlyArray<readonly [string, string]> => {\n const open = attachment.unguarded === 'allow' ? 'open' : 'closed'\n const show = (target: Target) =>\n Option.match(surfaceOf(attachment, target), {\n onNone: () => open,\n onSome: ({ rules, deny }) =>\n // An empty disjunction allows no one.\n `${rules.length === 0 ? 'nobody' : rules.map(showRule).join(' | ')} → ${showDeny(Option.getOrElse(deny, () => defaultDeny(target)))}`,\n })\n const interactions = [\n 'Read',\n 'Create',\n 'Update',\n 'Delete',\n ...Object.keys(attachment.row).filter(interaction => !builtIn.includes(interaction as never)),\n ]\n return [\n ...(attachment.always.length > 0\n ? [['always', attachment.always.map(showRule).join(' & ')] as const]\n : []),\n ...interactions.map(interaction => [interaction, show({ _tag: 'Row', interaction })] as const),\n ...Object.keys(attachment.members).flatMap(member =>\n ['Read', 'Create', 'Update'].flatMap(interaction => {\n const target: Target = { _tag: 'Member', member, interaction }\n return Option.isSome(surfaceOf(attachment, target))\n ? [[`${member}.${interaction}`, show(target)] as const]\n : []\n }),\n ),\n ...Object.entries(attachment.relations).flatMap(([relation, surfaces]) =>\n Object.keys(surfaces).map(\n interaction =>\n [\n `${relation}.${interaction}`,\n show({ _tag: 'Relation', relation, interaction }),\n ] as const,\n ),\n ),\n ]\n}\n\nconst isOn = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): slot is On<AnyRule, Deny> =>\n !Array.isArray(slot)\n\nconst surfaceFrom = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): Surface =>\n isOn(slot)\n ? { rules: slot.rules, deny: Option.some(slot.deny) }\n : { rules: Object.freeze([...slot]), deny: Option.none() }\n\n/** Throws for a row guard over another Entity that shares the target's name. */\nconst checkRules = (\n set: string,\n entity: AnyEntity,\n where: string,\n rules: ReadonlyArray<AnyRule>,\n): void => {\n for (const rule of rules) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n if (!Entity.same(guard.entity, entity)) {\n throw new Error(\n `[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, a guard over another Entity named ${entity.name}`,\n )\n }\n },\n All: ({ rules }) => checkRules(set, entity, where, rules),\n Inherit: () => {},\n })\n }\n}\n\nconst surfacesFrom = (\n set: string,\n entity: AnyEntity,\n where: string,\n slots: Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>>,\n): Surfaces => {\n const surfaces = record<Surface>()\n // `Write` goes first, whatever order the keys were written in: beside it, a\n // slot of its own adds rules to it and its refusal replaces Write's.\n const ordered = Object.entries(slots).sort(\n ([left], [right]) => Number(right === 'Write') - Number(left === 'Write'),\n )\n for (const [interaction, slot] of ordered) {\n if (slot === undefined) continue\n const added = surfaceFrom(slot)\n checkRules(set, entity, `${where}${interaction}`, added.rules)\n // Write is shorthand, so it is stored as the three it stands for.\n for (const each of interaction === 'Write' ? ['Create', 'Update', 'Delete'] : [interaction]) {\n appendSurface(surfaces, each, added)\n }\n }\n return Object.freeze(surfaces)\n}\n\nconst nested = (\n set: string,\n entity: AnyEntity,\n given: Readonly<\n Record<\n string,\n Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>> | undefined\n >\n >,\n): Readonly<Record<string, Surfaces>> => {\n const surfaces = record<Surfaces>()\n for (const [member, slots] of Object.entries(given)) {\n if (slots !== undefined) surfaces[member] = surfacesFrom(set, entity, `${member}.`, slots)\n }\n return Object.freeze(surfaces)\n}\n\n/** A row guard's own fields, and the relation an inherited Read follows. */\nconst membersRead = (rule: AnyRule): ReadonlyArray<string> =>\n Match.valueTags(rule, {\n PrincipalGuard: () => [],\n RowGuard: ({ query }) => Query.dependencies(query).predicate.map(field => field.key),\n All: ({ rules }) => rules.flatMap(membersRead),\n Inherit: ({ relation }) => [relation],\n })\n\nexport const attached = (entity: AnyEntity): Option.Option<Attachment> =>\n Option.fromUndefinedOr(key.get(entity.metadata)[0])\n\nexport const Attaching = {\n /**\n * Attaches guards to an Entity, per surface and interaction. A surface's list\n * is a disjunction; `always` is ANDed after it. Attaching twice appends to a\n * surface's list and replaces its refusal.\n */\n attach:\n <Name extends string, User, E extends AnyEntity>(\n G: {\n readonly name: Name\n readonly schema: Schema.Codec<User, unknown>\n readonly unguarded: 'allow' | 'deny'\n },\n config: Attach<NoInfer<User>, NoInfer<Name>, E>,\n ) =>\n (entity: E): E => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== G.name) {\n throw new Error(\n `[foldkit-guard] ${G.name}.attach: ${entity.name} carries the guards of ${set} already`,\n )\n }\n })\n const always = config.always ?? []\n checkRules(G.name, entity, 'always', always)\n const attachment: Attachment = Object.freeze({\n set: G.name,\n unguarded: G.unguarded,\n // A named interaction is the row's, as the matrix and the decisions read it.\n row: surfacesFrom(G.name, entity, '', { ...config.row, ...config.interactions }),\n members: nested(G.name, entity, config.members ?? {}),\n relations: nested(G.name, entity, config.relations ?? {}),\n always: Object.freeze([...always]),\n })\n // What the row's Read rules read, so a client placing rows knows it cannot judge a change to them.\n const filtered = [\n ...new Set(\n [...(attachment.row['Read']?.rules ?? []), ...attachment.always].flatMap(membersRead),\n ),\n ]\n return entity.pipe(\n Entity.annotate(Metadata.combine([key.of(attachment), ReadFilter.of(filtered)])),\n )\n },\n\n /** The guards attached to `entity`, every attachment merged. */\n attached,\n\n /** Every rule must allow, as one rule. Principal and row guards may mix. */\n all: <\n const Rules extends readonly [\n Exclude<AnyRule, Inherit<string>>,\n ...ReadonlyArray<Exclude<AnyRule, Inherit<string>>>,\n ],\n >(\n ...rules: Rules\n ): All<Rules[number]> => Object.freeze({ _tag: 'All', rules: Object.freeze([...rules]) }),\n\n /**\n * A rule everyone passes, a visitor included: a conjunction of nothing.\n * For a surface that is public under a set whose `unguarded` is `'deny'`.\n */\n anyone: Object.freeze<All<never>>({ _tag: 'All', rules: Object.freeze([]) }),\n\n /** This row's Read is the Read of the row its `one` relation points at. */\n inherit: <const Relation extends string>(relation: Relation): Inherit<Relation> =>\n Object.freeze({ _tag: 'Inherit', relation }),\n\n /** A surface's guards with a refusal other than its default. */\n on: <const Rules extends ReadonlyArray<AnyRule>, D extends Redact<unknown> | Explain>(\n rules: Rules,\n deny: D,\n ): On<Rules[number], D> => Object.freeze({ _tag: 'On', rules: Object.freeze([...rules]), deny }),\n\n /** A hidden member reads as `value`, typed by the member's schema. */\n redact: <const A>(value: A): Redact<A> => Object.freeze({ _tag: 'Redact', value }),\n\n /** A refused write tells the caller `reason`. */\n explain: (reason: string): Explain => Object.freeze({ _tag: 'Explain', reason }),\n\n /**\n * The members a row interaction's guards read, `always` included: a change\n * to one can change whether a principal may. A relation an inherited Read\n * follows counts.\n */\n guardFields: (\n entity: AnyEntity,\n interaction: 'Read' | 'Create' | 'Update' | 'Delete' | InteractionKey,\n ): ReadonlyArray<string> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [\n ...new Set(\n [...(attachment.row[interaction]?.rules ?? []), ...attachment.always].flatMap(\n membersRead,\n ),\n ),\n ],\n }),\n\n /** Who may do what, one line per surface, for review and for a committed snapshot. */\n matrix: (entities: ReadonlyArray<AnyEntity>): string =>\n entities\n .flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [`${entity.name}: no guards`],\n onSome: attachment =>\n linesOf(attachment).map(([where, rule]) => `${entity.name}.${where}: ${rule}`),\n }),\n )\n .join('\\n'),\n}\n"],"mappings":";;;;;;;;;AAsBA,MAAM,UAAU;CAAC;CAAQ;CAAU;CAAU;CAAU;CAAS;CAAQ;AAAQ;AAEhF,MAAa,cAAc;;AAEzB,OAAkC,SAAkC;CAClE,IAAK,QAAkC,SAAS,IAAI,GAClD,MAAM,IAAI,MAAM,sCAAsC,KAAK,4BAA4B;CAEzF,OAAO,OAAO,OAAO;EAAE;EAAM,KAAK;CAA6B,CAAC;AAClE,EACF;AAyIA,MAAM,eAAqC,OAAO,OAAO,IAAI;AAE7D,MAAM,iBAAiB,MAA+B,aAAqB,UAAmB;CAC5F,MAAM,SAAS,KAAK;CACpB,KAAK,eACH,WAAW,KAAA,IACP,QACA;EACE,OAAO,CAAC,GAAG,OAAO,OAAO,GAAG,MAAM,KAAK;EACvC,MAAM,OAAO,OAAO,MAAM,YAAY,OAAO,IAAI;CACnD;AACR;AAEA,MAAM,kBAAkB,MAA+B,UAAoB;CACzE,KAAK,MAAM,CAAC,aAAa,YAAY,OAAO,QAAQ,KAAK,GACvD,cAAc,MAAM,aAAa,OAAO;AAE5C;AAEA,MAAM,kBAAkB,aAAuC;CAC7D,KAAK,MAAM,OAAO,OAAO,KAAK,QAAQ,GAAG,OAAO,OAAO,SAAS,IAAI;CACpE,OAAO,OAAO,OAAO,QAAQ;AAC/B;;AAGA,MAAM,oBAAoB,gBAAuD;CAC/E,MAAM,MAAM,OA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