foldkit-guard 0.3.0 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,8 +1,7 @@
1
1
  # foldkit-guard
2
2
 
3
3
  Who may do what, declared once on a Foldkit Plus domain, and enforced on every
4
- path a row is read or written by. [`guard-DESIGN.md`](../../docs/design/guard-DESIGN.md)
5
- explains the design and why.
4
+ path a row is read or written by.
6
5
 
7
6
  ## What it is
8
7
 
@@ -62,8 +61,8 @@ pnpm add effect foldkit-entity foldkit-guard
62
61
  `foldkit-guard` is the shared declaration. Its subpaths bring their packages
63
62
  as optional peers: `foldkit-guard/server` needs `foldkit-remote` and
64
63
  `foldkit-remote-server`, `/drizzle` also `foldkit-remote-drizzle` and
65
- `drizzle-orm`, `/sync` `foldkit-sync` and `foldkit-remote-server`, and
66
- `/agent` `foldkit-remote`.
64
+ `drizzle-orm`, `/sync` `foldkit-sync` and `foldkit-remote-server`,
65
+ `/agent` `foldkit-remote`, and `/media` `foldkit-media`.
67
66
 
68
67
  ## Sixty seconds
69
68
 
@@ -696,6 +695,48 @@ has a `RequestedArchive` with the todo's `id`.
696
695
  - It is the agent's gate, not the check: the Message's mutation is checked on
697
696
  the server, under the same principal.
698
697
 
698
+ ## Uploads
699
+
700
+ `foldkit-media`'s upload routes ask one question of an `UploadPolicy`
701
+ before reading a byte: may this request upload (`Upload`), or have an image
702
+ named by URL described (`DescribeUrl`)? `foldkit-guard/media` answers it with
703
+ principal guards, for who your resolver says is asking:
704
+
705
+ ```ts
706
+ import { Layer } from 'effect'
707
+ import { uploadLayer, uploadsKeyValueStore } from 'foldkit-media/server'
708
+ import { GuardMedia } from 'foldkit-guard/media'
709
+
710
+ const uploads = uploadLayer().pipe(
711
+ Layer.provide(
712
+ Layer.mergeAll(
713
+ uploadsKeyValueStore(),
714
+ inspector,
715
+ GuardMedia.uploadPolicy(Policy, { resolve, Upload: [G.isAdmin], DescribeUrl: [G.isAdmin] }),
716
+ ),
717
+ ),
718
+ )
719
+ ```
720
+
721
+ `resolve` is the resolver your Remote server is given:
722
+ `(request: Request) => Effect<Option<User>, E, R>`, which
723
+ `AuthServer.resolver` from `foldkit-auth/server` is. `inspector` is
724
+ `foldkit-media`'s `Inspector` for where you run (`inspectorSharp()`,
725
+ `inspectorImages(env.IMAGES)`).
726
+
727
+ - Only principal guards: no row exists before an upload, so a row guard is a
728
+ type error. A route admits when any one of its guards allows, and a route
729
+ given no guards admits nobody.
730
+ - The resolver gets the request's URL, method and headers and never its
731
+ body, so the route still reads no byte before the policy answers.
732
+ - A resolver that fails (an untrusted origin, a session that ended) is a
733
+ `401`; a principal the guards refuse is a `403`. Either says only its kind:
734
+ an `explain` sentence stays on the server.
735
+ - `Policy` must need no service; give it what its bodies need with
736
+ `Policy.provide`, as the other seams take it.
737
+ - Beside a deployment's secret for scripts:
738
+ `uploadPolicyAny(uploadPolicyBearer(secret), GuardMedia.uploadPolicy(…))`.
739
+
699
740
  ## Limits
700
741
 
701
742
  - **No rule runs on the client.** `may` is the server's answer for the row as
