foldkit-guard 0.11.0 → 0.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +157 -85
- package/dist/agent.d.mts +9 -6
- package/dist/agent.d.mts.map +1 -1
- package/dist/agent.mjs +21 -13
- package/dist/agent.mjs.map +1 -1
- package/dist/{attach-CJl-GtbN.d.mts → attach-CER19mzk.d.mts} +46 -9
- package/dist/attach-CER19mzk.d.mts.map +1 -0
- package/dist/{attach-CEGlbWu5.mjs → attach-DlrBpxOl.mjs} +33 -3
- package/dist/attach-DlrBpxOl.mjs.map +1 -0
- package/dist/{condition-dNSbUHzE.mjs → condition-VNIr9gDe.mjs} +2 -4
- package/dist/condition-VNIr9gDe.mjs.map +1 -0
- package/dist/drizzle.d.mts +1 -1
- package/dist/drizzle.mjs +7 -4
- package/dist/drizzle.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +4 -4
- package/dist/{may-DprCmMgK.mjs → may-Bd6O91A-.mjs} +62 -20
- package/dist/may-Bd6O91A-.mjs.map +1 -0
- package/dist/{me-C-gX1paZ.mjs → me-Bv7I0EcH.mjs} +3 -3
- package/dist/{me-C-gX1paZ.mjs.map → me-Bv7I0EcH.mjs.map} +1 -1
- package/dist/media.d.mts +1 -1
- package/dist/{placed-CGyo-NRR.mjs → placed-Dt05PaWi.mjs} +2 -2
- package/dist/{placed-CGyo-NRR.mjs.map → placed-Dt05PaWi.mjs.map} +1 -1
- package/dist/server.d.mts +9 -2
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +96 -73
- package/dist/server.mjs.map +1 -1
- package/dist/sync.d.mts +5 -3
- package/dist/sync.d.mts.map +1 -1
- package/dist/sync.mjs +10 -6
- package/dist/sync.mjs.map +1 -1
- package/package.json +16 -16
- package/dist/attach-CEGlbWu5.mjs.map +0 -1
- package/dist/attach-CJl-GtbN.d.mts.map +0 -1
- package/dist/condition-dNSbUHzE.mjs.map +0 -1
- package/dist/may-DprCmMgK.mjs.map +0 -1
|
@@ -111,6 +111,20 @@ const attachedRules = (attachment) => flattenRules([...attachment.always, ...[
|
|
|
111
111
|
...Object.values(attachment.relations)
|
|
112
112
|
].flatMap((surfaces) => Object.values(surfaces)).flatMap((surface) => surface.rules)]);
|
|
113
113
|
const isAnyone = (rule) => rule._tag === "All" && rule.rules.length === 0;
|
|
114
|
+
/** Whether a row guard reads another row (a path, a path from the viewer, an exists): one row cannot judge it. */
|
|
115
|
+
const reachesOther = (guard) => Query.dependencies(guard.query).reaches.length > 0;
|
|
116
|
+
/**
|
|
117
|
+
* The row guards among the row's rules for `interaction` that read another
|
|
118
|
+
* row, by name, each once. A check over one row read cannot judge one: a
|
|
119
|
+
* handler's (`GuardServer.mutation`), a Sync document's, and a writer's that
|
|
120
|
+
* holds no rule in its statement, each refused where it is made.
|
|
121
|
+
*/
|
|
122
|
+
const reachingRules = (attachment, interaction) => [...new Set(flattenRules(attachment.row[interaction]?.rules ?? []).flatMap((rule) => Match.valueTags(rule, {
|
|
123
|
+
PrincipalGuard: () => [],
|
|
124
|
+
RowGuard: (guard) => reachesOther(guard) ? [guard.name] : [],
|
|
125
|
+
All: () => [],
|
|
126
|
+
Inherit: () => []
|
|
127
|
+
})))];
|
|
114
128
|
/** Whether a surface's rules restrict who passes: not when one of them is `anyone`. */
|
|
115
129
|
const restricts = (surface) => Option.exists(surface, ({ rules }) => !rules.some(isAnyone));
|
|
116
130
|
const readRowsRuled = (attachment) => restricts(surfaceOf(attachment, {
|
|
@@ -198,7 +212,7 @@ const checkRules = (set, entity, where, rules) => {
|
|
|
198
212
|
PrincipalGuard: () => {},
|
|
199
213
|
RowGuard: (guard) => {
|
|
200
214
|
if (!Entity.same(guard.entity, entity)) throw new Error(`[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, a guard over another Entity named ${entity.name}`);
|
|
201
|
-
if (!reachingSurfaces.has(where) &&
|
|
215
|
+
if (!reachingSurfaces.has(where) && reachesOther(guard)) throw new Error(`[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, which reads another row (a path or an exists); only a row's Read rule may (judged in SQL), and its Update and Delete rules (judged in the write's statement), so name those rather than Write`);
|
|
202
216
|
},
|
|
203
217
|
All: ({ rules }) => checkRules(set, entity, where, rules),
|
|
204
218
|
Inherit: () => {}
|
|
@@ -232,6 +246,21 @@ const membersRead = (rule) => Match.valueTags(rule, {
|
|
|
232
246
|
Inherit: ({ relation }) => [relation]
|
|
233
247
|
});
|
|
234
248
|
const attached = (entity) => Option.fromUndefinedOr(key.get(entity.metadata)[0]);
|
|
249
|
+
/** Each Entity some descriptor of which carries guards. */
|
|
250
|
+
const guarded = /* @__PURE__ */ new WeakSet();
|
|
251
|
+
/**
|
|
252
|
+
* `attached`, for a reader that enforces the guards (a server's Source or
|
|
253
|
+
* writer, a SQL rule, a Sync document). A descriptor without them, of an
|
|
254
|
+
* Entity another descriptor of which carries them, would be read as
|
|
255
|
+
* unguarded and serve every row open, so it throws (#539). A hint reader
|
|
256
|
+
* (`may`, a client's placement) keeps `attached`: a rule is declared over
|
|
257
|
+
* the bare descriptor before any guard is attached.
|
|
258
|
+
*/
|
|
259
|
+
const enforced = (entity) => {
|
|
260
|
+
const attachment = attached(entity);
|
|
261
|
+
if (Option.isNone(attachment) && guarded.has(entity.identity)) throw new Error(`[foldkit-guard] ${entity.name} carries guards on another descriptor of it; pass the one Guards.attach returned`);
|
|
262
|
+
return attachment;
|
|
263
|
+
};
|
|
235
264
|
const Attaching = {
|
|
236
265
|
/**
|
|
237
266
|
* Attaches guards to an Entity, per surface and interaction. A surface's list
|
|
@@ -256,6 +285,7 @@ const Attaching = {
|
|
|
256
285
|
always: Object.freeze([...always])
|
|
257
286
|
});
|
|
258
287
|
const filtered = [...new Set([...attachment.row["Read"]?.rules ?? [], ...attachment.always].flatMap(membersRead))];
|
|
288
|
+
guarded.add(entity.identity);
|
|
259
289
|
return entity.pipe(Entity.annotate(Metadata.combine([key.of(attachment), ReadFilter.of(filtered)])));
|
|
260
290
|
},
|
|
261
291
|
/** The guards attached to `entity`, every attachment merged. */
|
|
@@ -309,6 +339,6 @@ const Attaching = {
|
|
|
309
339
|
onSome: (attachment) => linesOf(attachment).map(([where, rule]) => `${entity.name}.${where}: ${rule}`)
|
|
310
340
|
})).join("\n")
|
|
311
341
|
};
|
|
312
|
-
export { defaultDeny as a,
|
|
342
|
+
export { defaultDeny as a, isAnyone as c, readRowsRuled as d, readRuled as f, attachedRules as i, reachesOther as l, surfaceOf as m, Interaction as n, enforced as o, restricts as p, attached as r, flattenRules as s, Attaching as t, reachingRules as u };
|
|
313
343
|
|
|
314
|
-
//# sourceMappingURL=attach-
|
|
344
|
+
//# sourceMappingURL=attach-DlrBpxOl.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"attach-DlrBpxOl.mjs","names":[],"sources":["../src/attach.ts"],"sourcesContent":["/**\n * Attaching a guard set's guards to an Entity, per surface and interaction,\n * as metadata only `foldkit-guard` reads. See `guard-DESIGN.md` §3.2.\n */\nimport { Match, Option, type Schema } from 'effect'\nimport { Entity, Query, ReadFilter, type AnyEntity } from 'foldkit-entity'\nimport { Metadata } from 'foldkit-metadata'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\ndeclare const InteractionBrand: unique symbol\n\n/** An interaction the application names, used as a computed key: `[Archive.key]`. */\nexport type InteractionKey<Name extends string = string> = Name & {\n readonly [InteractionBrand]: Name\n}\n\nexport interface Interaction<Name extends string> {\n readonly name: Name\n readonly key: InteractionKey<Name>\n}\n\n/** The interactions every row has, and the ones a relation member has. */\nconst builtIn = ['Read', 'Create', 'Update', 'Delete', 'Write', 'Link', 'Unlink'] as const\n\nexport const Interaction = {\n /** An interaction beyond Read, Create, Update and Delete, such as `Archive`. */\n make: <const Name extends string>(name: Name): Interaction<Name> => {\n if ((builtIn as ReadonlyArray<string>).includes(name)) {\n throw new Error(`[foldkit-guard] Interaction.make: \"${name}\" is an interaction already`)\n }\n return Object.freeze({ name, key: name as InteractionKey<Name> })\n },\n}\n\n/** Every guard of `Rules` must allow, as one guard: `Guards.all(signedIn, isOwner)`. */\nexport interface All<Rules> {\n readonly _tag: 'All'\n readonly rules: ReadonlyArray<Rules>\n}\n\n/** This row's Read is the Read of the row its `one` relation points at. */\nexport interface Inherit<Relation extends string> {\n readonly _tag: 'Inherit'\n readonly relation: Relation\n}\n\n/** What a member hidden by its Read guards reads as instead of its value. */\nexport interface Redact<A> {\n readonly _tag: 'Redact'\n readonly value: A\n}\n\n/** A refused write's sentence, for the application's own users. */\nexport interface Explain {\n readonly _tag: 'Explain'\n readonly reason: string\n}\n\n/**\n * What a refusal looks like. The defaults need no constructor: a row Read\n * answers `NotFound`, a member or relation Read `Omit`, a write `Forbidden`.\n */\nexport type Deny =\n | { readonly _tag: 'NotFound' }\n | { readonly _tag: 'Omit' }\n | Redact<unknown>\n | { readonly _tag: 'Forbidden' }\n | Explain\n\n/** A surface's guards with a refusal other than its default. */\nexport interface On<Rules, D extends Deny> {\n readonly _tag: 'On'\n readonly rules: ReadonlyArray<Rules>\n readonly deny: D\n}\n\n/** Anything a surface's list may hold, of any guard set. */\nexport type AnyRule =\n | PrincipalGuard<any, string>\n | RowGuard<any, AnyEntity, string>\n | All<any>\n | Inherit<string>\n\n/**\n * What a surface of the Entity named `Name` accepts from the guard set `Set`:\n * its principal guards, its row guards over that Entity, and conjunctions of\n * both. A row guard over another Entity, or a guard of another set, is refused.\n */\nexport type RuleFor<User, Set extends string, Name extends string> =\n | PrincipalGuard<User, Set>\n | RowGuard<User, Entity<Name, any, any, any>, Set>\n | All<RuleFor<User, Set, Name>>\n\ntype Slot<Rule, D extends Deny> = ReadonlyArray<Rule> | On<Rule, D>\n\ntype WriteSlot<Rule> = Slot<Rule, Explain>\n\ntype OneRelations<E extends AnyEntity> = {\n [K in keyof E['relations']]: E['relations'][K] extends { readonly cardinality: 'one' } ? K : never\n}[keyof E['relations']] &\n string\n\ntype MemberKeys<E extends AnyEntity> = (keyof E['fields'] | keyof E['derived']) & string\n\ntype TypeOf<E extends AnyEntity, K extends keyof E['members']> = E['members'][K]['schema']['Type']\n\n/** What `Guards.attach` takes for the Entity `E`, every key checked against it. */\nexport type Attach<User, Set extends string, E extends AnyEntity> = {\n readonly row?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']> | Inherit<OneRelations<E>>>\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Delete?: WriteSlot<RuleFor<User, Set, E['name']>>\n /** The same guards on Create, Update and Delete. */\n readonly Write?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /**\n * The row's interactions the application named, by key:\n * `{ [Archive.key]: [G.isAdmin] }`. Apart from `row`, whose `Read` may\n * inherit: a literal with a computed key is typed as an index signature,\n * which `Read`'s rules would have to fit too.\n */\n readonly interactions?: {\n readonly [K: InteractionKey]: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /** Narrow a field or derived member: a member is reachable only if its row is. */\n readonly members?: {\n readonly [K in MemberKeys<E>]?: {\n readonly Read?: Slot<RuleFor<User, Set, E['name']>, Redact<TypeOf<E, K>>>\n /** When absent, `Update`'s guards govern setting the member on creation too. */\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n readonly relations?: {\n readonly [K in keyof E['relations']]?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n readonly Link?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Unlink?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n /** ANDed with every surface's guards, and never out-voted by them. */\n readonly always?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n}\n\n/** One surface's guards as attached: a disjunction, and a refusal if one was chosen. */\nexport interface Surface {\n readonly rules: ReadonlyArray<AnyRule>\n readonly deny: Option.Option<Deny>\n}\n\ntype Surfaces = Readonly<Record<string, Surface>>\n\n/** An Entity's guards, every attachment merged. */\nexport interface Attachment {\n readonly set: string\n readonly unguarded: 'allow' | 'deny'\n readonly row: Surfaces\n readonly members: Readonly<Record<string, Surfaces>>\n readonly relations: Readonly<Record<string, Surfaces>>\n readonly always: ReadonlyArray<AnyRule>\n}\n\n/** Which surface a rule is asked about. */\ntype Target =\n | { readonly _tag: 'Row'; readonly interaction: string }\n | { readonly _tag: 'Member'; readonly member: string; readonly interaction: string }\n | { readonly _tag: 'Relation'; readonly relation: string; readonly interaction: string }\n\nconst record = <A>(): Record<string, A> => Object.create(null)\n\nconst appendSurface = (into: Record<string, Surface>, interaction: string, added: Surface) => {\n const before = into[interaction]\n into[interaction] =\n before === undefined\n ? added\n : {\n rules: [...before.rules, ...added.rules],\n deny: Option.orElse(added.deny, () => before.deny),\n }\n}\n\nconst appendSurfaces = (into: Record<string, Surface>, added: Surfaces) => {\n for (const [interaction, surface] of Object.entries(added)) {\n appendSurface(into, interaction, surface)\n }\n}\n\nconst freezeSurfaces = (surfaces: Record<string, Surfaces>) => {\n for (const key of Object.keys(surfaces)) Object.freeze(surfaces[key])\n return Object.freeze(surfaces)\n}\n\n/** Later attachments append to each surface's disjunction and replace its refusal. */\nconst mergeAttachments = (attachments: ReadonlyArray<Attachment>): Attachment => {\n const row = record<Surface>()\n const members = record<Record<string, Surface>>()\n const relations = record<Record<string, Surface>>()\n const always: Array<AnyRule> = []\n for (const attachment of attachments) {\n appendSurfaces(row, attachment.row)\n for (const [key, surfaces] of Object.entries(attachment.members)) {\n appendSurfaces((members[key] ??= record()), surfaces)\n }\n for (const [key, surfaces] of Object.entries(attachment.relations)) {\n appendSurfaces((relations[key] ??= record()), surfaces)\n }\n always.push(...attachment.always)\n }\n const { set, unguarded } = attachments[0]!\n return Object.freeze({\n set,\n unguarded,\n row: Object.freeze(row),\n members: freezeSurfaces(members),\n relations: freezeSurfaces(relations),\n always: Object.freeze(always),\n })\n}\n\nconst showRule = (rule: AnyRule): string =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => name,\n RowGuard: ({ name }) => name,\n All: ({ rules }) => (rules.length === 0 ? 'anyone' : `all(${rules.map(showRule).join(', ')})`),\n Inherit: ({ relation }) => `inherit(${relation})`,\n })\n\nconst showDeny = (deny: Deny): string =>\n Match.valueTags(deny, {\n NotFound: () => 'not_found',\n Omit: () => 'omit',\n Redact: ({ value }) => `redact(${JSON.stringify(value)})`,\n Forbidden: () => 'forbidden',\n Explain: ({ reason }) => `explain(${JSON.stringify(reason)})`,\n })\n\nconst notFound: Deny = Object.freeze({ _tag: 'NotFound' })\nconst omit: Deny = Object.freeze({ _tag: 'Omit' })\nconst forbidden: Deny = Object.freeze({ _tag: 'Forbidden' })\n\n/** The refusal a surface takes when none was chosen. */\nexport const defaultDeny = (target: Target): Deny =>\n target.interaction === 'Read'\n ? Match.valueTags(target, { Row: () => notFound, Member: () => omit, Relation: () => omit })\n : forbidden\n\n/** The guards a surface carries; `none` where it falls to the set's `unguarded`. */\nexport const surfaceOf = (attachment: Attachment, target: Target): Option.Option<Surface> =>\n Match.valueTags(target, {\n Row: ({ interaction }) => Option.fromUndefinedOr(attachment.row[interaction]),\n Member: ({ member, interaction }) => {\n const surfaces = attachment.members[member]\n if (surfaces === undefined) return Option.none()\n const own = surfaces[interaction]\n // A member a caller may not change is rarely one it may set freely on creation.\n return Option.fromUndefinedOr(\n own === undefined && interaction === 'Create' ? surfaces['Update'] : own,\n )\n },\n Relation: ({ relation, interaction }) =>\n Option.fromUndefinedOr(attachment.relations[relation]?.[interaction]),\n })\n\n/** Whether who may read the rows depends on who is asking: a row Read rule, or `always`. */\n/** `Guards.anyone`: a conjunction of nothing, which every principal passes. */\n/** The rules, each `all` opened into its parts: every guard they ask. */\nexport const flattenRules = (rules: ReadonlyArray<AnyRule>): ReadonlyArray<AnyRule> =>\n rules.flatMap(rule =>\n Match.valueTags(rule, {\n PrincipalGuard: () => [rule],\n RowGuard: () => [rule],\n All: ({ rules: parts }) => flattenRules(parts),\n Inherit: () => [rule],\n }),\n )\n\n/** Every rule attached anywhere: on the row, each member and relation, and always. */\nexport const attachedRules = (attachment: Attachment): ReadonlyArray<AnyRule> =>\n flattenRules([\n ...attachment.always,\n ...[\n attachment.row,\n ...Object.values(attachment.members),\n ...Object.values(attachment.relations),\n ]\n .flatMap(surfaces => Object.values(surfaces))\n .flatMap(surface => surface.rules),\n ])\n\nexport const isAnyone = (rule: AnyRule): boolean => rule._tag === 'All' && rule.rules.length === 0\n\n/** Whether a row guard reads another row (a path, a path from the viewer, an exists): one row cannot judge it. */\nexport const reachesOther = (guard: RowGuard<any, AnyEntity>): boolean =>\n Query.dependencies(guard.query).reaches.length > 0\n\n/**\n * The row guards among the row's rules for `interaction` that read another\n * row, by name, each once. A check over one row read cannot judge one: a\n * handler's (`GuardServer.mutation`), a Sync document's, and a writer's that\n * holds no rule in its statement, each refused where it is made.\n */\nexport const reachingRules = (\n attachment: Attachment,\n interaction: string,\n): ReadonlyArray<string> => [\n ...new Set(\n flattenRules(attachment.row[interaction]?.rules ?? []).flatMap(rule =>\n Match.valueTags(rule, {\n PrincipalGuard: () => [],\n RowGuard: guard => (reachesOther(guard) ? [guard.name] : []),\n All: () => [],\n Inherit: () => [],\n }),\n ),\n ),\n]\n\n/** Whether a surface's rules restrict who passes: not when one of them is `anyone`. */\nexport const restricts = (surface: Option.Option<Surface>): boolean =>\n Option.exists(surface, ({ rules }) => !rules.some(isAnyone))\n\nexport const readRowsRuled = (attachment: Attachment): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Row', interaction: 'Read' })) ||\n attachment.always.some(rule => !isAnyone(rule))\n\n/** Whether `member`, a field or a relation, has a Read rule of its own. */\nexport const readRuled = (attachment: Attachment, member: string): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })) ||\n restricts(surfaceOf(attachment, { _tag: 'Relation', relation: member, interaction: 'Read' }))\n\nconst key = Metadata.key<Attachment>('foldkit-guard/attachment', {\n merge: attachments => [mergeAttachments(attachments)],\n summarize: attachment =>\n linesOf(attachment)\n .map(([where, rule]) => `${where}: ${rule}`)\n .join('; '),\n})\n\n/** The rows of an attachment's matrix: each surface it decides, and how. */\nconst linesOf = (attachment: Attachment): ReadonlyArray<readonly [string, string]> => {\n const open = attachment.unguarded === 'allow' ? 'open' : 'closed'\n const show = (target: Target) =>\n Option.match(surfaceOf(attachment, target), {\n onNone: () => open,\n onSome: ({ rules, deny }) =>\n // An empty disjunction allows no one.\n `${rules.length === 0 ? 'nobody' : rules.map(showRule).join(' | ')} → ${showDeny(Option.getOrElse(deny, () => defaultDeny(target)))}`,\n })\n const interactions = [\n 'Read',\n 'Create',\n 'Update',\n 'Delete',\n ...Object.keys(attachment.row).filter(interaction => !builtIn.includes(interaction as never)),\n ]\n return [\n ...(attachment.always.length > 0\n ? [['always', attachment.always.map(showRule).join(' & ')] as const]\n : []),\n ...interactions.map(interaction => [interaction, show({ _tag: 'Row', interaction })] as const),\n ...Object.keys(attachment.members).flatMap(member =>\n ['Read', 'Create', 'Update'].flatMap(interaction => {\n const target: Target = { _tag: 'Member', member, interaction }\n return Option.isSome(surfaceOf(attachment, target))\n ? [[`${member}.${interaction}`, show(target)] as const]\n : []\n }),\n ),\n ...Object.entries(attachment.relations).flatMap(([relation, surfaces]) =>\n Object.keys(surfaces).map(\n interaction =>\n [\n `${relation}.${interaction}`,\n show({ _tag: 'Relation', relation, interaction }),\n ] as const,\n ),\n ),\n ]\n}\n\nconst isOn = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): slot is On<AnyRule, Deny> =>\n !Array.isArray(slot)\n\nconst surfaceFrom = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): Surface =>\n isOn(slot)\n ? { rules: slot.rules, deny: Option.some(slot.deny) }\n : { rules: Object.freeze([...slot]), deny: Option.none() }\n\n/**\n * The row surfaces a rule that reads another row may sit on: Read, compiled\n * to SQL, and Update and Delete, judged in the write's own statement. Every\n * other is judged over one row in memory.\n */\nconst reachingSurfaces = new Set(['Read', 'Update', 'Delete'])\n\n/**\n * Throws for a row guard over another Entity that shares the target's name,\n * and, where the surface is judged over one row in memory, for one that reads\n * another row.\n */\nconst checkRules = (\n set: string,\n entity: AnyEntity,\n where: string,\n rules: ReadonlyArray<AnyRule>,\n): void => {\n for (const rule of rules) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n if (!Entity.same(guard.entity, entity)) {\n throw new Error(\n `[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, a guard over another Entity named ${entity.name}`,\n )\n }\n if (!reachingSurfaces.has(where) && reachesOther(guard)) {\n throw new Error(\n `[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, which reads another row (a path or an exists); only a row's Read rule may (judged in SQL), and its Update and Delete rules (judged in the write's statement), so name those rather than Write`,\n )\n }\n },\n All: ({ rules }) => checkRules(set, entity, where, rules),\n Inherit: () => {},\n })\n }\n}\n\nconst surfacesFrom = (\n set: string,\n entity: AnyEntity,\n where: string,\n slots: Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>>,\n): Surfaces => {\n const surfaces = record<Surface>()\n // `Write` goes first, whatever order the keys were written in: beside it, a\n // slot of its own adds rules to it and its refusal replaces Write's.\n const ordered = Object.entries(slots).sort(\n ([left], [right]) => Number(right === 'Write') - Number(left === 'Write'),\n )\n for (const [interaction, slot] of ordered) {\n if (slot === undefined) continue\n const added = surfaceFrom(slot)\n checkRules(set, entity, `${where}${interaction}`, added.rules)\n // Write is shorthand, so it is stored as the three it stands for.\n for (const each of interaction === 'Write' ? ['Create', 'Update', 'Delete'] : [interaction]) {\n appendSurface(surfaces, each, added)\n }\n }\n return Object.freeze(surfaces)\n}\n\nconst nested = (\n set: string,\n entity: AnyEntity,\n given: Readonly<\n Record<\n string,\n Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>> | undefined\n >\n >,\n): Readonly<Record<string, Surfaces>> => {\n const surfaces = record<Surfaces>()\n for (const [member, slots] of Object.entries(given)) {\n if (slots !== undefined) surfaces[member] = surfacesFrom(set, entity, `${member}.`, slots)\n }\n return Object.freeze(surfaces)\n}\n\n/** A row guard's own fields, and the relation an inherited Read follows. */\nconst membersRead = (rule: AnyRule): ReadonlyArray<string> =>\n Match.valueTags(rule, {\n PrincipalGuard: () => [],\n RowGuard: ({ query }) => Query.dependencies(query).predicate.map(field => field.key),\n All: ({ rules }) => rules.flatMap(membersRead),\n Inherit: ({ relation }) => [relation],\n })\n\nexport const attached = (entity: AnyEntity): Option.Option<Attachment> =>\n Option.fromUndefinedOr(key.get(entity.metadata)[0])\n\n/** Each Entity some descriptor of which carries guards. */\nconst guarded = new WeakSet<AnyEntity['identity']>()\n\n/**\n * `attached`, for a reader that enforces the guards (a server's Source or\n * writer, a SQL rule, a Sync document). A descriptor without them, of an\n * Entity another descriptor of which carries them, would be read as\n * unguarded and serve every row open, so it throws (#539). A hint reader\n * (`may`, a client's placement) keeps `attached`: a rule is declared over\n * the bare descriptor before any guard is attached.\n */\nexport const enforced = (entity: AnyEntity): Option.Option<Attachment> => {\n const attachment = attached(entity)\n if (Option.isNone(attachment) && guarded.has(entity.identity)) {\n throw new Error(\n `[foldkit-guard] ${entity.name} carries guards on another descriptor of it; pass the one Guards.attach returned`,\n )\n }\n return attachment\n}\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 // Recorded once nothing above can refuse the attachment.\n guarded.add(entity.identity)\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,O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AAC,OAAO,UAAU,GAAG,OAAO,KAAK,GAAG,MAAM,IAAI,MAAM;CACjF,CAAC,CACH,CAAC,CACA,KAAK,IAAI;AAChB"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { a as defaultDeny,
|
|
1
|
+
import { a as defaultDeny, l as reachesOther, m as surfaceOf, r as attached } from "./attach-DlrBpxOl.mjs";
|
|
2
2
|
import { Effect, Match, Option } from "effect";
|
|
3
3
|
import { Held, Judge, Query, evaluateEach, viewerIdOf } from "foldkit-entity";
|
|
4
4
|
// src/condition.ts
|
|
@@ -8,8 +8,6 @@ import { Held, Judge, Query, evaluateEach, viewerIdOf } from "foldkit-entity";
|
|
|
8
8
|
* interpreter runs (`evaluate` in memory, SQL in a binding). Principal guards
|
|
9
9
|
* never reach it, so their bodies stay on the server that decided them.
|
|
10
10
|
*/
|
|
11
|
-
/** Whether a row guard reads another row: one row cannot judge it. */
|
|
12
|
-
const reachesOther = (guard) => Query.dependencies(guard.query).reaches.length > 0;
|
|
13
11
|
const always = Object.freeze({ _tag: "Always" });
|
|
14
12
|
const never = Object.freeze({ _tag: "Never" });
|
|
15
13
|
/** A conjunction, with what it settles already folded away. */
|
|
@@ -302,4 +300,4 @@ const rowTarget = (interaction) => ({
|
|
|
302
300
|
});
|
|
303
301
|
export { deciding as n, readsPrincipal as r, Condition as t };
|
|
304
302
|
|
|
305
|
-
//# sourceMappingURL=condition-
|
|
303
|
+
//# sourceMappingURL=condition-VNIr9gDe.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"condition-VNIr9gDe.mjs","names":[],"sources":["../src/condition.ts"],"sourcesContent":["/**\n * What an attachment's read rules come to for one principal, once its\n * principal guards are decided: a condition over the row, which an\n * interpreter runs (`evaluate` in memory, SQL in a binding). Principal guards\n * never reach it, so their bodies stay on the server that decided them.\n */\nimport { Effect, Match, Option } from 'effect'\nimport {\n Held,\n Judge,\n Query,\n evaluateEach,\n viewerIdOf,\n type AnyEntity,\n type EntityRef,\n type ExprContext,\n type HeldRow,\n type HeldRows,\n type MemoryOperators,\n} from 'foldkit-entity'\nimport {\n attached,\n defaultDeny,\n reachesOther,\n surfaceOf,\n type AnyRule,\n type Deny,\n} from './attach.js'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\nexport type Condition =\n | { readonly _tag: 'Always' }\n | { readonly _tag: 'Never' }\n /** A row guard, and what its `Expr.viewer` reads: the principal it was decided for. */\n | {\n readonly _tag: 'Row'\n readonly guard: RowGuard<any, AnyEntity>\n readonly context: ExprContext\n }\n /** The row its `one` relation points at is readable. */\n | { readonly _tag: 'Inherit'; readonly relation: string }\n | { readonly _tag: 'And'; readonly conditions: ReadonlyArray<Condition> }\n | { readonly _tag: 'Or'; readonly conditions: ReadonlyArray<Condition> }\n\nconst always: Condition = Object.freeze({ _tag: 'Always' })\nconst never: Condition = Object.freeze({ _tag: 'Never' })\n\n/** A conjunction, with what it settles already folded away. */\nconst and = (conditions: ReadonlyArray<Condition>): Condition => {\n const kept: Array<Condition> = []\n for (const condition of conditions) {\n if (condition._tag === 'Never') return never\n if (condition._tag !== 'Always') kept.push(condition)\n }\n if (kept.length === 0) return always\n if (kept.length === 1) return kept[0]!\n return Object.freeze({ _tag: 'And', conditions: Object.freeze(kept) })\n}\n\n/** A disjunction, with what it settles already folded away. */\nconst or = (conditions: ReadonlyArray<Condition>): Condition => {\n const kept: Array<Condition> = []\n for (const condition of conditions) {\n if (condition._tag === 'Always') return always\n if (condition._tag !== 'Never') kept.push(condition)\n }\n if (kept.length === 0) return never\n if (kept.length === 1) return kept[0]!\n return Object.freeze({ _tag: 'Or', conditions: Object.freeze(kept) })\n}\n\nexport const Condition = {\n always,\n never,\n and,\n or,\n\n /**\n * Whether a row's stored values meet `condition`, its row guards read with\n * `input` (the principal's, from `G.inputOf`). `inherit` answers whether the\n * row a relation points at is readable, which only the caller can look up.\n * `operators` runs the guards' primitive operators: the policy's.\n *\n * A row guard the row's own values make an operator refuse (text holding a\n * NUL, an implementation that throws) does not hold: what a write supplies\n * can deny it, never end the request.\n */\n holds: (\n condition: Condition,\n values: Readonly<Record<string, unknown>>,\n input: Readonly<Record<string, unknown>>,\n inherit: (relation: string) => boolean,\n operators: MemoryOperators,\n ): boolean => {\n const holds = (each: Condition): boolean =>\n Match.valueTags(each, {\n Always: () => true,\n Never: () => false,\n // A row as a Source reads it holds its links as ref keys; the rule reads ids.\n Row: ({ guard, context }) =>\n evaluateEach(guard.query, input, [Held.fromRefs(guard.query, values)], {\n operators,\n context,\n }).matched.length === 1,\n Inherit: ({ relation }) => inherit(relation),\n And: ({ conditions }) => conditions.every(holds),\n Or: ({ conditions }) => conditions.some(holds),\n })\n return holds(condition)\n },\n\n /**\n * `condition` decided over one row as far as one row can: each row guard\n * over the row alone judged (`holds`), an inherited Read refused, as a\n * writer refuses one, and each row guard that reads another row (a path, an\n * exists) kept for a statement to judge. `Always` or `Never` when the row\n * alone decides it.\n */\n residual: (\n condition: Condition,\n values: Readonly<Record<string, unknown>>,\n input: Readonly<Record<string, unknown>>,\n operators: MemoryOperators,\n ): Condition => {\n const decided = (each: Condition): Condition =>\n Match.valueTags(each, {\n Always: () => each,\n Never: () => each,\n Row: row =>\n reachesOther(row.guard)\n ? each\n : Condition.holds(each, values, input, () => false, operators)\n ? always\n : never,\n Inherit: () => never,\n And: ({ conditions }) => and(conditions.map(decided)),\n Or: ({ conditions }) => or(conditions.map(decided)),\n })\n return decided(condition)\n },\n\n /** `Always` and `Never` as what one row decided; none where a statement must judge the rest. */\n decided: (condition: Condition): Option.Option<boolean> =>\n Match.valueTags(condition, {\n Always: () => Option.some(true),\n Never: () => Option.some(false),\n Row: () => Option.none(),\n Inherit: () => Option.none(),\n And: () => Option.none(),\n Or: () => Option.none(),\n }),\n\n /**\n * The members of `written`, the row a write changes, that a condition's\n * guards reading another row start from: each one's fields, the relation\n * each path leaves by, and, where `written` is the viewer's own row, what a\n * path from the viewer leaves it by. A write that changes one would need the\n * guard judged over the row it leaves, which a statement over the stored row\n * does not do.\n */\n reachedFrom: (condition: Condition, written: EntityRef): ReadonlyArray<string> => {\n const read = (each: Condition): ReadonlyArray<string> =>\n Match.valueTags(each, {\n Always: () => [],\n Never: () => [],\n Row: ({ guard, context }) => {\n if (!reachesOther(guard)) return []\n const dependencies = Query.dependencies(guard.query)\n return [\n ...dependencies.predicate.map(field => field.key),\n // An exists reached through a path leaves by its first relation as surely\n // as a path does; one over the row itself reads only its id. A path from the\n // viewer leaves the row written the same way when that row is the viewer's.\n ...dependencies.reaches.flatMap(reach =>\n Match.valueTags(reach, {\n Path: ({ via }) => [via[0]!.key],\n Exists: ({ via }) => via.slice(0, 1).map(relation => relation.key),\n ViewerPath: ({ viewer, via, field }) => {\n const start = viewer.target()\n return start.name === written.entity &&\n Option.exists(viewerIdOf(start, context), id => id === written.id)\n ? [via[0]?.key ?? field.key]\n : []\n },\n }),\n ),\n ]\n },\n Inherit: () => [],\n And: ({ conditions }) => conditions.flatMap(read),\n Or: ({ conditions }) => conditions.flatMap(read),\n })\n return [...new Set(read(condition))]\n },\n\n /**\n * Whether a row a client holds meets `condition`, a part it cannot decide\n * taken to be `assumed`: a row guard over the principal's fields, which a\n * client is not given, an inherited Read, and a rule over a row or field\n * the holder lacks. A row guard reads the holder's rows (`rows`) where it\n * follows a path from the viewer. Run once assuming each way, it is decided\n * where both agree, since no part of a condition is negated.\n */\n judge: (condition: Condition, row: HeldRow, rows: HeldRows, assumed: boolean): boolean => {\n const judge = (each: Condition): boolean =>\n Match.valueTags(each, {\n Always: () => true,\n Never: () => false,\n Row: ({ guard, context }) =>\n readsPrincipal(guard)\n ? assumed\n : Judge.match(Judge.predicate(guard.body, row, { context, rows }), {\n // SQL's null leaves a row out, as false does.\n onKnown: truth => truth === true,\n onUnknown: () => assumed,\n }),\n Inherit: () => assumed,\n And: ({ conditions }) => conditions.every(judge),\n Or: ({ conditions }) => conditions.some(judge),\n })\n return judge(condition)\n },\n\n /**\n * `condition` with every row guard that reads one of `unset`, and every\n * relation of them it follows, refused: a field a create leaves unset\n * matches no guard, `isNull` and `isNotNull` alike, since the create never\n * said what it holds.\n */\n unsetting: (condition: Condition, unset: ReadonlySet<string>): Condition => {\n const kept = (each: Condition): Condition =>\n Match.valueTags(each, {\n Always: () => each,\n Never: () => each,\n Row: ({ guard }) =>\n Query.dependencies(guard.query).predicate.some(field => unset.has(field.key))\n ? never\n : each,\n Inherit: ({ relation }) => (unset.has(relation) ? never : each),\n And: ({ conditions }) => and(conditions.map(kept)),\n Or: ({ conditions }) => or(conditions.map(kept)),\n })\n return kept(condition)\n },\n\n /** The members a condition reads: its row guards' fields, and each relation it follows. */\n members: (condition: Condition): ReadonlyArray<string> => {\n const read = (each: Condition): ReadonlyArray<string> =>\n Match.valueTags(each, {\n Always: () => [],\n Never: () => [],\n Row: ({ guard }) => Query.dependencies(guard.query).predicate.map(field => field.key),\n Inherit: ({ relation }) => [relation],\n And: ({ conditions }) => conditions.flatMap(read),\n Or: ({ conditions }) => conditions.flatMap(read),\n })\n return [...new Set(read(condition))]\n },\n}\n\n/** A member's read rule for one principal: the condition, and what a refusal shows. */\nexport interface MemberRead {\n readonly member: string\n readonly condition: Condition\n readonly deny: Deny\n}\n\n/**\n * Whether a row guard reads the principal's fields. A visitor has none, so\n * passes no guard that does; one over the row alone (`publishedAt` is set)\n * holds for a visitor as for anyone.\n */\nexport const readsPrincipal = (guard: RowGuard<any, AnyEntity>): boolean =>\n Query.dependencies(guard.query).inputs.length > 0\n\n/** Every principal guard the rules name, each once. */\nconst principalGuardsIn = (rules: ReadonlyArray<AnyRule>): ReadonlyArray<PrincipalGuard<any>> => {\n const found = new Map<string, PrincipalGuard<any>>()\n const visit = (rule: AnyRule): void =>\n Match.valueTags(rule, {\n PrincipalGuard: guard => void found.set(guard.name, guard),\n RowGuard: () => {},\n All: ({ rules }) => rules.forEach(visit),\n Inherit: () => {},\n })\n rules.forEach(visit)\n return [...found.values()]\n}\n\n/**\n * Turns `rules` into a condition for one principal. Each principal guard is\n * decided once, however many rules name it; a visitor passes no row guard\n * that reads the principal.\n */\nconst conditionsFor = <R>(\n rules: ReadonlyArray<AnyRule>,\n decide: (guard: PrincipalGuard<any>) => Effect.Effect<boolean, never, R>,\n visitor: boolean,\n context: ExprContext,\n): Effect.Effect<(rules: ReadonlyArray<AnyRule>, join: typeof and) => Condition, never, R> =>\n Effect.map(\n Effect.forEach(principalGuardsIn(rules), guard =>\n Effect.map(decide(guard), allowed => [guard.name, allowed] as const),\n ),\n decisions => {\n const allowed = new Map(decisions)\n const conditionOf = (rule: AnyRule): Condition =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => (allowed.get(name) === true ? always : never),\n RowGuard: guard =>\n visitor && readsPrincipal(guard)\n ? never\n : Object.freeze({ _tag: 'Row' as const, guard, context }),\n All: ({ rules }) => and(rules.map(conditionOf)),\n Inherit: ({ relation }) => Object.freeze({ _tag: 'Inherit' as const, relation }),\n })\n return (rules, join) => join(rules.map(conditionOf))\n },\n )\n\n/** A row's rule for one interaction and principal: the condition, and what a refusal shows. */\nexport interface RowRule {\n readonly condition: Condition\n readonly deny: Deny\n}\n\n/**\n * How a Policy decides one interaction, given the set's principal guards as\n * decided for it.\n */\nexport const deciding = <R>(\n decide: (guard: PrincipalGuard<any>) => Effect.Effect<boolean, never, R>,\n visitor: boolean,\n interaction: string,\n context: ExprContext,\n) => ({\n /** Who may do it to which rows of `entity`: `always`, then the row's rules for it. */\n row: (entity: AnyEntity): Effect.Effect<RowRule, never, R> =>\n Option.match(attached(entity), {\n onNone: () =>\n Effect.succeed({ condition: always, deny: defaultDeny(rowTarget(interaction)) }),\n onSome: attachment => {\n const target = rowTarget(interaction)\n const row = surfaceOf(attachment, target)\n const rules = Option.match(row, {\n onNone: (): ReadonlyArray<AnyRule> => [],\n onSome: ({ rules }) => rules,\n })\n // An interaction left without rules falls to the set's default.\n const unguarded = attachment.unguarded === 'allow' ? always : never\n return Effect.map(\n conditionsFor([...attachment.always, ...rules], decide, visitor, context),\n condition => ({\n condition: and([\n condition(attachment.always, and),\n Option.isSome(row) ? condition(rules, or) : unguarded,\n ]),\n deny: Option.getOrElse(\n Option.flatMap(row, ({ deny }) => deny),\n () => defaultDeny(target),\n ),\n }),\n )\n },\n }),\n\n /**\n * The rule of each of `members` that has one for this interaction. One\n * without follows its row. A relation key's Read is its relation's, decided\n * over the parent row as a member's is.\n */\n members: (\n entity: AnyEntity,\n members: ReadonlyArray<string>,\n ): Effect.Effect<ReadonlyArray<MemberRead>, never, R> =>\n Option.match(attached(entity), {\n onNone: () => Effect.succeed([]),\n onSome: attachment => {\n const surfaces = members.flatMap(member => {\n const target = Object.hasOwn(entity.relations, member)\n ? ({ _tag: 'Relation', relation: member, interaction } as const)\n : ({ _tag: 'Member', member, interaction } as const)\n return Option.match(surfaceOf(attachment, target), {\n onNone: () => [],\n onSome: ({ rules, deny }) => [\n { member, rules, deny: Option.getOrElse(deny, () => defaultDeny(target)) },\n ],\n })\n })\n return Effect.map(\n conditionsFor(\n surfaces.flatMap(({ rules }) => rules),\n decide,\n visitor,\n context,\n ),\n condition =>\n surfaces.map(({ member, rules, deny }) => ({\n member,\n condition: condition(rules, or),\n deny,\n })),\n )\n },\n }),\n\n /** A relation's rule for this interaction (`Link`, `Unlink`), when it has one. */\n relation: (\n entity: AnyEntity,\n relation: string,\n ): Effect.Effect<Option.Option<RowRule>, never, R> => {\n const target = { _tag: 'Relation', relation, interaction } as const\n return Option.match(\n Option.flatMap(attached(entity), attachment => surfaceOf(attachment, target)),\n {\n onNone: () => Effect.succeed(Option.none()),\n onSome: ({ rules, deny }) =>\n Effect.map(conditionsFor(rules, decide, visitor, context), condition =>\n Option.some({\n condition: condition(rules, or),\n deny: Option.getOrElse(deny, () => defaultDeny(target)),\n }),\n ),\n },\n )\n },\n})\n\nconst rowTarget = (interaction: string) => ({ _tag: 'Row', interaction }) as const\n"],"mappings":";;;;;;;;;;AA4CA,MAAM,SAAoB,OAAO,OAAO,EAAE,MAAM,SAAS,CAAC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,YAAY,MAAM,CAAC;KAAE,CAC3E;IACF,CAAC;GACH,CAAC;GACD,OAAO,OAAO,IACZ,cACE,SAAS,SAAS,EAAE,YAAY,KAAK,GACrC,QACA,SACA,OACF,IACA,cACE,SAAS,KAAK,EAAE,QAAQ,OAAO,YAAY;IACzC;IACA,WAAW,UAAU,OAAO,EAAE;IAC9B;GACF,EAAE,CACN;EACF;CACF,CAAC;;CAGH,WACE,QACA,aACoD;EACpD,MAAM,SAAS;GAAE,MAAM;GAAY;GAAU;EAAY;EACzD,OAAO,OAAO,MACZ,OAAO,QAAQ,SAAS,MAAM,IAAG,eAAc,UAAU,YAAY,MAAM,CAAC,GAC5E;GACE,cAAc,OAAO,QAAQ,OAAO,KAAK,CAAC;GAC1C,SAAS,EAAE,OAAO,WAChB,OAAO,IAAI,cAAc,OAAO,QAAQ,SAAS,OAAO,IAAG,cACzD,OAAO,KAAK;IACV,WAAW,UAAU,OAAO,EAAE;IAC9B,MAAM,OAAO,UAAU,YAAY,YAAY,MAAM,CAAC;GACxD,CAAC,CACH;EACJ,CACF;CACF;AACF;AAEA,MAAM,aAAa,iBAAyB;CAAE,MAAM;CAAO;AAAY"}
|
package/dist/drizzle.d.mts
CHANGED
package/dist/drizzle.mjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { o as
|
|
2
|
-
import { n as rowRules } from "./placed-
|
|
1
|
+
import { o as enforced, s as flattenRules } from "./attach-DlrBpxOl.mjs";
|
|
2
|
+
import { n as rowRules } from "./placed-Dt05PaWi.mjs";
|
|
3
3
|
import { Effect, Match, Option } from "effect";
|
|
4
4
|
import { Query } from "foldkit-entity";
|
|
5
5
|
import { RemoteServerError } from "foldkit-remote-server";
|
|
@@ -15,7 +15,7 @@ function fail(message) {
|
|
|
15
15
|
throw new Error(`[foldkit-guard] GuardDrizzle.visible: ${message}`);
|
|
16
16
|
}
|
|
17
17
|
/** Every rule that decides who may read a row of `entity`. */
|
|
18
|
-
const readRules = (entity) => Option.match(
|
|
18
|
+
const readRules = (entity) => Option.match(enforced(entity), {
|
|
19
19
|
onNone: () => [],
|
|
20
20
|
onSome: (attachment) => [...attachment.always, ...attachment.row["Read"]?.rules ?? []]
|
|
21
21
|
});
|
|
@@ -94,7 +94,10 @@ visible: (policy, entities, options = {}) => {
|
|
|
94
94
|
if (!policy.isPrincipal(principal)) return Effect.die(/* @__PURE__ */ new Error(`[foldkit-guard] ${name}: the principal is not an Option of the guard set's`));
|
|
95
95
|
return Effect.flatMap(Effect.forEach(reaches.get(name), (each) => Effect.map(policy.readable(byName.get(each), principal), (condition) => [each, condition])), (decided) => Effect.try({
|
|
96
96
|
try: () => compile(name, self, new Map(decided), policy.inputOf(principal)),
|
|
97
|
-
catch: (
|
|
97
|
+
catch: (cause) => new RemoteServerError({
|
|
98
|
+
message: `${name}'s Read rule could not be compiled to SQL`,
|
|
99
|
+
cause
|
|
100
|
+
})
|
|
98
101
|
}));
|
|
99
102
|
};
|
|
100
103
|
return Object.fromEntries(entities.map((entity) => [entity.name, rowRules.add(visible(entity.name), policy, [entity])]));
|
package/dist/drizzle.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"drizzle.mjs","names":[],"sources":["../src/drizzle.ts"],"sourcesContent":["/**\n * A guard set's read rules as `foldkit-remote-drizzle` bindings' `visible`:\n * each principal guard decided, what is left compiled to SQL over the table,\n * and an inherited Read a subquery over the related table's own rule.\n */\nimport { and, or, sql, type SQL } from 'drizzle-orm'\nimport { Effect, Match, Option } from 'effect'\nimport { Query, type AnyEntity } from 'foldkit-entity'\nimport {\n DrizzleOperators,\n bodyOperations,\n compileWhere,\n idColumn,\n type AnyEntityBinding,\n type Visible,\n} from 'foldkit-remote-drizzle'\nimport { RemoteServerError } from 'foldkit-remote-server'\nimport { attached, flattenRules, type AnyRule } from './attach.js'\nimport type { Condition } from './condition.js'\nimport type { Policy } from './index.js'\nimport { rowRules } from './placed.js'\n\n// A declaration, not an arrow, so a call narrows what follows it.\nfunction fail(message: string): never {\n throw new Error(`[foldkit-guard] GuardDrizzle.visible: ${message}`)\n}\n\n/** Every rule that decides who may read a row of `entity`. */\nconst readRules = (entity: AnyEntity): ReadonlyArray<AnyRule> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [...attachment.always, ...(attachment.row['Read']?.rules ?? [])],\n })\n\nconst nothing = sql`1 = 0`\n\nexport const GuardDrizzle = {\n /**\n * The `visible` rule of each of `entities`, the Entities as `Guards.attach`\n * returned them, by name, for `bind`'s storage. Checked here, before any\n * request: a row guard this compiler cannot run, and an inherited Read whose\n * Entity is not listed, has no Read rule, or leads back to itself, throw.\n * `operators` is the SQL table each rule is checked against here and compiled\n * by (the kernel's when not given), and the policy's table decides what a rule\n * reads from the input alone, so a server that starts can compile every rule\n * whatever table its bindings were given. Give it the bindings' SQL table, so\n * a rule and a query over one operator compile it alike.\n *\n * ```ts\n * const visible = GuardDrizzle.visible(Policy, [Todo, Project])\n * bind(Domain, { Todo: { table: todos, visible: visible.Todo, … }, … })\n * ```\n */\n visible: <User, const Es extends ReadonlyArray<AnyEntity>>(\n policy: Policy<User>,\n entities: Es,\n options: { readonly operators?: DrizzleOperators | undefined } = {},\n ): { readonly [K in Es[number]['name']]: Visible } => {\n const sqlOperators = options.operators ?? DrizzleOperators.kernel\n const byName = new Map(entities.map(entity => [entity.name, entity] as const))\n const inherits = new Map<string, ReadonlyArray<string>>()\n for (const entity of entities) {\n const targets: Array<string> = []\n for (const rule of flattenRules(readRules(entity))) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n const missing = Query.unsupported(guard.query, bodyOperations, sqlOperators)\n if (missing.length > 0) {\n fail(\n `${entity.name}'s ${guard.name} needs ${missing.join(', ')}, which SQL here does not run`,\n )\n }\n },\n All: () => {},\n Inherit: ({ relation }) => {\n const target = entity.relations[relation]!.target().name\n const guarded = byName.get(target)\n if (guarded === undefined) {\n fail(`${entity.name} inherits ${target}'s Read, but ${target} is not listed`)\n }\n if (readRules(guarded).length === 0) {\n fail(`${entity.name} inherits ${target}'s Read, but ${target} has no Read rule`)\n }\n targets.push(target)\n },\n })\n }\n inherits.set(entity.name, targets)\n }\n // A loop of inherited Reads would be a subquery that never ends.\n const closure = (name: string, path: ReadonlyArray<string>): ReadonlyArray<string> => {\n if (path.includes(name)) fail(`inherited Reads loop: ${[...path, name].join(' → ')}`)\n return [name, ...(inherits.get(name) ?? []).flatMap(next => closure(next, [...path, name]))]\n }\n const reaches = new Map(\n entities.map(entity => [entity.name, [...new Set(closure(entity.name, []))]]),\n )\n\n const compile = (\n name: string,\n binding: AnyEntityBinding,\n conditions: ReadonlyMap<string, Condition>,\n input: Readonly<Record<string, unknown>>,\n ): SQL | undefined => {\n const of = (condition: Condition): SQL | undefined =>\n Match.valueTags(condition, {\n Always: () => undefined,\n Never: () => nothing,\n // By the tables the rule was checked against: the SQL one given here, and\n // the policy's for what is decided from the input alone, as Guard judges.\n // A rule reads the rows it reaches as they are stored: it is the server's\n // decision, as a principal guard's body is, not a read by the principal.\n Row: ({ guard, context }) =>\n and(\n ...compileWhere(\n guard.query,\n {\n ...binding,\n operators: { memory: policy.operators, sql: sqlOperators },\n context,\n visibleOf: () => Option.none(),\n },\n input,\n `${name}.${guard.name}`,\n ),\n ),\n And: ({ conditions: parts }) => and(...parts.map(of)),\n // `Condition.or` folds away a part that admits every row, so each part here is SQL.\n Or: ({ conditions: parts }) => or(...parts.map(of)),\n Inherit: ({ relation }) => {\n const storage = binding.relations[relation]\n if (storage === undefined || storage.kind !== 'one') {\n return fail(\n `${name}.${relation} is inherited, so it must be stored as a foreign key here`,\n )\n }\n const target = storage.entity\n const where = compile(target.name, target, conditions, input) ?? sql`1 = 1`\n return sql`${storage.field} in (select ${idColumn(target)} from ${target.table} where ${where})`\n },\n })\n return of(conditions.get(name)!)\n }\n\n const visible =\n (name: string): Visible =>\n (principal, self) => {\n if (!policy.isPrincipal(principal)) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: the principal is not an Option of the guard set's`),\n )\n }\n return Effect.flatMap(\n Effect.forEach(reaches.get(name)!, each =>\n Effect.map(\n policy.readable(byName.get(each)!, principal),\n condition => [each, condition] as const,\n ),\n ),\n decided =>\n Effect.try({\n try: () => compile(name, self, new Map(decided), policy.inputOf(principal)),\n catch: error =>\n new RemoteServerError({\n message: error instanceof Error ? error.message : String(error),\n }),\n }),\n )\n }\n return Object.fromEntries(\n entities.map(entity => [entity.name, rowRules.add(visible(entity.name), policy, [entity])]),\n ) as {\n readonly [K in Es[number]['name']]: Visible\n }\n },\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,SAAS,KAAK,SAAwB;CACpC,MAAM,IAAI,MAAM,yCAAyC,SAAS;AACpE;;AAGA,MAAM,aAAa,WACjB,OAAO,MAAM,SAAS,MAAM,GAAG;CAC7B,cAAc,CAAC;CACf,SAAQ,eAAc,CAAC,GAAG,WAAW,QAAQ,GAAI,WAAW,IAAI,OAAO,EAAE,SAAS,CAAC,CAAE;AACvF,CAAC;AAEH,MAAM,UAAU,GAAG;AAEnB,MAAa,eAAe;;;;;;;;;;;;;;;;;AAiB1B,UACE,QACA,UACA,UAAiE,CAAC,MACd;CACpD,MAAM,eAAe,QAAQ,aAAa,iBAAiB;CAC3D,MAAM,SAAS,IAAI,IAAI,SAAS,KAAI,WAAU,CAAC,OAAO,MAAM,MAAM,CAAU,CAAC;CAC7E,MAAM,2BAAW,IAAI,IAAmC;CACxD,KAAK,MAAM,UAAU,UAAU;EAC7B,MAAM,UAAyB,CAAC;EAChC,KAAK,MAAM,QAAQ,aAAa,UAAU,MAAM,CAAC,GAC/C,MAAM,UAAU,MAAM;GACpB,sBAAsB,CAAC;GACvB,WAAU,UAAS;IACjB,MAAM,UAAU,MAAM,YAAY,MAAM,OAAO,gBAAgB,YAAY;IAC3E,IAAI,QAAQ,SAAS,GACnB,KACE,GAAG,OAAO,KAAK,KAAK,MAAM,KAAK,SAAS,QAAQ,KAAK,IAAI,EAAE,8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ldkit-remote-drizzle` bindings' `visible`:\n * each principal guard decided, what is left compiled to SQL over the table,\n * and an inherited Read a subquery over the related table's own rule.\n */\nimport { and, or, sql, type SQL } from 'drizzle-orm'\nimport { Effect, Match, Option } from 'effect'\nimport { Query, type AnyEntity } from 'foldkit-entity'\nimport {\n DrizzleOperators,\n bodyOperations,\n compileWhere,\n idColumn,\n type AnyEntityBinding,\n type Visible,\n} from 'foldkit-remote-drizzle'\nimport { RemoteServerError } from 'foldkit-remote-server'\nimport { enforced, flattenRules, type AnyRule } from './attach.js'\nimport type { Condition } from './condition.js'\nimport type { Policy } from './index.js'\nimport { rowRules } from './placed.js'\n\n// A declaration, not an arrow, so a call narrows what follows it.\nfunction fail(message: string): never {\n throw new Error(`[foldkit-guard] GuardDrizzle.visible: ${message}`)\n}\n\n/** Every rule that decides who may read a row of `entity`. */\nconst readRules = (entity: AnyEntity): ReadonlyArray<AnyRule> =>\n Option.match(enforced(entity), {\n onNone: () => [],\n onSome: attachment => [...attachment.always, ...(attachment.row['Read']?.rules ?? [])],\n })\n\nconst nothing = sql`1 = 0`\n\nexport const GuardDrizzle = {\n /**\n * The `visible` rule of each of `entities`, the Entities as `Guards.attach`\n * returned them, by name, for `bind`'s storage. Checked here, before any\n * request: a row guard this compiler cannot run, and an inherited Read whose\n * Entity is not listed, has no Read rule, or leads back to itself, throw.\n * `operators` is the SQL table each rule is checked against here and compiled\n * by (the kernel's when not given), and the policy's table decides what a rule\n * reads from the input alone, so a server that starts can compile every rule\n * whatever table its bindings were given. Give it the bindings' SQL table, so\n * a rule and a query over one operator compile it alike.\n *\n * ```ts\n * const visible = GuardDrizzle.visible(Policy, [Todo, Project])\n * bind(Domain, { Todo: { table: todos, visible: visible.Todo, … }, … })\n * ```\n */\n visible: <User, const Es extends ReadonlyArray<AnyEntity>>(\n policy: Policy<User>,\n entities: Es,\n options: { readonly operators?: DrizzleOperators | undefined } = {},\n ): { readonly [K in Es[number]['name']]: Visible } => {\n const sqlOperators = options.operators ?? DrizzleOperators.kernel\n const byName = new Map(entities.map(entity => [entity.name, entity] as const))\n const inherits = new Map<string, ReadonlyArray<string>>()\n for (const entity of entities) {\n const targets: Array<string> = []\n for (const rule of flattenRules(readRules(entity))) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n const missing = Query.unsupported(guard.query, bodyOperations, sqlOperators)\n if (missing.length > 0) {\n fail(\n `${entity.name}'s ${guard.name} needs ${missing.join(', ')}, which SQL here does not run`,\n )\n }\n },\n All: () => {},\n Inherit: ({ relation }) => {\n const target = entity.relations[relation]!.target().name\n const guarded = byName.get(target)\n if (guarded === undefined) {\n fail(`${entity.name} inherits ${target}'s Read, but ${target} is not listed`)\n }\n if (readRules(guarded).length === 0) {\n fail(`${entity.name} inherits ${target}'s Read, but ${target} has no Read rule`)\n }\n targets.push(target)\n },\n })\n }\n inherits.set(entity.name, targets)\n }\n // A loop of inherited Reads would be a subquery that never ends.\n const closure = (name: string, path: ReadonlyArray<string>): ReadonlyArray<string> => {\n if (path.includes(name)) fail(`inherited Reads loop: ${[...path, name].join(' → ')}`)\n return [name, ...(inherits.get(name) ?? []).flatMap(next => closure(next, [...path, name]))]\n }\n const reaches = new Map(\n entities.map(entity => [entity.name, [...new Set(closure(entity.name, []))]]),\n )\n\n const compile = (\n name: string,\n binding: AnyEntityBinding,\n conditions: ReadonlyMap<string, Condition>,\n input: Readonly<Record<string, unknown>>,\n ): SQL | undefined => {\n const of = (condition: Condition): SQL | undefined =>\n Match.valueTags(condition, {\n Always: () => undefined,\n Never: () => nothing,\n // By the tables the rule was checked against: the SQL one given here, and\n // the policy's for what is decided from the input alone, as Guard judges.\n // A rule reads the rows it reaches as they are stored: it is the server's\n // decision, as a principal guard's body is, not a read by the principal.\n Row: ({ guard, context }) =>\n and(\n ...compileWhere(\n guard.query,\n {\n ...binding,\n operators: { memory: policy.operators, sql: sqlOperators },\n context,\n visibleOf: () => Option.none(),\n },\n input,\n `${name}.${guard.name}`,\n ),\n ),\n And: ({ conditions: parts }) => and(...parts.map(of)),\n // `Condition.or` folds away a part that admits every row, so each part here is SQL.\n Or: ({ conditions: parts }) => or(...parts.map(of)),\n Inherit: ({ relation }) => {\n const storage = binding.relations[relation]\n if (storage === undefined || storage.kind !== 'one') {\n return fail(\n `${name}.${relation} is inherited, so it must be stored as a foreign key here`,\n )\n }\n const target = storage.entity\n const where = compile(target.name, target, conditions, input) ?? sql`1 = 1`\n return sql`${storage.field} in (select ${idColumn(target)} from ${target.table} where ${where})`\n },\n })\n return of(conditions.get(name)!)\n }\n\n const visible =\n (name: string): Visible =>\n (principal, self) => {\n if (!policy.isPrincipal(principal)) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: the principal is not an Option of the guard set's`),\n )\n }\n return Effect.flatMap(\n Effect.forEach(reaches.get(name)!, each =>\n Effect.map(\n policy.readable(byName.get(each)!, principal),\n condition => [each, condition] as const,\n ),\n ),\n decided =>\n Effect.try({\n try: () => compile(name, self, new Map(decided), policy.inputOf(principal)),\n // What the compiler says names the rule's members and operators: for the report.\n catch: cause =>\n new RemoteServerError({\n message: `${name}'s Read rule could not be compiled to SQL`,\n cause,\n }),\n }),\n )\n }\n return Object.fromEntries(\n entities.map(entity => [entity.name, rowRules.add(visible(entity.name), policy, [entity])]),\n ) as {\n readonly [K in Es[number]['name']]: Visible\n }\n },\n}\n"],"mappings":";;;;;;;;;;;;;AAuBA,SAAS,KAAK,SAAwB;CACpC,MAAM,IAAI,MAAM,yCAAyC,SAAS;AACpE;;AAGA,MAAM,aAAa,WACjB,OAAO,MAAM,SAAS,MAAM,GAAG;CAC7B,cAAc,CAAC;CACf,SAAQ,eAAc,CAAC,GAAG,WAAW,QAAQ,GAAI,WAAW,IAAI,OAAO,EAAE,SAAS,CAAC,CAAE;AACvF,CAAC;AAEH,MAAM,UAAU,GAAG;AAEnB,MAAa,eAAe;;;;;;;;;;;;;;;;;AAiB1B,UACE,QACA,UACA,UAAiE,CAAC,MACd;CACpD,MAAM,eAAe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CAC/B,CACF,IACA,YACE,OAAO,IAAI;GACT,WAAW,QAAQ,MAAM,MAAM,IAAI,IAAI,OAAO,GAAG,OAAO,QAAQ,SAAS,CAAC;GAE1E,QAAO,UACL,IAAI,kBAAkB;IACpB,SAAS,GAAG,KAAK;IACjB;GACF,CAAC;EACL,CAAC,CACL;CACF;CACF,OAAO,OAAO,YACZ,SAAS,KAAI,WAAU,CAAC,OAAO,MAAM,SAAS,IAAI,QAAQ,OAAO,IAAI,GAAG,QAAQ,CAAC,MAAM,CAAC,CAAC,CAAC,CAC5F;AAGF,EACF"}
|
package/dist/index.d.mts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { A as May, C as PrincipalGuard, D as RowSpec, E as RowGuard, F as RowRule, M as MaySchema, N as Condition, O as ME, P as MemberRead, S as Policy, T as PrincipalSpec, _ as Builders, a as Deny, b as Guards, c as Interaction, d as Redact, f as RuleFor, g as Body, h as AnyGuard, i as Attachment, j as MayAnswer, k as MeEntity, l as InteractionKey, m as About, n as AnyRule, o as Explain, p as Surface, r as Attach, s as Inherit, t as All, u as On, v as Decision, w as PrincipalOf, x as Placeholders, y as GuardSet } from "./attach-
|
|
1
|
+
import { A as May, C as PrincipalGuard, D as RowSpec, E as RowGuard, F as RowRule, M as MaySchema, N as Condition, O as ME, P as MemberRead, S as Policy, T as PrincipalSpec, _ as Builders, a as Deny, b as Guards, c as Interaction, d as Redact, f as RuleFor, g as Body, h as AnyGuard, i as Attachment, j as MayAnswer, k as MeEntity, l as InteractionKey, m as About, n as AnyRule, o as Explain, p as Surface, r as Attach, s as Inherit, t as All, u as On, v as Decision, w as PrincipalOf, x as Placeholders, y as GuardSet } from "./attach-CER19mzk.mjs";
|
|
2
2
|
export { About, type All, AnyGuard, type AnyRule, type Attach, type Attachment, Body, Builders, Condition, Decision, type Deny, type Explain, GuardSet, Guards, type Inherit, Interaction, type InteractionKey, ME, May, type MayAnswer, MaySchema, type MeEntity, type MemberRead, type On, Placeholders, Policy, PrincipalGuard, PrincipalOf, PrincipalSpec, type Redact, RowGuard, type RowRule, RowSpec, type RuleFor, type Surface };
|
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { n as Interaction, r as attached, t as Attaching } from "./attach-
|
|
2
|
-
import { n as deciding, r as readsPrincipal, t as Condition } from "./condition-
|
|
3
|
-
import { n as MaySchema, t as May } from "./may-
|
|
4
|
-
import { n as me, t as ME } from "./me-
|
|
1
|
+
import { n as Interaction, r as attached, t as Attaching } from "./attach-DlrBpxOl.mjs";
|
|
2
|
+
import { n as deciding, r as readsPrincipal, t as Condition } from "./condition-VNIr9gDe.mjs";
|
|
3
|
+
import { n as MaySchema, t as May } from "./may-Bd6O91A-.mjs";
|
|
4
|
+
import { n as me, t as ME } from "./me-Bv7I0EcH.mjs";
|
|
5
5
|
import { n as providedFrom } from "./origin-igJoiz74.mjs";
|
|
6
6
|
import { Context, Effect, Match, Option, Schema } from "effect";
|
|
7
7
|
import { Expr, Operators, Query, evaluate } from "foldkit-entity";
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { r as attached } from "./attach-
|
|
2
|
-
import { n as deciding, t as Condition } from "./condition-
|
|
1
|
+
import { r as attached } from "./attach-DlrBpxOl.mjs";
|
|
2
|
+
import { n as deciding, t as Condition } from "./condition-VNIr9gDe.mjs";
|
|
3
3
|
import { Effect, Match, Option, Record, Schema } from "effect";
|
|
4
4
|
import { Derived, Entity } from "foldkit-entity";
|
|
5
5
|
// src/may.ts
|
|
@@ -15,6 +15,11 @@ import { Derived, Entity } from "foldkit-entity";
|
|
|
15
15
|
* application named), per member with its own `Update` rule, and per relation
|
|
16
16
|
* with a `Link` or `Unlink` rule; and, for a row interaction refused with an
|
|
17
17
|
* `explain`, its sentence.
|
|
18
|
+
*
|
|
19
|
+
* `row` says one of three things of an interaction: `true`, its rule let the
|
|
20
|
+
* reader; `false`, it refused; and nothing, the key left out, where the rule
|
|
21
|
+
* reads another row and one row cannot decide it. The write's statement
|
|
22
|
+
* decides that one. Read the three with `May.answer`.
|
|
18
23
|
*/
|
|
19
24
|
const MaySchema = Schema.Struct({
|
|
20
25
|
row: Schema.Record(Schema.String, Schema.Boolean),
|
|
@@ -25,11 +30,17 @@ const MaySchema = Schema.Struct({
|
|
|
25
30
|
Unlink: Schema.Boolean
|
|
26
31
|
}))
|
|
27
32
|
});
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
const
|
|
31
|
-
/**
|
|
32
|
-
const
|
|
33
|
+
/** What the answer says of a row interaction; none where it does not name it. */
|
|
34
|
+
const answer = (may, interaction) => Record.get(may.row, interaction);
|
|
35
|
+
const can = (may, interaction) => Option.getOrElse(answer(may, interaction), () => false);
|
|
36
|
+
/** Whether `answers` names `key`, and says no to it. */
|
|
37
|
+
const refuses = (answers, key) => Option.exists(Record.get(answers, key), (said) => !said);
|
|
38
|
+
/** Whether the relation has a rule of its own for the direction, and it said no. */
|
|
39
|
+
const refusesLink = (may, relation, interaction) => Option.exists(Record.get(may.relations, relation), (said) => !said[interaction]);
|
|
40
|
+
/** A yes to the row's `Update`, and no refusal from the member's own rule. */
|
|
41
|
+
const setting = (may, member) => can(may, "Update") && !refuses(may.members, member);
|
|
42
|
+
/** A yes to the row's `Update`, and no refusal from the relation's own rule for the direction. */
|
|
43
|
+
const linking = (may, relation, interaction) => can(may, "Update") && !refusesLink(may, relation, interaction);
|
|
33
44
|
const isMay = Schema.is(MaySchema);
|
|
34
45
|
const sameMay = Schema.toEquivalence(MaySchema);
|
|
35
46
|
/** The interactions a row answers `may` for: `Update`, `Delete`, and each one the set named. */
|
|
@@ -134,8 +145,6 @@ const predict = ({ entity, row, rows, context }) => {
|
|
|
134
145
|
const held = answerAssuming(true);
|
|
135
146
|
return sameMay(held, answerAssuming(false)) ? Option.some(held) : Option.none();
|
|
136
147
|
};
|
|
137
|
-
/** Whether `answer` names `key`, and says no to it. */
|
|
138
|
-
const refuses = (answer, key) => Object.hasOwn(answer, key) && answer[key] === false;
|
|
139
148
|
/**
|
|
140
149
|
* The write a held `may` refuses, as the server would: the row's `Update` or
|
|
141
150
|
* `Delete`, a written member's own `Update`, a relation's `Link` or `Unlink`,
|
|
@@ -146,7 +155,7 @@ const forbids = (value, surface) => {
|
|
|
146
155
|
if (!isMay(value)) return Option.none();
|
|
147
156
|
if (refuses(value.row, surface.kind)) return Option.some({ reason: Option.fromUndefinedOr(Object.hasOwn(value.reasons, surface.kind) ? value.reasons[surface.kind] : void 0) });
|
|
148
157
|
const member = surface.members.some((key) => refuses(value.members, key));
|
|
149
|
-
const relation = surface.relations.some(({ relation, interaction }) =>
|
|
158
|
+
const relation = surface.relations.some(({ relation, interaction }) => refusesLink(value, relation, interaction));
|
|
150
159
|
return member || relation ? Option.some({ reason: Option.none() }) : Option.none();
|
|
151
160
|
};
|
|
152
161
|
const May = {
|
|
@@ -161,26 +170,58 @@ const May = {
|
|
|
161
170
|
forbids
|
|
162
171
|
}) }),
|
|
163
172
|
/**
|
|
164
|
-
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
173
|
+
* What the answer says of the row's rule for `interaction`: `some(true)`,
|
|
174
|
+
* it let the reader when the row was read; `some(false)`, it refused; none,
|
|
175
|
+
* the answer does not say, since the rule reads another row and one row
|
|
176
|
+
* cannot decide it. The server decides that one when the write reaches it.
|
|
177
|
+
*
|
|
178
|
+
* ```ts
|
|
179
|
+
* Option.match(May.answer(todo.may, 'Update'), {
|
|
180
|
+
* onNone: () => 'the server will say',
|
|
181
|
+
* onSome: allowed => (allowed ? 'yes' : 'no'),
|
|
182
|
+
* })
|
|
183
|
+
* ```
|
|
184
|
+
*/
|
|
185
|
+
answer: (may, interaction) => answer(may, interaction),
|
|
186
|
+
/**
|
|
187
|
+
* Whether the answer says yes to `interaction`: `false` both where the rule
|
|
188
|
+
* refused and where the answer does not say. For what is drawn only on a
|
|
189
|
+
* certain yes; to hide or disable only what was refused, read `refused`.
|
|
167
190
|
*/
|
|
168
191
|
can: (may, interaction) => can(may, interaction),
|
|
169
192
|
/**
|
|
193
|
+
* Whether the answer says no to `interaction`: `false` both where the rule
|
|
194
|
+
* let the reader and where the answer does not say. What a hint hides,
|
|
195
|
+
* disables or refuses on: what was not said is left for the server.
|
|
196
|
+
*/
|
|
197
|
+
refused: (may, interaction) => refuses(may.row, interaction),
|
|
198
|
+
/**
|
|
170
199
|
* Why the row's rule for `interaction` refused, when it was refused with an
|
|
171
200
|
* `explain`: words for whoever asked. None where it was allowed (the server
|
|
172
201
|
* gives none then), or refused without one.
|
|
173
202
|
*/
|
|
174
203
|
reason: (may, interaction) => Record.get(may.reasons, interaction),
|
|
175
|
-
/**
|
|
204
|
+
/**
|
|
205
|
+
* Whether the answer says the principal may set `member` on this row: a
|
|
206
|
+
* yes to the row's `Update`, and no refusal from the member's own rule.
|
|
207
|
+
* `false` where the row's `Update` was not said: to lock only what was
|
|
208
|
+
* refused, read `locks`.
|
|
209
|
+
*/
|
|
176
210
|
canSet: (may, _entity, member) => setting(may, member),
|
|
177
|
-
/**
|
|
211
|
+
/**
|
|
212
|
+
* Whether the answer says the principal may point `relation` at a row, or
|
|
213
|
+
* away from one: a yes to the row's `Update`, and no refusal from the
|
|
214
|
+
* relation's own rule. `false` where the row's `Update` was not said.
|
|
215
|
+
*/
|
|
178
216
|
canLink: (may, _entity, relation, interaction) => linking(may, relation, interaction),
|
|
179
217
|
/**
|
|
180
218
|
* `foldkit-crud`'s `locks` for `entity`: an editor loads `may` beside the
|
|
181
|
-
* form's members and locks each the
|
|
182
|
-
*
|
|
183
|
-
*
|
|
219
|
+
* form's members and locks each the answer refuses: the row's `Update`, or
|
|
220
|
+
* the member's own rule, said no. A relation is locked where its `Unlink`
|
|
221
|
+
* or its `Link` said no. Nothing is locked on what was not said: a row's
|
|
222
|
+
* `Update` whose rule reads another row, or a `may` not answered at all (a
|
|
223
|
+
* Source without the filter). The write is checked anyway, and its refusal
|
|
224
|
+
* is the server's to give.
|
|
184
225
|
*
|
|
185
226
|
* ```ts
|
|
186
227
|
* Crud.editor('todo', { form, mutation: EditTodo, locks: May.locks(Todo) })
|
|
@@ -191,10 +232,11 @@ const May = {
|
|
|
191
232
|
locked: (row, member) => {
|
|
192
233
|
const may = row.may;
|
|
193
234
|
if (!isMay(may)) return false;
|
|
194
|
-
|
|
235
|
+
if (refuses(may.row, "Update")) return true;
|
|
236
|
+
return Object.hasOwn(entity.relations, member) ? refusesLink(may, member, "Unlink") || refusesLink(may, member, "Link") : refuses(may.members, member);
|
|
195
237
|
}
|
|
196
238
|
})
|
|
197
239
|
};
|
|
198
240
|
export { mayRules as a, mayConditions as i, MaySchema as n, answerOf as r, May as t };
|
|
199
241
|
|
|
200
|
-
//# sourceMappingURL=may-
|
|
242
|
+
//# sourceMappingURL=may-Bd6O91A-.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"may-Bd6O91A-.mjs","names":[],"sources":["../src/may.ts"],"sourcesContent":["/**\n * `may`: what a principal may do with a row, as a derived member the client\n * reads like any other. The server answers it for the row as it was read; a\n * client foresees it for a row it writes, from the same rules, where they\n * decide it whatever it does not know. Either way it is a hint for a\n * greyed-out button, never the check: the write is checked again when made.\n */\nimport { Effect, Match, Option, Record, Schema } from 'effect'\nimport { Derived, Entity, type AnyEntity, type Forbids, type Predict } from 'foldkit-entity'\nimport { attached, type InteractionKey } from './attach.js'\nimport { Condition, deciding, type MemberRead, type RowRule } from './condition.js'\n\n/**\n * The answer: per row interaction (`Update`, `Delete`, and each one the\n * application named), per member with its own `Update` rule, and per relation\n * with a `Link` or `Unlink` rule; and, for a row interaction refused with an\n * `explain`, its sentence.\n *\n * `row` says one of three things of an interaction: `true`, its rule let the\n * reader; `false`, it refused; and nothing, the key left out, where the rule\n * reads another row and one row cannot decide it. The write's statement\n * decides that one. Read the three with `May.answer`.\n */\nexport const MaySchema = Schema.Struct({\n row: Schema.Record(Schema.String, Schema.Boolean),\n reasons: Schema.Record(Schema.String, Schema.String),\n members: Schema.Record(Schema.String, Schema.Boolean),\n relations: Schema.Record(\n Schema.String,\n Schema.Struct({ Link: Schema.Boolean, Unlink: Schema.Boolean }),\n ),\n})\nexport type MayAnswer = typeof MaySchema.Type\n\ntype MemberKeys<E extends AnyEntity> = (keyof E['fields'] | keyof E['derived']) & string\n\n/** What the answer says of a row interaction; none where it does not name it. */\nconst answer = (may: MayAnswer, interaction: string): Option.Option<boolean> =>\n Record.get(may.row, interaction)\n\nconst can = (may: MayAnswer, interaction: string): boolean =>\n Option.getOrElse(answer(may, interaction), () => false)\n\n/** Whether `answers` names `key`, and says no to it. */\nconst refuses = (answers: Readonly<Record<string, boolean>>, key: string): boolean =>\n Option.exists(Record.get(answers, key), said => !said)\n\n/** Whether the relation has a rule of its own for the direction, and it said no. */\nconst refusesLink = (may: MayAnswer, relation: string, interaction: 'Link' | 'Unlink'): boolean =>\n Option.exists(Record.get(may.relations, relation), said => !said[interaction])\n\n/** A yes to the row's `Update`, and no refusal from the member's own rule. */\nconst setting = (may: MayAnswer, member: string): boolean =>\n can(may, 'Update') && !refuses(may.members, member)\n\n/** A yes to the row's `Update`, and no refusal from the relation's own rule for the direction. */\nconst linking = (may: MayAnswer, relation: string, interaction: 'Link' | 'Unlink'): boolean =>\n can(may, 'Update') && !refusesLink(may, relation, interaction)\n\nconst isMay = Schema.is(MaySchema)\nconst sameMay = Schema.toEquivalence(MaySchema)\n\n/** The interactions a row answers `may` for: `Update`, `Delete`, and each one the set named. */\nconst builtInRow = new Set(['Read', 'Create', 'Update', 'Delete'])\n\n/**\n * What `may` asks, for one principal: each row interaction's rule, each\n * member's own `Update`, each relation's `Link` and `Unlink`.\n */\nexport interface MayRules {\n readonly rows: ReadonlyArray<readonly [string, RowRule]>\n readonly members: ReadonlyArray<MemberRead>\n readonly relations: ReadonlyArray<{\n readonly relation: string\n readonly link: Option.Option<RowRule>\n readonly unlink: Option.Option<RowRule>\n }>\n}\n\n/** How one side decides a rule for its principal: a Policy's bodies, or a client's assumption. */\nexport interface MayAsk<R> {\n readonly row: (interaction: string) => Effect.Effect<RowRule, never, R>\n readonly members: (\n members: ReadonlyArray<string>,\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n readonly relation: (\n relation: string,\n interaction: 'Link' | 'Unlink',\n ) => Effect.Effect<Option.Option<RowRule>, never, R>\n}\n\n/** The rules `may` answers for `entity`, each decided by `ask`. */\nexport const mayRules = <R>(\n entity: AnyEntity,\n ask: MayAsk<R>,\n): Effect.Effect<MayRules, never, R> => {\n const attachment = attached(entity)\n const named = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ row }) => Object.keys(row).filter(interaction => !builtInRow.has(interaction)),\n })\n const ruledMembers = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ members }) => Object.keys(members),\n })\n const ruledRelations = Option.match(attachment, {\n onNone: () => [],\n onSome: ({ relations }) => Object.keys(relations),\n })\n return Effect.map(\n Effect.all([\n Effect.forEach(['Update', 'Delete', ...named], interaction =>\n Effect.map(ask.row(interaction), rule => [interaction, rule] as const),\n ),\n ask.members(ruledMembers),\n Effect.forEach(ruledRelations, relation =>\n Effect.map(\n Effect.all([ask.relation(relation, 'Link'), ask.relation(relation, 'Unlink')]),\n ([link, unlink]) => ({ relation, link, unlink }),\n ),\n ),\n ]),\n ([rows, members, relations]) => ({ rows, members, relations }),\n )\n}\n\n/** Every condition the rules hold a row to. */\nexport const mayConditions = (rules: MayRules): ReadonlyArray<Condition> => [\n ...rules.rows.map(([, { condition }]) => condition),\n ...rules.members.map(({ condition }) => condition),\n ...rules.relations.flatMap(({ link, unlink }) =>\n [...Option.toArray(link), ...Option.toArray(unlink)].map(({ condition }) => condition),\n ),\n]\n\n/**\n * The answer over one row, each condition decided by `decide`. A row\n * interaction it cannot decide over one row (a rule reading another row,\n * which the write's statement judges) is left out, and so refuses nothing.\n */\nexport const answerOf = (\n rules: MayRules,\n decide: (condition: Condition) => Option.Option<boolean>,\n): MayAnswer => {\n // Member and relation rules never read another row (`Guards.attach` refuses one).\n const holds = (condition: Condition) => Option.getOrElse(decide(condition), () => false)\n // A relation without a rule for one direction leaves it to the row's Update.\n const allows = (rule: Option.Option<RowRule>) =>\n Option.match(rule, { onNone: () => true, onSome: ({ condition }) => holds(condition) })\n const decided = rules.rows.flatMap(([interaction, rule]) =>\n Option.match(decide(rule.condition), {\n onNone: () => [],\n onSome: answer => [{ interaction, rule, answer }],\n }),\n )\n return {\n row: Object.fromEntries(decided.map(({ interaction, answer }) => [interaction, answer])),\n // Only an `explain`'s sentence is for whoever asked.\n reasons: Object.fromEntries(\n decided.flatMap(({ interaction, rule: { deny }, answer }) =>\n answer\n ? []\n : Match.valueTags(deny, {\n Explain: ({ reason }) => [[interaction, reason] as const],\n Forbidden: () => [],\n NotFound: () => [],\n Omit: () => [],\n Redact: () => [],\n }),\n ),\n ),\n members: Object.fromEntries(\n rules.members.map(({ member, condition }) => [member, holds(condition)]),\n ),\n relations: Object.fromEntries(\n rules.relations.map(({ relation, link, unlink }) => [\n relation,\n { Link: allows(link), Unlink: allows(unlink) },\n ]),\n ),\n }\n}\n\n/**\n * `may` foreseen for a row the client writes. A principal guard's body is\n * the server's, and the principal's fields are not the client's to know, so\n * each is unknown, as is a rule over a row or field the store lacks. Every\n * rule is a conjunction and disjunction of its parts, so it is decided when\n * it comes out the same with every unknown part taken to hold and taken not\n * to: the answer is foreseen only when the whole of it is.\n */\nconst predict: Predict = ({ entity, row, rows, context }) => {\n // Never a visitor here: a client without a viewer may be one that was not told it.\n const answerAssuming = (assumed: boolean): MayAnswer => {\n const decide = (interaction: string) =>\n deciding(() => Effect.succeed(assumed), false, interaction, context)\n const rules = Effect.runSync(\n mayRules(entity, {\n row: interaction => decide(interaction).row(entity),\n members: members => decide('Update').members(entity, members),\n relation: (relation, interaction) => decide(interaction).relation(entity, relation),\n }),\n )\n return answerOf(rules, condition => Option.some(Condition.judge(condition, row, rows, assumed)))\n }\n const held = answerAssuming(true)\n return sameMay(held, answerAssuming(false)) ? Option.some(held) : Option.none()\n}\n\n/**\n * The write a held `may` refuses, as the server would: the row's `Update` or\n * `Delete`, a written member's own `Update`, a relation's `Link` or `Unlink`,\n * each judged over the row as read, where the answer says `false`. What it\n * does not name refuses nothing, and neither does a value that is no answer.\n */\nconst forbids: Forbids = (value, surface) => {\n if (!isMay(value)) return Option.none()\n // Only a row interaction's refusal carries the `explain` the server would give.\n if (refuses(value.row, surface.kind)) {\n return Option.some({\n reason: Option.fromUndefinedOr(\n Object.hasOwn(value.reasons, surface.kind) ? value.reasons[surface.kind] : undefined,\n ),\n })\n }\n const member = surface.members.some(key => refuses(value.members, key))\n const relation = surface.relations.some(({ relation, interaction }) =>\n refusesLink(value, relation, interaction),\n )\n return member || relation ? Option.some({ reason: Option.none() }) : Option.none()\n}\n\nexport const May = {\n /**\n * Adds the `may` member to an Entity, after its guards are attached:\n * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`. Select it as any\n * member (`may: true`); `GuardServer.filter` answers it. A client holding it\n * refuses, where it is made, a write it says no to (`Forbidden`).\n */\n member: Entity.derived({ may: Derived.make(MaySchema, { predict, forbids }) }),\n\n /**\n * What the answer says of the row's rule for `interaction`: `some(true)`,\n * it let the reader when the row was read; `some(false)`, it refused; none,\n * the answer does not say, since the rule reads another row and one row\n * cannot decide it. The server decides that one when the write reaches it.\n *\n * ```ts\n * Option.match(May.answer(todo.may, 'Update'), {\n * onNone: () => 'the server will say',\n * onSome: allowed => (allowed ? 'yes' : 'no'),\n * })\n * ```\n */\n answer: (\n may: MayAnswer,\n interaction: 'Update' | 'Delete' | InteractionKey,\n ): Option.Option<boolean> => answer(may, interaction),\n\n /**\n * Whether the answer says yes to `interaction`: `false` both where the rule\n * refused and where the answer does not say. For what is drawn only on a\n * certain yes; to hide or disable only what was refused, read `refused`.\n */\n can: (may: MayAnswer, interaction: 'Update' | 'Delete' | InteractionKey): boolean =>\n can(may, interaction),\n\n /**\n * Whether the answer says no to `interaction`: `false` both where the rule\n * let the reader and where the answer does not say. What a hint hides,\n * disables or refuses on: what was not said is left for the server.\n */\n refused: (may: MayAnswer, interaction: 'Update' | 'Delete' | InteractionKey): boolean =>\n refuses(may.row, interaction),\n\n /**\n * Why the row's rule for `interaction` refused, when it was refused with an\n * `explain`: words for whoever asked. None where it was allowed (the server\n * gives none then), or refused without one.\n */\n reason: (\n may: MayAnswer,\n interaction: 'Update' | 'Delete' | InteractionKey,\n ): Option.Option<string> => Record.get(may.reasons, interaction),\n\n /**\n * Whether the answer says the principal may set `member` on this row: a\n * yes to the row's `Update`, and no refusal from the member's own rule.\n * `false` where the row's `Update` was not said: to lock only what was\n * refused, read `locks`.\n */\n canSet: <E extends AnyEntity>(may: MayAnswer, _entity: E, member: MemberKeys<E>): boolean =>\n setting(may, member),\n\n /**\n * Whether the answer says the principal may point `relation` at a row, or\n * away from one: a yes to the row's `Update`, and no refusal from the\n * relation's own rule. `false` where the row's `Update` was not said.\n */\n canLink: <E extends AnyEntity>(\n may: MayAnswer,\n _entity: E,\n relation: keyof E['relations'] & string,\n interaction: 'Link' | 'Unlink',\n ): boolean => linking(may, relation, interaction),\n\n /**\n * `foldkit-crud`'s `locks` for `entity`: an editor loads `may` beside the\n * form's members and locks each the answer refuses: the row's `Update`, or\n * the member's own rule, said no. A relation is locked where its `Unlink`\n * or its `Link` said no. Nothing is locked on what was not said: a row's\n * `Update` whose rule reads another row, or a `may` not answered at all (a\n * Source without the filter). The write is checked anyway, and its refusal\n * is the server's to give.\n *\n * ```ts\n * Crud.editor('todo', { form, mutation: EditTodo, locks: May.locks(Todo) })\n * ```\n */\n locks: (entity: AnyEntity) => ({\n select: { may: true } as const,\n locked: (row: Readonly<Record<string, unknown>>, member: string): boolean => {\n const may = row.may\n if (!isMay(may)) return false\n if (refuses(may.row, 'Update')) return true\n return Object.hasOwn(entity.relations, member)\n ? refusesLink(may, member, 'Unlink') || refusesLink(may, member, 'Link')\n : refuses(may.members, member)\n },\n }),\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAuBA,MAAa,YAAY,OAAO,OA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,MAAM,IAAI;GAChB,IAAI,CAAC,MAAM,GAAG,GAAG,OAAO;GACxB,IAAI,QAAQ,IAAI,KAAK,QAAQ,GAAG,OAAO;GACvC,OAAO,OAAO,OAAO,OAAO,WAAW,MAAM,IACzC,YAAY,KAAK,QAAQ,QAAQ,KAAK,YAAY,KAAK,QAAQ,MAAM,IACrE,QAAQ,IAAI,SAAS,MAAM;EACjC;CACF;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { t as Attaching } from "./attach-
|
|
2
|
-
import { t as May } from "./may-
|
|
1
|
+
import { t as Attaching } from "./attach-DlrBpxOl.mjs";
|
|
2
|
+
import { t as May } from "./may-Bd6O91A-.mjs";
|
|
3
3
|
import { Schema } from "effect";
|
|
4
4
|
import { Entity } from "foldkit-entity";
|
|
5
5
|
// src/me.ts
|
|
@@ -36,4 +36,4 @@ const me = (G, options = {}) => MeFields.pipe(Attaching.attach(G, {
|
|
|
36
36
|
}), May.member);
|
|
37
37
|
export { me as n, ME as t };
|
|
38
38
|
|
|
39
|
-
//# sourceMappingURL=me-
|
|
39
|
+
//# sourceMappingURL=me-Bv7I0EcH.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"me-
|
|
1
|
+
{"version":3,"file":"me-Bv7I0EcH.mjs","names":[],"sources":["../src/me.ts"],"sourcesContent":["/**\n * The visitor as an Entity: one row, `me`, answered for whoever asks. What a\n * client knows about itself (signed in, as whom, what it may open) is read\n * through Remote like any row, `may` included, so no rule runs on the client.\n */\nimport { Schema } from 'effect'\nimport { Entity } from 'foldkit-entity'\nimport { Attaching, type Attach } from './attach.js'\nimport { May } from './may.js'\n\n/** The one row's id. */\nexport const ME = 'me'\n\nconst MeFields = Entity.define(\n 'Me',\n Schema.Struct({\n id: Schema.String,\n /** Whether the server answered as someone. */\n signedIn: Schema.Boolean,\n /** Who the server answered as: `declare`'s `key` of the principal. */\n key: Schema.OptionFromNullOr(Schema.String),\n }),\n)\n\n/** `Me`'s Entity, with `may`. */\nexport type MeEntity = ReturnType<typeof May.member<typeof MeFields>>\n\n/**\n * `Me` for guard set `G`: everyone reads their own row, no one writes it, and\n * each interaction is answered in `may` as `G`'s bodies decide it for the\n * asker (`May.can(me.may, OpenAdmin.key)`).\n *\n * ```ts\n * const OpenAdmin = Interaction.make('OpenAdmin')\n * export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })\n * ```\n */\nexport const me = <Name extends string, User>(\n G: {\n readonly name: Name\n readonly schema: Schema.Codec<User, unknown>\n readonly unguarded: 'allow' | 'deny'\n },\n options: {\n readonly interactions?: Attach<NoInfer<User>, NoInfer<Name>, typeof MeFields>['interactions']\n } = {},\n): MeEntity =>\n MeFields.pipe(\n Attaching.attach(G, {\n row: { Read: [Attaching.anyone], Write: [] },\n ...(options.interactions === undefined ? {} : { interactions: options.interactions }),\n }),\n May.member,\n )\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,KAAK;AAElB,MAAM,WAAW,OAAO,OACtB,MACA,OAAO,OAAO;CACZ,IAAI,OAAO;;CAEX,UAAU,OAAO;;CAEjB,KAAK,OAAO,iBAAiB,OAAO,MAAM;AAC5C,CAAC,CACH;;;;;;;;;;;AAeA,MAAa,MACX,GAKA,UAEI,CAAC,MAEL,SAAS,KACP,UAAU,OAAO,GAAG;CAClB,KAAK;EAAE,MAAM,CAAC,UAAU,MAAM;EAAG,OAAO,CAAC;CAAE;CAC3C,GAAI,QAAQ,iBAAiB,KAAA,IAAY,CAAC,IAAI,EAAE,cAAc,QAAQ,aAAa;AACrF,CAAC,GACD,IAAI,MACN"}
|
package/dist/media.d.mts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { C as PrincipalGuard, S as Policy } from "./attach-
|
|
1
|
+
import { C as PrincipalGuard, S as Policy } from "./attach-CER19mzk.mjs";
|
|
2
2
|
import { Effect, Layer, Option } from "effect";
|
|
3
3
|
import { UploadPolicy } from "foldkit-media/server";
|
|
4
4
|
export interface UploadPolicyConfig<User, E, R> {
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { r as attached } from "./attach-
|
|
1
|
+
import { r as attached } from "./attach-DlrBpxOl.mjs";
|
|
2
2
|
import { t as originOf } from "./origin-igJoiz74.mjs";
|
|
3
3
|
import { Option } from "effect";
|
|
4
4
|
// src/placed.ts
|
|
@@ -36,4 +36,4 @@ const memberRules = record(/* @__PURE__ */ new WeakMap());
|
|
|
36
36
|
const writeRules = record(/* @__PURE__ */ new WeakMap());
|
|
37
37
|
export { rowRules as n, writeRules as r, memberRules as t };
|
|
38
38
|
|
|
39
|
-
//# sourceMappingURL=placed-
|
|
39
|
+
//# sourceMappingURL=placed-Dt05PaWi.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"placed-
|
|
1
|
+
{"version":3,"file":"placed-Dt05PaWi.mjs","names":[],"sources":["../src/placed.ts"],"sourcesContent":["/**\n * What each guard seam built, and for which Policy and Entities, so\n * `GuardServer.validate` can tell a Source that applies a guard set's rules\n * from one that only looks as if it does.\n */\nimport { Option } from 'effect'\nimport type { AnyEntity } from 'foldkit-entity'\nimport { attached, type Attachment } from './attach.js'\nimport type { Policy } from './index.js'\nimport { originOf } from './origin.js'\n\ninterface Placed {\n readonly policy: Policy<any, any>\n /** Each Entity's attachment as it was built from: none for one built before `attach`. */\n readonly entities: ReadonlyMap<string, Attachment | undefined>\n}\n\n/** An Entity's guards, by identity: the same attachment is the same rules. */\nconst guardsOf = (entity: AnyEntity) => Option.getOrUndefined(attached(entity))\n\nconst record = (registry: WeakMap<object, Placed>) => ({\n add: <F extends object>(built: F, policy: Policy<any, any>, entities: Iterable<AnyEntity>): F => {\n registry.set(built, {\n policy,\n entities: new Map([...entities].map(entity => [entity.name, guardsOf(entity)])),\n })\n return built\n },\n /**\n * Whether `built` applies `entity`'s guards from `policy`: built for it,\n * not for another Entity of its name, nor for it before its guards were\n * attached, which decides nothing.\n */\n has: (built: unknown, policy: Policy<any, any>, entity: AnyEntity): boolean => {\n if (typeof built !== 'function' && (typeof built !== 'object' || built === null)) return false\n const placed = registry.get(built)\n return (\n placed !== undefined &&\n originOf(placed.policy) === originOf(policy) &&\n placed.entities.has(entity.name) &&\n placed.entities.get(entity.name) === guardsOf(entity)\n )\n },\n})\n\n/** Row rules: `GuardDrizzle.visible`'s, and `GuardServer.memory`'s `readable`. */\nexport const rowRules = record(new WeakMap())\n\n/** Member and relation rules: `GuardServer.filter`'s. */\nexport const memberRules = record(new WeakMap())\n\n/** Write rules: `GuardServer.writer`'s. */\nexport const writeRules = record(new WeakMap())\n"],"mappings":";;;;;;;;;;AAkBA,MAAM,YAAY,WAAsB,OAAO,eAAe,SAAS,MAAM,CAAC;AAE9E,MAAM,UAAU,cAAuC;CACrD,MAAwB,OAAU,QAA0B,aAAqC;EAC/F,SAAS,IAAI,OAAO;GAClB;GACA,UAAU,IAAI,IAAI,CAAC,GAAG,QAAQ,CAAC,CAAC,KAAI,WAAU,CAAC,OAAO,MAAM,SAAS,MAAM,CAAC,CAAC,CAAC;EAChF,CAAC;EACD,OAAO;CACT;;;;;;CAMA,MAAM,OAAgB,QAA0B,WAA+B;EAC7E,IAAI,OAAO,UAAU,eAAe,OAAO,UAAU,YAAY,UAAU,OAAO,OAAO;EACzF,MAAM,SAAS,SAAS,IAAI,KAAK;EACjC,OACE,WAAW,KAAA,KACX,SAAS,OAAO,MAAM,MAAM,SAAS,MAAM,KAC3C,OAAO,SAAS,IAAI,OAAO,IAAI,KAC/B,OAAO,SAAS,IAAI,OAAO,IAAI,MAAM,SAAS,MAAM;CAExD;AACF;;AAGA,MAAa,WAAW,uBAAO,IAAI,QAAQ,CAAC;;AAG5C,MAAa,cAAc,uBAAO,IAAI,QAAQ,CAAC;;AAG/C,MAAa,aAAa,uBAAO,IAAI,QAAQ,CAAC"}
|