@@ -1 +1 @@
1
- {"version":3,"file":"attach-BVG6LsFf.d.mts","names":["MemberKeys","_$__attach_js0.Attach","_$__attach_js0.AnyRule","_$__attach_js0.Inherit","_$__attach_js0.All","_$__attach_js0.Redact","_$__attach_js0.Explain","_$__attach_js0.On"],"sources":["../src/condition.ts","../src/may.ts","../src/me.ts","../src/index.ts","../src/attach.ts"],"mappings":";;;KAWY;WACG;;WACA;;WACA;WAAsB,OAAO,cAAc;;;;WAE3C;WAA0B;;WAC1B;WAAsB,YAAY,cAAc;;WAChD;WAAqB,YAAY,cAAc;;;cAMxD,MAAG,YAAgB,cAAc,eAAa;;cAY9C,KAAE,YAAgB,cAAc,eAAa;cAWtC;;aAnCQ;;;aACA;;;;;;;;;EA8CN,QAAA,WAAA,WAAS,QACZ,SAAS,0BAAwB,OAClC,SAAS,0BAAwB,UAC9B;;;;;;;EAoBW,YAAA,WAAA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AU,gBACzB,WAAW,iBAAiB,eAAe;WAAsB;IAAuB,mBACnF;KAGH,WAAW,UAAU,oBAAoB,oBAAoB;KAE7D,OAAO,UAAU,WAAW,gBAAgB,gBAAgB,aAAa;;KAGlE,OAAO,MAAM,oBAAoB,UAAU;WAC5C;aACE,OAAO,cAAc,QAAQ,MAAM,KAAK,aAAa,QAAQ,aAAa;aAC1E,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;;aAEtC,QAAQ,UAAU,QAAQ,MAAM,KAAK;;;;;;;;WAQvC;cACG,GAAG,iBAAiB,UAAU,QAAQ,MAAM,KAAK;;;WAGpD,sBACG,KAAK,WAAW;aACf,OAAO,KAAK,QAAQ,MAAM,KAAK,YAAY,OAAO,OAAO,GAAG;;aAE5D,SAAS,UAAU,QAAQ,MAAM,KAAK;aACtC,SAAS,UAAU,QAAQ,MAAM,KAAK;;WAG1C,wBACG,WAAW;aACV,OAAO,cAAc,QAAQ,MAAM,KAAK;aACxC,OAAO,UAAU,QAAQ,MAAM,KAAK;aACpC,SAAS,UAAU,QAAQ,MAAM,KAAK;;;WAI1C,SAAS,cAAc,QAAQ,MAAM,KAAK;;;UAIpC;WACN,OAAO,cAAc;WACrB,MAAM,OAAO,OAAO;;KAG1B,WAAW,SAAS,eAAe;;UAGvB;WACN;WACA;WACA,KAAK;WACL,SAAS,SAAS,eAAe;WACjC,WAAW,SAAS,eAAe;WACnC,QAAQ,cAAc;;cA4PpB,WAAQ,QAAY,cAAY,OAAO,OAAO"}
1
+ {"version":3,"file":"attach-BVG6LsFf.d.mts","names":["MemberKeys","_$__attach_js0.Attach","_$__attach_js0.AnyRule","_$__attach_js0.Inherit","_$__attach_js0.All","_$__attach_js0.Redact","_$__attach_js0.Explain","_$__attach_js0.On"],"sources":["../src/condition.ts","../src/may.ts","../src/me.ts","../src/index.ts","../src/attach.ts"],"mappings":";;;KAWY;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S,eAAe;WACnC,QAAQ,cAAc;;cA4PpB,WAAQ,QAAY,cAAY,OAAO,OAAO"}
@@ -1 +1 @@
1
- {"version":3,"file":"attach-BZyVvs7H.mjs","names":[],"sources":["../src/attach.ts"],"sourcesContent":["/**\n * Attaching a guard set's guards to an Entity, per surface and interaction,\n * as metadata only `foldkit-guard` reads. See `guard-DESIGN.md` §3.2.\n */\nimport { Match, Option, type Schema } from 'effect'\nimport { Entity, Query, ReadFilter, type AnyEntity } from 'foldkit-entity'\nimport { Metadata } from 'foldkit-metadata'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\ndeclare const InteractionBrand: unique symbol\n\n/** An interaction the application names, used as a computed key: `[Archive.key]`. */\nexport type InteractionKey<Name extends string = string> = Name & {\n readonly [InteractionBrand]: Name\n}\n\nexport interface Interaction<Name extends string> {\n readonly name: Name\n readonly key: InteractionKey<Name>\n}\n\n/** The interactions every row has, and the ones a relation member has. */\nconst builtIn = ['Read', 'Create', 'Update', 'Delete', 'Write', 'Link', 'Unlink'] as const\n\nexport const Interaction = {\n /** An interaction beyond Read, Create, Update and Delete, such as `Archive`. */\n make: <const Name extends string>(name: Name): Interaction<Name> => {\n if ((builtIn as ReadonlyArray<string>).includes(name)) {\n throw new Error(`[foldkit-guard] Interaction.make: \"${name}\" is an interaction already`)\n }\n return Object.freeze({ name, key: name as InteractionKey<Name> })\n },\n}\n\n/** Every guard of `Rules` must allow, as one guard: `Guards.all(signedIn, isOwner)`. */\nexport interface All<Rules> {\n readonly _tag: 'All'\n readonly rules: ReadonlyArray<Rules>\n}\n\n/** This row's Read is the Read of the row its `one` relation points at. */\nexport interface Inherit<Relation extends string> {\n readonly _tag: 'Inherit'\n readonly relation: Relation\n}\n\n/** What a member hidden by its Read guards reads as instead of its value. */\nexport interface Redact<A> {\n readonly _tag: 'Redact'\n readonly value: A\n}\n\n/** A refused write's sentence, for the application's own users. */\nexport interface Explain {\n readonly _tag: 'Explain'\n readonly reason: string\n}\n\n/**\n * What a refusal looks like. The defaults need no constructor: a row Read\n * answers `NotFound`, a member or relation Read `Omit`, a write `Forbidden`.\n */\nexport type Deny =\n | { readonly _tag: 'NotFound' }\n | { readonly _tag: 'Omit' }\n | Redact<unknown>\n | { readonly _tag: 'Forbidden' }\n | Explain\n\n/** A surface's guards with a refusal other than its default. */\nexport interface On<Rules, D extends Deny> {\n readonly _tag: 'On'\n readonly rules: ReadonlyArray<Rules>\n readonly deny: D\n}\n\n/** Anything a surface's list may hold, of any guard set. */\nexport type AnyRule =\n PrincipalGuard<any, string> | RowGuard<any, AnyEntity, string> | All<any> | Inherit<string>\n\n/**\n * What a surface of the Entity named `Name` accepts from the guard set `Set`:\n * its principal guards, its row guards over that Entity, and conjunctions of\n * both. A row guard over another Entity, or a guard of another set, is refused.\n */\nexport type RuleFor<User, Set extends string, Name extends string> =\n | PrincipalGuard<User, Set>\n | RowGuard<User, Entity<Name, any, any, any>, Set>\n | All<RuleFor<User, Set, Name>>\n\ntype Slot<Rule, D extends Deny> = ReadonlyArray<Rule> | On<Rule, D>\n\ntype WriteSlot<Rule> = Slot<Rule, Explain>\n\ntype OneRelations<E extends AnyEntity> = {\n [K in keyof E['relations']]: E['relations'][K] extends { readonly cardinality: 'one' } ? K : never\n}[keyof E['relations']] &\n string\n\ntype MemberKeys<E extends AnyEntity> = (keyof E['fields'] | keyof E['derived']) & string\n\ntype TypeOf<E extends AnyEntity, K extends keyof E['members']> = E['members'][K]['schema']['Type']\n\n/** What `Guards.attach` takes for the Entity `E`, every key checked against it. */\nexport type Attach<User, Set extends string, E extends AnyEntity> = {\n readonly row?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']> | Inherit<OneRelations<E>>>\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Delete?: WriteSlot<RuleFor<User, Set, E['name']>>\n /** The same guards on Create, Update and Delete. */\n readonly Write?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /**\n * The row's interactions the application named, by key:\n * `{ [Archive.key]: [G.isAdmin] }`. Apart from `row`, whose `Read` may\n * inherit: a literal with a computed key is typed as an index signature,\n * which `Read`'s rules would have to fit too.\n */\n readonly interactions?: {\n readonly [K: InteractionKey]: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /** Narrow a field or derived member: a member is reachable only if its row is. */\n readonly members?: {\n readonly [K in MemberKeys<E>]?: {\n readonly Read?: Slot<RuleFor<User, Set, E['name']>, Redact<TypeOf<E, K>>>\n /** When absent, `Update`'s guards govern setting the member on creation too. */\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n readonly relations?: {\n readonly [K in keyof E['relations']]?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n readonly Link?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Unlink?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n /** ANDed with every surface's guards, and never out-voted by them. */\n readonly always?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n}\n\n/** One surface's guards as attached: a disjunction, and a refusal if one was chosen. */\nexport interface Surface {\n readonly rules: ReadonlyArray<AnyRule>\n readonly deny: Option.Option<Deny>\n}\n\ntype Surfaces = Readonly<Record<string, Surface>>\n\n/** An Entity's guards, every attachment merged. */\nexport interface Attachment {\n readonly set: string\n readonly unguarded: 'allow' | 'deny'\n readonly row: Surfaces\n readonly members: Readonly<Record<string, Surfaces>>\n readonly relations: Readonly<Record<string, Surfaces>>\n readonly always: ReadonlyArray<AnyRule>\n}\n\n/** Which surface a rule is asked about. */\ntype Target =\n | { readonly _tag: 'Row'; readonly interaction: string }\n | { readonly _tag: 'Member'; readonly member: string; readonly interaction: string }\n | { readonly _tag: 'Relation'; readonly relation: string; readonly interaction: string }\n\nconst record = <A>(): Record<string, A> => Object.create(null)\n\nconst appendSurface = (into: Record<string, Surface>, interaction: string, added: Surface) => {\n const before = into[interaction]\n into[interaction] =\n before === undefined\n ? added\n : {\n rules: [...before.rules, ...added.rules],\n deny: Option.orElse(added.deny, () => before.deny),\n }\n}\n\nconst appendSurfaces = (into: Record<string, Surface>, added: Surfaces) => {\n for (const [interaction, surface] of Object.entries(added)) {\n appendSurface(into, interaction, surface)\n }\n}\n\nconst freezeSurfaces = (surfaces: Record<string, Surfaces>) => {\n for (const key of Object.keys(surfaces)) Object.freeze(surfaces[key])\n return Object.freeze(surfaces)\n}\n\n/** Later attachments append to each surface's disjunction and replace its refusal. */\nconst mergeAttachments = (attachments: ReadonlyArray<Attachment>): Attachment => {\n const row = record<Surface>()\n const members = record<Record<string, Surface>>()\n const relations = record<Record<string, Surface>>()\n const always: Array<AnyRule> = []\n for (const attachment of attachments) {\n appendSurfaces(row, attachment.row)\n for (const [key, surfaces] of Object.entries(attachment.members)) {\n appendSurfaces((members[key] ??= record()), surfaces)\n }\n for (const [key, surfaces] of Object.entries(attachment.relations)) {\n appendSurfaces((relations[key] ??= record()), surfaces)\n }\n always.push(...attachment.always)\n }\n const { set, unguarded } = attachments[0]!\n return Object.freeze({\n set,\n unguarded,\n row: Object.freeze(row),\n members: freezeSurfaces(members),\n relations: freezeSurfaces(relations),\n always: Object.freeze(always),\n })\n}\n\nconst showRule = (rule: AnyRule): string =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => name,\n RowGuard: ({ name }) => name,\n All: ({ rules }) => (rules.length === 0 ? 'anyone' : `all(${rules.map(showRule).join(', ')})`),\n Inherit: ({ relation }) => `inherit(${relation})`,\n })\n\nconst showDeny = (deny: Deny): string =>\n Match.valueTags(deny, {\n NotFound: () => 'not_found',\n Omit: () => 'omit',\n Redact: ({ value }) => `redact(${JSON.stringify(value)})`,\n Forbidden: () => 'forbidden',\n Explain: ({ reason }) => `explain(${JSON.stringify(reason)})`,\n })\n\nconst notFound: Deny = Object.freeze({ _tag: 'NotFound' })\nconst omit: Deny = Object.freeze({ _tag: 'Omit' })\nconst forbidden: Deny = Object.freeze({ _tag: 'Forbidden' })\n\n/** The refusal a surface takes when none was chosen. */\nexport const defaultDeny = (target: Target): Deny =>\n target.interaction === 'Read'\n ? Match.valueTags(target, { Row: () => notFound, Member: () => omit, Relation: () => omit })\n : forbidden\n\n/** The guards a surface carries; `none` where it falls to the set's `unguarded`. */\nexport const surfaceOf = (attachment: Attachment, target: Target): Option.Option<Surface> =>\n Match.valueTags(target, {\n Row: ({ interaction }) => Option.fromUndefinedOr(attachment.row[interaction]),\n Member: ({ member, interaction }) => {\n const surfaces = attachment.members[member]\n if (surfaces === undefined) return Option.none()\n const own = surfaces[interaction]\n // A member a caller may not change is rarely one it may set freely on creation.\n return Option.fromUndefinedOr(\n own === undefined && interaction === 'Create' ? surfaces['Update'] : own,\n )\n },\n Relation: ({ relation, interaction }) =>\n Option.fromUndefinedOr(attachment.relations[relation]?.[interaction]),\n })\n\n/** Whether who may read the rows depends on who is asking: a row Read rule, or `always`. */\n/** `Guards.anyone`: a conjunction of nothing, which every principal passes. */\nexport const isAnyone = (rule: AnyRule): boolean => rule._tag === 'All' && rule.rules.length === 0\n\n/** Whether a surface's rules restrict who passes: not when one of them is `anyone`. */\nexport const restricts = (surface: Option.Option<Surface>): boolean =>\n Option.exists(surface, ({ rules }) => !rules.some(isAnyone))\n\nexport const readRowsRuled = (attachment: Attachment): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Row', interaction: 'Read' })) ||\n attachment.always.some(rule => !isAnyone(rule))\n\n/** Whether `member`, a field or a relation, has a Read rule of its own. */\nexport const readRuled = (attachment: Attachment, member: string): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })) ||\n restricts(surfaceOf(attachment, { _tag: 'Relation', relation: member, interaction: 'Read' }))\n\nconst key = Metadata.key<Attachment>('foldkit-guard/attachment', {\n merge: attachments => [mergeAttachments(attachments)],\n summarize: attachment =>\n linesOf(attachment)\n .map(([where, rule]) => `${where}: ${rule}`)\n .join('; '),\n})\n\n/** The rows of an attachment's matrix: each surface it decides, and how. */\nconst linesOf = (attachment: Attachment): ReadonlyArray<readonly [string, string]> => {\n const open = attachment.unguarded === 'allow' ? 'open' : 'closed'\n const show = (target: Target) =>\n Option.match(surfaceOf(attachment, target), {\n onNone: () => open,\n onSome: ({ rules, deny }) =>\n // An empty disjunction allows no one.\n `${rules.length === 0 ? 'nobody' : rules.map(showRule).join(' | ')} → ${showDeny(Option.getOrElse(deny, () => defaultDeny(target)))}`,\n })\n const interactions = [\n 'Read',\n 'Create',\n 'Update',\n 'Delete',\n ...Object.keys(attachment.row).filter(interaction => !builtIn.includes(interaction as never)),\n ]\n return [\n ...(attachment.always.length > 0\n ? [['always', attachment.always.map(showRule).join(' & ')] as const]\n : []),\n ...interactions.map(interaction => [interaction, show({ _tag: 'Row', interaction })] as const),\n ...Object.keys(attachment.members).flatMap(member =>\n ['Read', 'Create', 'Update'].flatMap(interaction => {\n const target: Target = { _tag: 'Member', member, interaction }\n return Option.isSome(surfaceOf(attachment, target))\n ? [[`${member}.${interaction}`, show(target)] as const]\n : []\n }),\n ),\n ...Object.entries(attachment.relations).flatMap(([relation, surfaces]) =>\n Object.keys(surfaces).map(\n interaction =>\n [\n `${relation}.${interaction}`,\n show({ _tag: 'Relation', relation, interaction }),\n ] as const,\n ),\n ),\n ]\n}\n\nconst isOn = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): slot is On<AnyRule, Deny> =>\n !Array.isArray(slot)\n\nconst surfaceFrom = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): Surface =>\n isOn(slot)\n ? { rules: slot.rules, deny: Option.some(slot.deny) }\n : { rules: Object.freeze([...slot]), deny: Option.none() }\n\n/** Throws for a row guard over another Entity that shares the target's name. */\nconst checkRules = (\n set: string,\n entity: AnyEntity,\n where: string,\n rules: ReadonlyArray<AnyRule>,\n): void => {\n for (const rule of rules) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n if (!Entity.same(guard.entity, entity)) {\n throw new Error(\n `[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, a guard over another Entity named ${entity.name}`,\n )\n }\n },\n All: ({ rules }) => checkRules(set, entity, where, rules),\n Inherit: () => {},\n })\n }\n}\n\nconst surfacesFrom = (\n set: string,\n entity: AnyEntity,\n where: string,\n slots: Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>>,\n): Surfaces => {\n const surfaces = record<Surface>()\n // `Write` goes first, whatever order the keys were written in: beside it, a\n // slot of its own adds rules to it and its refusal replaces Write's.\n const ordered = Object.entries(slots).sort(\n ([left], [right]) => Number(right === 'Write') - Number(left === 'Write'),\n )\n for (const [interaction, slot] of ordered) {\n if (slot === undefined) continue\n const added = surfaceFrom(slot)\n checkRules(set, entity, `${where}${interaction}`, added.rules)\n // Write is shorthand, so it is stored as the three it stands for.\n for (const each of interaction === 'Write' ? ['Create', 'Update', 'Delete'] : [interaction]) {\n appendSurface(surfaces, each, added)\n }\n }\n return Object.freeze(surfaces)\n}\n\nconst nested = (\n set: string,\n entity: AnyEntity,\n given: Readonly<\n Record<\n string,\n Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>> | undefined\n >\n >,\n): Readonly<Record<string, Surfaces>> => {\n const surfaces = record<Surfaces>()\n for (const [member, slots] of Object.entries(given)) {\n if (slots !== undefined) surfaces[member] = surfacesFrom(set, entity, `${member}.`, slots)\n }\n return Object.freeze(surfaces)\n}\n\n/** A row guard's own fields, and the relation an inherited Read follows. */\nconst membersRead = (rule: AnyRule): ReadonlyArray<string> =>\n Match.valueTags(rule, {\n PrincipalGuard: () => [],\n RowGuard: ({ query }) => Query.dependencies(query).predicate.map(field => field.key),\n All: ({ rules }) => rules.flatMap(membersRead),\n Inherit: ({ relation }) => [relation],\n })\n\nexport const attached = (entity: AnyEntity): Option.Option<Attachment> =>\n Option.fromUndefinedOr(key.get(entity.metadata)[0])\n\nexport const Attaching = {\n /**\n * Attaches guards to an Entity, per surface and interaction. A surface's list\n * is a disjunction; `always` is ANDed after it. Attaching twice appends to a\n * surface's list and replaces its refusal.\n */\n attach:\n <Name extends string, User, E extends AnyEntity>(\n G: {\n readonly name: Name\n readonly schema: Schema.Codec<User, unknown>\n readonly unguarded: 'allow' | 'deny'\n },\n config: Attach<NoInfer<User>, NoInfer<Name>, E>,\n ) =>\n (entity: E): E => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== G.name) {\n throw new Error(\n `[foldkit-guard] ${G.name}.attach: ${entity.name} carries the guards of ${set} already`,\n )\n }\n })\n const always = config.always ?? []\n checkRules(G.name, entity, 'always', always)\n const attachment: Attachment = Object.freeze({\n set: G.name,\n unguarded: G.unguarded,\n // A named interaction is the row's, as the matrix and the decisions read it.\n row: surfacesFrom(G.name, entity, '', { ...config.row, ...config.interactions }),\n members: nested(G.name, entity, config.members ?? {}),\n relations: nested(G.name, entity, config.relations ?? {}),\n always: Object.freeze([...always]),\n })\n // What the row's Read rules read, so a client placing rows knows it cannot judge a change to them.\n const filtered = [\n ...new Set(\n [...(attachment.row['Read']?.rules ?? []), ...attachment.always].flatMap(membersRead),\n ),\n ]\n return entity.pipe(\n Entity.annotate(Metadata.combine([key.of(attachment), ReadFilter.of(filtered)])),\n )\n },\n\n /** The guards attached to `entity`, every attachment merged. */\n attached,\n\n /** Every rule must allow, as one rule. Principal and row guards may mix. */\n all: <\n const Rules extends readonly [\n Exclude<AnyRule, Inherit<string>>,\n ...ReadonlyArray<Exclude<AnyRule, Inherit<string>>>,\n ],\n >(\n ...rules: Rules\n ): All<Rules[number]> => Object.freeze({ _tag: 'All', rules: Object.freeze([...rules]) }),\n\n /**\n * A rule everyone passes, a visitor included: a conjunction of nothing.\n * For a surface that is public under a set whose `unguarded` is `'deny'`.\n */\n anyone: Object.freeze<All<never>>({ _tag: 'All', rules: Object.freeze([]) }),\n\n /** This row's Read is the Read of the row its `one` relation points at. */\n inherit: <const Relation extends string>(relation: Relation): Inherit<Relation> =>\n Object.freeze({ _tag: 'Inherit', relation }),\n\n /** A surface's guards with a refusal other than its default. */\n on: <const Rules extends ReadonlyArray<AnyRule>, D extends Redact<unknown> | Explain>(\n rules: Rules,\n deny: D,\n ): On<Rules[number], D> => Object.freeze({ _tag: 'On', rules: Object.freeze([...rules]), deny }),\n\n /** A hidden member reads as `value`, typed by the member's schema. */\n redact: <const A>(value: A): Redact<A> => Object.freeze({ _tag: 'Redact', value }),\n\n /** A refused write tells the caller `reason`. */\n explain: (reason: string): Explain => Object.freeze({ _tag: 'Explain', reason }),\n\n /**\n * The members a row interaction's guards read, `always` included: a change\n * to one can change whether a principal may. A relation an inherited Read\n * follows counts.\n */\n guardFields: (\n entity: AnyEntity,\n interaction: 'Read' | 'Create' | 'Update' | 'Delete' | InteractionKey,\n ): ReadonlyArray<string> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [\n ...new Set(\n [...(attachment.row[interaction]?.rules ?? []), ...attachment.always].flatMap(\n membersRead,\n ),\n ),\n ],\n }),\n\n /** Who may do what, one line per surface, for review and for a committed snapshot. */\n matrix: (entities: ReadonlyArray<AnyEntity>): string =>\n entities\n .flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [`${entity.name}: no guards`],\n onSome: attachment =>\n linesOf(attachment).map(([where, rule]) => `${entity.name}.${where}: ${rule}`),\n }),\n )\n .join('\\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;AAsIA,MAAM,eAAqC,OAAO,OAAO,IAAI;AAE7D,MAAM,iBAAiB,MAA+B,aAAqB,UAAmB;CAC5F,MAAM,SAAS,KAAK;C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,SAAS,CAAC,GAAI,GAAG,WAAW,MAAM,CAAC,CAAC,QACpE,WACF,CACF,CACF;CACF,CAAC;;CAGH,SAAS,aACP,SACG,SAAQ,WACP,OAAO,MAAM,SAAS,MAAM,GAAG;EAC7B,cAAc,CAAC,GAAG,OAAO,KAAK,YAAY;EAC1C,SAAQ,eACN,QAAQ,UAAU,CAAC,CAAC,KAAK,CAAC,OAAO,UAAU,GAAG,OAAO,KAAK,GAAG,MAAM,IAAI,MAAM;CACjF,CAAC,CACH,CAAC,CACA,KAAK,IAAI;AAChB"}
1
+ {"version":3,"file":"attach-BZyVvs7H.mjs","names":[],"sources":["../src/attach.ts"],"sourcesContent":["/**\n * Attaching a guard set's guards to an Entity, per surface and interaction,\n * as metadata only `foldkit-guard` reads. See `guard-DESIGN.md` §3.2.\n */\nimport { Match, Option, type Schema } from 'effect'\nimport { Entity, Query, ReadFilter, type AnyEntity } from 'foldkit-entity'\nimport { Metadata } from 'foldkit-metadata'\nimport type { PrincipalGuard, RowGuard } from './index.js'\n\ndeclare const InteractionBrand: unique symbol\n\n/** An interaction the application names, used as a computed key: `[Archive.key]`. */\nexport type InteractionKey<Name extends string = string> = Name & {\n readonly [InteractionBrand]: Name\n}\n\nexport interface Interaction<Name extends string> {\n readonly name: Name\n readonly key: InteractionKey<Name>\n}\n\n/** The interactions every row has, and the ones a relation member has. */\nconst builtIn = ['Read', 'Create', 'Update', 'Delete', 'Write', 'Link', 'Unlink'] as const\n\nexport const Interaction = {\n /** An interaction beyond Read, Create, Update and Delete, such as `Archive`. */\n make: <const Name extends string>(name: Name): Interaction<Name> => {\n if ((builtIn as ReadonlyArray<string>).includes(name)) {\n throw new Error(`[foldkit-guard] Interaction.make: \"${name}\" is an interaction already`)\n }\n return Object.freeze({ name, key: name as InteractionKey<Name> })\n },\n}\n\n/** Every guard of `Rules` must allow, as one guard: `Guards.all(signedIn, isOwner)`. */\nexport interface All<Rules> {\n readonly _tag: 'All'\n readonly rules: ReadonlyArray<Rules>\n}\n\n/** This row's Read is the Read of the row its `one` relation points at. */\nexport interface Inherit<Relation extends string> {\n readonly _tag: 'Inherit'\n readonly relation: Relation\n}\n\n/** What a member hidden by its Read guards reads as instead of its value. */\nexport interface Redact<A> {\n readonly _tag: 'Redact'\n readonly value: A\n}\n\n/** A refused write's sentence, for the application's own users. */\nexport interface Explain {\n readonly _tag: 'Explain'\n readonly reason: string\n}\n\n/**\n * What a refusal looks like. The defaults need no constructor: a row Read\n * answers `NotFound`, a member or relation Read `Omit`, a write `Forbidden`.\n */\nexport type Deny =\n | { readonly _tag: 'NotFound' }\n | { readonly _tag: 'Omit' }\n | Redact<unknown>\n | { readonly _tag: 'Forbidden' }\n | Explain\n\n/** A surface's guards with a refusal other than its default. */\nexport interface On<Rules, D extends Deny> {\n readonly _tag: 'On'\n readonly rules: ReadonlyArray<Rules>\n readonly deny: D\n}\n\n/** Anything a surface's list may hold, of any guard set. */\nexport type AnyRule =\n | PrincipalGuard<any, string>\n | RowGuard<any, AnyEntity, string>\n | All<any>\n | Inherit<string>\n\n/**\n * What a surface of the Entity named `Name` accepts from the guard set `Set`:\n * its principal guards, its row guards over that Entity, and conjunctions of\n * both. A row guard over another Entity, or a guard of another set, is refused.\n */\nexport type RuleFor<User, Set extends string, Name extends string> =\n | PrincipalGuard<User, Set>\n | RowGuard<User, Entity<Name, any, any, any>, Set>\n | All<RuleFor<User, Set, Name>>\n\ntype Slot<Rule, D extends Deny> = ReadonlyArray<Rule> | On<Rule, D>\n\ntype WriteSlot<Rule> = Slot<Rule, Explain>\n\ntype OneRelations<E extends AnyEntity> = {\n [K in keyof E['relations']]: E['relations'][K] extends { readonly cardinality: 'one' } ? K : never\n}[keyof E['relations']] &\n string\n\ntype MemberKeys<E extends AnyEntity> = (keyof E['fields'] | keyof E['derived']) & string\n\ntype TypeOf<E extends AnyEntity, K extends keyof E['members']> = E['members'][K]['schema']['Type']\n\n/** What `Guards.attach` takes for the Entity `E`, every key checked against it. */\nexport type Attach<User, Set extends string, E extends AnyEntity> = {\n readonly row?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']> | Inherit<OneRelations<E>>>\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Delete?: WriteSlot<RuleFor<User, Set, E['name']>>\n /** The same guards on Create, Update and Delete. */\n readonly Write?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /**\n * The row's interactions the application named, by key:\n * `{ [Archive.key]: [G.isAdmin] }`. Apart from `row`, whose `Read` may\n * inherit: a literal with a computed key is typed as an index signature,\n * which `Read`'s rules would have to fit too.\n */\n readonly interactions?: {\n readonly [K: InteractionKey]: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n /** Narrow a field or derived member: a member is reachable only if its row is. */\n readonly members?: {\n readonly [K in MemberKeys<E>]?: {\n readonly Read?: Slot<RuleFor<User, Set, E['name']>, Redact<TypeOf<E, K>>>\n /** When absent, `Update`'s guards govern setting the member on creation too. */\n readonly Create?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Update?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n readonly relations?: {\n readonly [K in keyof E['relations']]?: {\n readonly Read?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n readonly Link?: WriteSlot<RuleFor<User, Set, E['name']>>\n readonly Unlink?: WriteSlot<RuleFor<User, Set, E['name']>>\n }\n }\n /** ANDed with every surface's guards, and never out-voted by them. */\n readonly always?: ReadonlyArray<RuleFor<User, Set, E['name']>>\n}\n\n/** One surface's guards as attached: a disjunction, and a refusal if one was chosen. */\nexport interface Surface {\n readonly rules: ReadonlyArray<AnyRule>\n readonly deny: Option.Option<Deny>\n}\n\ntype Surfaces = Readonly<Record<string, Surface>>\n\n/** An Entity's guards, every attachment merged. */\nexport interface Attachment {\n readonly set: string\n readonly unguarded: 'allow' | 'deny'\n readonly row: Surfaces\n readonly members: Readonly<Record<string, Surfaces>>\n readonly relations: Readonly<Record<string, Surfaces>>\n readonly always: ReadonlyArray<AnyRule>\n}\n\n/** Which surface a rule is asked about. */\ntype Target =\n | { readonly _tag: 'Row'; readonly interaction: string }\n | { readonly _tag: 'Member'; readonly member: string; readonly interaction: string }\n | { readonly _tag: 'Relation'; readonly relation: string; readonly interaction: string }\n\nconst record = <A>(): Record<string, A> => Object.create(null)\n\nconst appendSurface = (into: Record<string, Surface>, interaction: string, added: Surface) => {\n const before = into[interaction]\n into[interaction] =\n before === undefined\n ? added\n : {\n rules: [...before.rules, ...added.rules],\n deny: Option.orElse(added.deny, () => before.deny),\n }\n}\n\nconst appendSurfaces = (into: Record<string, Surface>, added: Surfaces) => {\n for (const [interaction, surface] of Object.entries(added)) {\n appendSurface(into, interaction, surface)\n }\n}\n\nconst freezeSurfaces = (surfaces: Record<string, Surfaces>) => {\n for (const key of Object.keys(surfaces)) Object.freeze(surfaces[key])\n return Object.freeze(surfaces)\n}\n\n/** Later attachments append to each surface's disjunction and replace its refusal. */\nconst mergeAttachments = (attachments: ReadonlyArray<Attachment>): Attachment => {\n const row = record<Surface>()\n const members = record<Record<string, Surface>>()\n const relations = record<Record<string, Surface>>()\n const always: Array<AnyRule> = []\n for (const attachment of attachments) {\n appendSurfaces(row, attachment.row)\n for (const [key, surfaces] of Object.entries(attachment.members)) {\n appendSurfaces((members[key] ??= record()), surfaces)\n }\n for (const [key, surfaces] of Object.entries(attachment.relations)) {\n appendSurfaces((relations[key] ??= record()), surfaces)\n }\n always.push(...attachment.always)\n }\n const { set, unguarded } = attachments[0]!\n return Object.freeze({\n set,\n unguarded,\n row: Object.freeze(row),\n members: freezeSurfaces(members),\n relations: freezeSurfaces(relations),\n always: Object.freeze(always),\n })\n}\n\nconst showRule = (rule: AnyRule): string =>\n Match.valueTags(rule, {\n PrincipalGuard: ({ name }) => name,\n RowGuard: ({ name }) => name,\n All: ({ rules }) => (rules.length === 0 ? 'anyone' : `all(${rules.map(showRule).join(', ')})`),\n Inherit: ({ relation }) => `inherit(${relation})`,\n })\n\nconst showDeny = (deny: Deny): string =>\n Match.valueTags(deny, {\n NotFound: () => 'not_found',\n Omit: () => 'omit',\n Redact: ({ value }) => `redact(${JSON.stringify(value)})`,\n Forbidden: () => 'forbidden',\n Explain: ({ reason }) => `explain(${JSON.stringify(reason)})`,\n })\n\nconst notFound: Deny = Object.freeze({ _tag: 'NotFound' })\nconst omit: Deny = Object.freeze({ _tag: 'Omit' })\nconst forbidden: Deny = Object.freeze({ _tag: 'Forbidden' })\n\n/** The refusal a surface takes when none was chosen. */\nexport const defaultDeny = (target: Target): Deny =>\n target.interaction === 'Read'\n ? Match.valueTags(target, { Row: () => notFound, Member: () => omit, Relation: () => omit })\n : forbidden\n\n/** The guards a surface carries; `none` where it falls to the set's `unguarded`. */\nexport const surfaceOf = (attachment: Attachment, target: Target): Option.Option<Surface> =>\n Match.valueTags(target, {\n Row: ({ interaction }) => Option.fromUndefinedOr(attachment.row[interaction]),\n Member: ({ member, interaction }) => {\n const surfaces = attachment.members[member]\n if (surfaces === undefined) return Option.none()\n const own = surfaces[interaction]\n // A member a caller may not change is rarely one it may set freely on creation.\n return Option.fromUndefinedOr(\n own === undefined && interaction === 'Create' ? surfaces['Update'] : own,\n )\n },\n Relation: ({ relation, interaction }) =>\n Option.fromUndefinedOr(attachment.relations[relation]?.[interaction]),\n })\n\n/** Whether who may read the rows depends on who is asking: a row Read rule, or `always`. */\n/** `Guards.anyone`: a conjunction of nothing, which every principal passes. */\nexport const isAnyone = (rule: AnyRule): boolean => rule._tag === 'All' && rule.rules.length === 0\n\n/** Whether a surface's rules restrict who passes: not when one of them is `anyone`. */\nexport const restricts = (surface: Option.Option<Surface>): boolean =>\n Option.exists(surface, ({ rules }) => !rules.some(isAnyone))\n\nexport const readRowsRuled = (attachment: Attachment): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Row', interaction: 'Read' })) ||\n attachment.always.some(rule => !isAnyone(rule))\n\n/** Whether `member`, a field or a relation, has a Read rule of its own. */\nexport const readRuled = (attachment: Attachment, member: string): boolean =>\n restricts(surfaceOf(attachment, { _tag: 'Member', member, interaction: 'Read' })) ||\n restricts(surfaceOf(attachment, { _tag: 'Relation', relation: member, interaction: 'Read' }))\n\nconst key = Metadata.key<Attachment>('foldkit-guard/attachment', {\n merge: attachments => [mergeAttachments(attachments)],\n summarize: attachment =>\n linesOf(attachment)\n .map(([where, rule]) => `${where}: ${rule}`)\n .join('; '),\n})\n\n/** The rows of an attachment's matrix: each surface it decides, and how. */\nconst linesOf = (attachment: Attachment): ReadonlyArray<readonly [string, string]> => {\n const open = attachment.unguarded === 'allow' ? 'open' : 'closed'\n const show = (target: Target) =>\n Option.match(surfaceOf(attachment, target), {\n onNone: () => open,\n onSome: ({ rules, deny }) =>\n // An empty disjunction allows no one.\n `${rules.length === 0 ? 'nobody' : rules.map(showRule).join(' | ')} → ${showDeny(Option.getOrElse(deny, () => defaultDeny(target)))}`,\n })\n const interactions = [\n 'Read',\n 'Create',\n 'Update',\n 'Delete',\n ...Object.keys(attachment.row).filter(interaction => !builtIn.includes(interaction as never)),\n ]\n return [\n ...(attachment.always.length > 0\n ? [['always', attachment.always.map(showRule).join(' & ')] as const]\n : []),\n ...interactions.map(interaction => [interaction, show({ _tag: 'Row', interaction })] as const),\n ...Object.keys(attachment.members).flatMap(member =>\n ['Read', 'Create', 'Update'].flatMap(interaction => {\n const target: Target = { _tag: 'Member', member, interaction }\n return Option.isSome(surfaceOf(attachment, target))\n ? [[`${member}.${interaction}`, show(target)] as const]\n : []\n }),\n ),\n ...Object.entries(attachment.relations).flatMap(([relation, surfaces]) =>\n Object.keys(surfaces).map(\n interaction =>\n [\n `${relation}.${interaction}`,\n show({ _tag: 'Relation', relation, interaction }),\n ] as const,\n ),\n ),\n ]\n}\n\nconst isOn = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): slot is On<AnyRule, Deny> =>\n !Array.isArray(slot)\n\nconst surfaceFrom = (slot: ReadonlyArray<AnyRule> | On<AnyRule, Deny>): Surface =>\n isOn(slot)\n ? { rules: slot.rules, deny: Option.some(slot.deny) }\n : { rules: Object.freeze([...slot]), deny: Option.none() }\n\n/** Throws for a row guard over another Entity that shares the target's name. */\nconst checkRules = (\n set: string,\n entity: AnyEntity,\n where: string,\n rules: ReadonlyArray<AnyRule>,\n): void => {\n for (const rule of rules) {\n Match.valueTags(rule, {\n PrincipalGuard: () => {},\n RowGuard: guard => {\n if (!Entity.same(guard.entity, entity)) {\n throw new Error(\n `[foldkit-guard] ${set}.attach: ${where} names ${guard.name}, a guard over another Entity named ${entity.name}`,\n )\n }\n },\n All: ({ rules }) => checkRules(set, entity, where, rules),\n Inherit: () => {},\n })\n }\n}\n\nconst surfacesFrom = (\n set: string,\n entity: AnyEntity,\n where: string,\n slots: Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>>,\n): Surfaces => {\n const surfaces = record<Surface>()\n // `Write` goes first, whatever order the keys were written in: beside it, a\n // slot of its own adds rules to it and its refusal replaces Write's.\n const ordered = Object.entries(slots).sort(\n ([left], [right]) => Number(right === 'Write') - Number(left === 'Write'),\n )\n for (const [interaction, slot] of ordered) {\n if (slot === undefined) continue\n const added = surfaceFrom(slot)\n checkRules(set, entity, `${where}${interaction}`, added.rules)\n // Write is shorthand, so it is stored as the three it stands for.\n for (const each of interaction === 'Write' ? ['Create', 'Update', 'Delete'] : [interaction]) {\n appendSurface(surfaces, each, added)\n }\n }\n return Object.freeze(surfaces)\n}\n\nconst nested = (\n set: string,\n entity: AnyEntity,\n given: Readonly<\n Record<\n string,\n Readonly<Record<string, ReadonlyArray<AnyRule> | On<AnyRule, Deny> | undefined>> | undefined\n >\n >,\n): Readonly<Record<string, Surfaces>> => {\n const surfaces = record<Surfaces>()\n for (const [member, slots] of Object.entries(given)) {\n if (slots !== undefined) surfaces[member] = surfacesFrom(set, entity, `${member}.`, slots)\n }\n return Object.freeze(surfaces)\n}\n\n/** A row guard's own fields, and the relation an inherited Read follows. */\nconst membersRead = (rule: AnyRule): ReadonlyArray<string> =>\n Match.valueTags(rule, {\n PrincipalGuard: () => [],\n RowGuard: ({ query }) => Query.dependencies(query).predicate.map(field => field.key),\n All: ({ rules }) => rules.flatMap(membersRead),\n Inherit: ({ relation }) => [relation],\n })\n\nexport const attached = (entity: AnyEntity): Option.Option<Attachment> =>\n Option.fromUndefinedOr(key.get(entity.metadata)[0])\n\nexport const Attaching = {\n /**\n * Attaches guards to an Entity, per surface and interaction. A surface's list\n * is a disjunction; `always` is ANDed after it. Attaching twice appends to a\n * surface's list and replaces its refusal.\n */\n attach:\n <Name extends string, User, E extends AnyEntity>(\n G: {\n readonly name: Name\n readonly schema: Schema.Codec<User, unknown>\n readonly unguarded: 'allow' | 'deny'\n },\n config: Attach<NoInfer<User>, NoInfer<Name>, E>,\n ) =>\n (entity: E): E => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== G.name) {\n throw new Error(\n `[foldkit-guard] ${G.name}.attach: ${entity.name} carries the guards of ${set} already`,\n )\n }\n })\n const always = config.always ?? []\n checkRules(G.name, entity, 'always', always)\n const attachment: Attachment = Object.freeze({\n set: G.name,\n unguarded: G.unguarded,\n // A named interaction is the row's, as the matrix and the decisions read it.\n row: surfacesFrom(G.name, entity, '', { ...config.row, ...config.interactions }),\n members: nested(G.name, entity, config.members ?? {}),\n relations: nested(G.name, entity, config.relations ?? {}),\n always: Object.freeze([...always]),\n })\n // What the row's Read rules read, so a client placing rows knows it cannot judge a change to them.\n const filtered = [\n ...new Set(\n [...(attachment.row['Read']?.rules ?? []), ...attachment.always].flatMap(membersRead),\n ),\n ]\n return entity.pipe(\n Entity.annotate(Metadata.combine([key.of(attachment), ReadFilter.of(filtered)])),\n )\n },\n\n /** The guards attached to `entity`, every attachment merged. */\n attached,\n\n /** Every rule must allow, as one rule. Principal and row guards may mix. */\n all: <\n const Rules extends readonly [\n Exclude<AnyRule, Inherit<string>>,\n ...ReadonlyArray<Exclude<AnyRule, Inherit<string>>>,\n ],\n >(\n ...rules: Rules\n ): All<Rules[number]> => Object.freeze({ _tag: 'All', rules: Object.freeze([...rules]) }),\n\n /**\n * A rule everyone passes, a visitor included: a conjunction of nothing.\n * For a surface that is public under a set whose `unguarded` is `'deny'`.\n */\n anyone: Object.freeze<All<never>>({ _tag: 'All', rules: Object.freeze([]) }),\n\n /** This row's Read is the Read of the row its `one` relation points at. */\n inherit: <const Relation extends string>(relation: Relation): Inherit<Relation> =>\n Object.freeze({ _tag: 'Inherit', relation }),\n\n /** A surface's guards with a refusal other than its default. */\n on: <const Rules extends ReadonlyArray<AnyRule>, D extends Redact<unknown> | Explain>(\n rules: Rules,\n deny: D,\n ): On<Rules[number], D> => Object.freeze({ _tag: 'On', rules: Object.freeze([...rules]), deny }),\n\n /** A hidden member reads as `value`, typed by the member's schema. */\n redact: <const A>(value: A): Redact<A> => Object.freeze({ _tag: 'Redact', value }),\n\n /** A refused write tells the caller `reason`. */\n explain: (reason: string): Explain => Object.freeze({ _tag: 'Explain', reason }),\n\n /**\n * The members a row interaction's guards read, `always` included: a change\n * to one can change whether a principal may. A relation an inherited Read\n * follows counts.\n */\n guardFields: (\n entity: AnyEntity,\n interaction: 'Read' | 'Create' | 'Update' | 'Delete' | InteractionKey,\n ): ReadonlyArray<string> =>\n Option.match(attached(entity), {\n onNone: () => [],\n onSome: attachment => [\n ...new Set(\n [...(attachment.row[interaction]?.rules ?? []), ...attachment.always].flatMap(\n membersRead,\n ),\n ),\n ],\n }),\n\n /** Who may do what, one line per surface, for review and for a committed snapshot. */\n matrix: (entities: ReadonlyArray<AnyEntity>): string =>\n entities\n .flatMap(entity =>\n Option.match(attached(entity), {\n onNone: () => [`${entity.name}: no guards`],\n onSome: attachment =>\n linesOf(attachment).map(([where, rule]) => `${entity.name}.${where}: ${rule}`),\n }),\n )\n .join('\\n'),\n}\n"],"mappings":";;;;;;;;;AAsBA,MAAM,UAAU;CAAC;CAAQ;CAAU;CAAU;CAAU;CAAS;CAAQ;AAAQ;AAEhF,MAAa,cAAc;;AAE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kB,UAAwB,OAAO,OAAO;EAAE,MAAM;EAAU;CAAM,CAAC;;CAGjF,UAAU,WAA4B,OAAO,OAAO;EAAE,MAAM;EAAW;CAAO,CAAC;;;;;;CAO/E,cACE,QACA,gBAEA,OAAO,MAAM,SAAS,MAAM,GAAG;EAC7B,cAAc,CAAC;EACf,SAAQ,eAAc,CACpB,GAAG,IAAI,IACL,CAAC,GAAI,WAAW,IAAI,YAAY,EAAE,SAAS,CAAC,GAAI,GAAG,WAAW,MAAM,CAAC,CAAC,QACpE,WACF,CACF,CACF;CACF,CAAC;;CAGH,SAAS,aACP,SACG,SAAQ,WACP,OAAO,MAAM,SAAS,MAAM,GAAG;EAC7B,cAAc,CAAC,GAAG,OAAO,KAAK,YAAY;EAC1C,SAAQ,eACN,QAAQ,UAAU,CAAC,CAAC,KAAK,CAAC,OAAO,UAAU,GAAG,OAAO,KAAK,GAAG,MAAM,IAAI,MAAM;CACjF,CAAC,CACH,CAAC,CACA,KAAK,IAAI;AAChB"}
@@ -0,0 +1,30 @@
1
+ import { C as PrincipalGuard, S as Policy } from "./attach-BVG6LsFf.mjs";
2
+ import { Effect, Layer, Option } from "effect";
3
+ import { UploadPolicy } from "foldkit-media/server";
4
+ //#region src/media.d.ts
5
+ export interface UploadPolicyConfig<User, E, R> {
6
+ /**
7
+ * Who is asking, from a request holding the upload's URL, method and
8
+ * headers, and no body. A failure means it could not tell (an untrusted
9
+ * origin, a session that ended), answered `401`; none is a visitor.
10
+ */
11
+ readonly resolve: (request: Request) => Effect.Effect<Option.Option<User>, E, R>;
12
+ /** Who may upload: any one of these principal guards. Omitted, nobody. */
13
+ readonly Upload?: ReadonlyArray<PrincipalGuard<User>>;
14
+ /** Who may have an image named by URL described. Omitted, nobody. */
15
+ readonly DescribeUrl?: ReadonlyArray<PrincipalGuard<User>>;
16
+ }
17
+ /**
18
+ * An `UploadPolicy` deciding each route by `policy`'s principal guards for who
19
+ * `resolve` says is asking. A route admits when any one of its guards allows;
20
+ * a refusal's reason stays on the server, as every media refusal says only
21
+ * its kind. `policy` must need no service of its own: give it what its bodies
22
+ * need with `Policy.provide`, as the other seams take it.
23
+ */
24
+ declare const uploadPolicy: <User, E, R>(policy: Policy<User>, config: UploadPolicyConfig<User, E, R>) => Layer.Layer<UploadPolicy, never, R>;
25
+ export declare const GuardMedia: {
26
+ readonly uploadPolicy: typeof uploadPolicy;
27
+ };
28
+ //#endregion
29
+ export {};
30
+ //# sourceMappingURL=media.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media.d.mts","names":[],"sources":["../src/media.ts"],"mappings":";;;;iBAkBiB,mBAAmB,MAAM,GAAG;;;;;;WAMlC,UAAU,SAAS,YAAY,OAAO,OAAO,OAAO,OAAO,OAAO,GAAG;;WAErE,SAAS,cAAc,eAAe;;WAEtC,cAAc,cAAc,eAAe;;;;;;;;;cAyBhD,eAAgB,MAAM,GAAG,GAAC,QACtB,OAAO,OAAK,QACZ,mBAAmB,MAAM,GAAG,OACnC,MAAM,MAAM,qBAAqB;qBAqBvB;gCAAA"}
package/dist/media.mjs ADDED
@@ -0,0 +1,41 @@
1
+ import { Effect, Layer, Option } from "effect";
2
+ import { HttpServerRequest } from "effect/http";
3
+ import { UploadForbidden, UploadPolicy, UploadUnauthenticated } from "foldkit-media/server";
4
+ //#region src/media.ts
5
+ /**
6
+ * `foldkit-guard/media`: `foldkit-media`'s `UploadPolicy` decided by a guard
7
+ * set. Who is asking comes from the application's resolver, the one its
8
+ * Remote server is given (`AuthServer.resolver` from `foldkit-auth/server` has
9
+ * the shape), read from the request's headers alone, so the upload route
10
+ * still reads no byte before the policy has answered. Each route is decided by
11
+ * principal guards, since no row exists yet; a route not named is refused.
12
+ */
13
+ const urlOf = (request) => URL.canParse(request.originalUrl) ? Option.some(new URL(request.originalUrl)) : HttpServerRequest.toURL(request);
14
+ const headersOnly = (request) => Option.map(urlOf(request), (url) => new Request(url, {
15
+ method: request.method,
16
+ headers: request.headers
17
+ }));
18
+ /**
19
+ * An `UploadPolicy` deciding each route by `policy`'s principal guards for who
20
+ * `resolve` says is asking. A route admits when any one of its guards allows;
21
+ * a refusal's reason stays on the server, as every media refusal says only
22
+ * its kind. `policy` must need no service of its own: give it what its bodies
23
+ * need with `Policy.provide`, as the other seams take it.
24
+ */
25
+ const uploadPolicy = (policy, config) => Layer.effect(UploadPolicy, Effect.map(Effect.context(), (context) => ({ admit: (request, route) => Effect.gen(function* () {
26
+ const asked = yield* Option.match(headersOnly(request), {
27
+ onNone: () => Effect.fail(new UploadUnauthenticated({})),
28
+ onSome: Effect.succeed
29
+ });
30
+ const principal = yield* config.resolve(asked).pipe(Effect.mapError(() => new UploadUnauthenticated({})));
31
+ for (const guard of config[route] ?? []) if ((yield* policy.decide(guard, {
32
+ principal,
33
+ interaction: route
34
+ })) === true) return;
35
+ return yield* new UploadForbidden({});
36
+ }).pipe(Effect.provideContext(context)) })));
37
+ const GuardMedia = { uploadPolicy };
38
+ //#endregion
39
+ export { GuardMedia };
40
+
41
+ //# sourceMappingURL=media.mjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"media.mjs","names":[],"sources":["../src/media.ts"],"sourcesContent":["/**\n * `foldkit-guard/media`: `foldkit-media`'s `UploadPolicy` decided by a guard\n * set. Who is asking comes from the application's resolver, the one its\n * Remote server is given (`AuthServer.resolver` from `foldkit-auth/server` has\n * the shape), read from the request's headers alone, so the upload route\n * still reads no byte before the policy has answered. Each route is decided by\n * principal guards, since no row exists yet; a route not named is refused.\n */\nimport { Effect, Layer, Option } from 'effect'\nimport { HttpServerRequest } from 'effect/http'\nimport {\n UploadForbidden,\n UploadPolicy,\n UploadUnauthenticated,\n type UploadRoute,\n} from 'foldkit-media/server'\nimport type { Policy, PrincipalGuard } from './index.js'\n\nexport interface UploadPolicyConfig<User, E, R> {\n /**\n * Who is asking, from a request holding the upload's URL, method and\n * headers, and no body. A failure means it could not tell (an untrusted\n * origin, a session that ended), answered `401`; none is a visitor.\n */\n readonly resolve: (request: Request) => Effect.Effect<Option.Option<User>, E, R>\n /** Who may upload: any one of these principal guards. Omitted, nobody. */\n readonly Upload?: ReadonlyArray<PrincipalGuard<User>>\n /** Who may have an image named by URL described. Omitted, nobody. */\n readonly DescribeUrl?: ReadonlyArray<PrincipalGuard<User>>\n}\n\n// The URL a request arrived at. On the web its `originalUrl` is whole; on a Node server it is a\n// path, and `toURL` rebuilds it from the `Host` header (else `http://localhost`).\nconst urlOf = (request: HttpServerRequest.HttpServerRequest): Option.Option<URL> =>\n URL.canParse(request.originalUrl)\n ? Option.some(new URL(request.originalUrl))\n : HttpServerRequest.toURL(request)\n\n// The URL, method and headers the resolver reads, and never the body: in a Worker,\n// `HttpServerRequest.toWeb` would hand back the request itself, stream and all.\nconst headersOnly = (request: HttpServerRequest.HttpServerRequest): Option.Option<Request> =>\n Option.map(\n urlOf(request),\n url => new Request(url, { method: request.method, headers: request.headers }),\n )\n\n/**\n * An `UploadPolicy` deciding each route by `policy`'s principal guards for who\n * `resolve` says is asking. A route admits when any one of its guards allows;\n * a refusal's reason stays on the server, as every media refusal says only\n * its kind. `policy` must need no service of its own: give it what its bodies\n * need with `Policy.provide`, as the other seams take it.\n */\nconst uploadPolicy = <User, E, R>(\n policy: Policy<User>,\n config: UploadPolicyConfig<User, E, R>,\n): Layer.Layer<UploadPolicy, never, R> =>\n Layer.effect(\n UploadPolicy,\n Effect.map(Effect.context<R>(), context => ({\n admit: (request: HttpServerRequest.HttpServerRequest, route: UploadRoute) =>\n Effect.gen(function* () {\n const asked = yield* Option.match(headersOnly(request), {\n onNone: () => Effect.fail(new UploadUnauthenticated({})),\n onSome: Effect.succeed,\n })\n const principal = yield* config\n .resolve(asked)\n .pipe(Effect.mapError(() => new UploadUnauthenticated({})))\n for (const guard of config[route] ?? []) {\n if ((yield* policy.decide(guard, { principal, interaction: route })) === true) return\n }\n return yield* new UploadForbidden({})\n }).pipe(Effect.provideContext(context)),\n })),\n )\n\nexport const GuardMedia = { uploadPolicy } as const\n"],"mappings":";;;;;;;;;;;;AAiCA,MAAM,SAAS,YACb,IAAI,SAAS,QAAQ,WAAW,IAC5B,OAAO,KAAK,IAAI,IAAI,QAAQ,WAAW,CAAC,IACxC,kBAAkB,MAAM,OAAO;AAIrC,MAAM,eAAe,YACnB,OAAO,IACL,MAAM,OAAO,IACb,QAAO,IAAI,QAAQ,KAAK;CAAE,QAAQ,QAAQ;CAAQ,SAAS,QAAQ;AAAQ,CAAC,CAC9E;;;;;;;;AASF,MAAM,gBACJ,QACA,WAEA,MAAM,OACJ,cACA,OAAO,IAAI,OAAO,QAAW,IAAG,aAAY,EAC1C,QAAQ,SAA8C,UACpD,OAAO,IAAI,aAAa;CACtB,MAAM,QAAQ,OAAO,OAAO,MAAM,YAAY,OAAO,GAAG;EACtD,cAAc,OAAO,KAAK,IAAI,sBAAsB,CAAC,CAAC,CAAC;EACvD,QAAQ,OAAO;CACjB,CAAC;CACD,MAAM,YAAY,OAAO,OACtB,QAAQ,KAAK,CAAC,CACd,KAAK,OAAO,eAAe,IAAI,sBAAsB,CAAC,CAAC,CAAC,CAAC;CAC5D,KAAK,MAAM,SAAS,OAAO,UAAU,CAAC,GACpC,KAAK,OAAO,OAAO,OAAO,OAAO;EAAE;EAAW,aAAa;CAAM,CAAC,OAAO,MAAM;CAEjF,OAAO,OAAO,IAAI,gBAAgB,CAAC,CAAC;AACtC,CAAC,CAAC,CAAC,KAAK,OAAO,eAAe,OAAO,CAAC,EAC1C,EAAE,CACJ;AAEF,MAAa,aAAa,EAAE,aAAa"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "foldkit-guard",
3
- "version": "0.3.0",
3
+ "version": "0.3.1",
4
4
  "description": "Who may do what, declared once on a Foldkit Plus domain: principal guards implemented on the server, row guards as query expressions.",
5
5
  "keywords": [
6
6
  "foldkit",
@@ -48,6 +48,11 @@
48
48
  "foldkit-plus:source": "./src/sync.ts",
49
49
  "types": "./dist/sync.d.mts",
50
50
  "import": "./dist/sync.mjs"
51
+ },
52
+ "./media": {
53
+ "foldkit-plus:source": "./src/media.ts",
54
+ "types": "./dist/media.d.mts",
55
+ "import": "./dist/media.mjs"
51
56
  }
52
57
  },
53
58
  "files": [
@@ -56,21 +61,25 @@
56
61
  "LICENSE"
57
62
  ],
58
63
  "dependencies": {
59
- "foldkit-metadata": "0.1.0",
60
- "foldkit-entity": "0.10.0"
64
+ "foldkit-entity": "0.10.0",
65
+ "foldkit-metadata": "0.1.0"
61
66
  },
62
67
  "peerDependencies": {
63
- "drizzle-orm": "1.0.0-rc.4",
68
+ "drizzle-orm": "1.0.0-rc.5",
64
69
  "effect": "^4.0.0",
65
- "foldkit-remote-drizzle": "^0.12.2",
66
- "foldkit-remote-server": "^0.14.0",
67
- "foldkit-remote": "^0.18.0",
68
- "foldkit-sync": "^0.12.0"
70
+ "foldkit-media": "^0.2.0",
71
+ "foldkit-remote": "^0.18.1",
72
+ "foldkit-remote-drizzle": "^0.12.4",
73
+ "foldkit-sync": "^0.12.1",
74
+ "foldkit-remote-server": "^0.15.1"
69
75
  },
70
76
  "peerDependenciesMeta": {
71
77
  "drizzle-orm": {
72
78
  "optional": true
73
79
  },
80
+ "foldkit-media": {
81
+ "optional": true
82
+ },
74
83
  "foldkit-remote": {
75
84
  "optional": true
76
85
  },
@@ -85,17 +94,18 @@
85
94
  }
86
95
  },
87
96
  "devDependencies": {
88
- "drizzle-orm": "1.0.0-rc.4",
89
- "effect": "^4.0.4",
90
- "foldkit": "0.168.0",
97
+ "drizzle-orm": "1.0.0-rc.5",
98
+ "effect": "^4.0.5",
99
+ "foldkit": "0.169.0",
91
100
  "tsdown": "^0.23.1",
92
101
  "typescript": "7.0.2",
93
- "foldkit-remote": "0.18.0",
94
- "foldkit-agent": "0.8.1",
95
- "foldkit-remote-server": "0.14.0",
96
- "foldkit-remote-drizzle": "0.12.2",
97
- "foldkit-sync": "0.12.0",
98
- "foldkit-surface": "0.10.0"
102
+ "foldkit-media": "0.2.0",
103
+ "foldkit-remote-drizzle": "0.12.4",
104
+ "foldkit-agent": "0.8.2",
105
+ "foldkit-remote": "0.18.1",
106
+ "foldkit-remote-server": "0.15.1",
107
+ "foldkit-surface": "0.10.1",
108
+ "foldkit-sync": "0.12.1"
99
109
  },
100
110
  "scripts": {
101
111
  "build": "tsdown",