foldkit-guard 0.4.0 → 0.6.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 +18 -3
- package/dist/agent.d.mts +1 -3
- package/dist/agent.d.mts.map +1 -1
- package/dist/agent.mjs +2 -3
- package/dist/{attach-BVG6LsFf.d.mts → attach-BepaL930.d.mts} +22 -15
- package/dist/attach-BepaL930.d.mts.map +1 -0
- package/dist/{attach-BZyVvs7H.mjs → attach-CRCF5XHS.mjs} +16 -4
- package/dist/attach-CRCF5XHS.mjs.map +1 -0
- package/dist/{condition-Dunujvzy.mjs → condition-Dx54lL7v.mjs} +11 -7
- package/dist/condition-Dx54lL7v.mjs.map +1 -0
- package/dist/drizzle.d.mts +10 -5
- package/dist/drizzle.d.mts.map +1 -1
- package/dist/drizzle.mjs +20 -15
- package/dist/drizzle.mjs.map +1 -1
- package/dist/index.d.mts +1 -1
- package/dist/index.mjs +12 -11
- package/dist/index.mjs.map +1 -1
- package/dist/{may-DK-2lomO.mjs → may-DzCAt_5M.mjs} +2 -3
- package/dist/{may-DK-2lomO.mjs.map → may-DzCAt_5M.mjs.map} +1 -1
- package/dist/{me-DeSZOGt3.mjs → me-BYpuVqJE.mjs} +4 -5
- package/dist/{me-DeSZOGt3.mjs.map → me-BYpuVqJE.mjs.map} +1 -1
- package/dist/media.d.mts +1 -3
- package/dist/media.d.mts.map +1 -1
- package/dist/media.mjs +1 -2
- package/dist/{origin-CN6ThFTp.mjs → origin-igJoiz74.mjs} +2 -3
- package/dist/{origin-CN6ThFTp.mjs.map → origin-igJoiz74.mjs.map} +1 -1
- package/dist/{placed-CkyMqxFw.mjs → placed-BvdNmZJu.mjs} +4 -5
- package/dist/{placed-CkyMqxFw.mjs.map → placed-BvdNmZJu.mjs.map} +1 -1
- package/dist/server.d.mts +1 -3
- package/dist/server.d.mts.map +1 -1
- package/dist/server.mjs +82 -28
- package/dist/server.mjs.map +1 -1
- package/dist/sync.d.mts +1 -3
- package/dist/sync.d.mts.map +1 -1
- package/dist/sync.mjs +4 -5
- package/dist/sync.mjs.map +1 -1
- package/package.json +12 -12
- package/dist/attach-BVG6LsFf.d.mts.map +0 -1
- package/dist/attach-BZyVvs7H.mjs.map +0 -1
- package/dist/condition-Dunujvzy.mjs.map +0 -1
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Who may do what, declared once on the domain.\n *\n * A guard set names its guards once, in shared code the client imports too.\n * A **principal guard** is declared by name and implemented only on the\n * server (`G.implement`), so its logic never ships. A **row guard** is an\n * `Expr` over one Entity's fields with the principal's fields as inputs: data,\n * which the SQL compiler and `evaluate` both run. See `guard-DESIGN.md`.\n */\nimport { Context, Effect, Match, Option, Schema } from 'effect'\nimport { Attaching, attached, type InteractionKey } from './attach.js'\nimport {\n deciding,\n readsPrincipal,\n type Condition,\n type MemberRead,\n type RowRule,\n} from './condition.js'\nimport { May } from './may.js'\nimport { me } from './me.js'\nimport { providedFrom } from './origin.js'\nimport {\n Expr,\n Query,\n evaluate,\n type AnyEntity,\n type AnyQuery,\n type InputExpr,\n type Predicate,\n} from 'foldkit-entity'\n\n/** A guard's answer: allowed, refused, or refused with a sentence the caller may read. */\nexport type Decision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a principal guard is asked about. */\nexport interface About {\n /** The interaction attempted: `Read`, `Update`, or one the application names. */\n readonly interaction: string\n}\n\n/**\n * The principal's fields as a row guard's body sees them: each an input named\n * `principal.<field>`, typed as the field. A body is built once, so it holds\n * these placeholders and never a value: branching on one is a type error.\n */\nexport type Placeholders<User> = {\n readonly [K in keyof User & string]: InputExpr<User[K]>\n}\n\n/** What `guard.principal()` declares: a name whose body the server supplies. */\nexport interface PrincipalSpec {\n readonly _tag: 'PrincipalSpec'\n}\n\n/** What `guard.row(entity, body)` declares: a predicate over one Entity's rows. */\nexport interface RowSpec<E extends AnyEntity> {\n readonly _tag: 'RowSpec'\n readonly entity: E\n readonly body: Predicate\n}\n\ntype AnySpec = PrincipalSpec | RowSpec<AnyEntity>\n\n/**\n * The principal a guard is for, kept in the type so a guard of one principal\n * cannot stand where another's is wanted. A function type, so it is invariant.\n */\ninterface ForPrincipal<User> {\n readonly '~principal'?: (user: User) => User\n}\n\n/** A guard whose body lives on the server, asked of the principal alone. */\nexport interface PrincipalGuard<User, Set extends string = string> extends ForPrincipal<User> {\n readonly _tag: 'PrincipalGuard'\n readonly name: string\n /** The name of the guard set it belongs to. */\n readonly set: Set\n}\n\n/** A guard over the rows of `E`: its predicate, and the query that asks it of rows. */\nexport interface RowGuard<\n User,\n E extends AnyEntity,\n Set extends string = string,\n> extends ForPrincipal<User> {\n readonly _tag: 'RowGuard'\n readonly name: string\n readonly set: Set\n readonly entity: E\n readonly body: Predicate\n /** `from(entity).where(body)`, for an interpreter that runs queries. */\n readonly query: AnyQuery\n}\n\nexport type AnyGuard<User> = PrincipalGuard<User> | RowGuard<User, AnyEntity>\n\ntype GuardOf<User, Set extends string, S> =\n S extends RowSpec<infer E> ? RowGuard<User, E, Set> : PrincipalGuard<User, Set>\n\n/** The keys of a spec record that are principal guards: what `implement` must supply. */\ntype PrincipalKeys<S> = { [K in keyof S]: S[K] extends PrincipalSpec ? K : never }[keyof S]\n\n/** A principal guard's body, on the server. */\nexport type Body<User, R = never> = (\n principal: Option.Option<User>,\n about: About,\n) => Decision | Effect.Effect<Decision, never, R>\n\n/** Names a guard set reserves for itself, which no guard may take. */\nconst reserved = [\n 'name',\n 'schema',\n 'Principal',\n 'key',\n 'unguarded',\n 'inputOf',\n 'implement',\n] as const\ntype Reserved = (typeof reserved)[number]\n\n/** Who is asking, for one guard set: a visitor is `none`. */\nexport interface PrincipalOf<Name extends string> {\n readonly '~guardSet': Name\n}\n\n/** The guard set of one application, as `Guards.declare` returns it. */\nexport type GuardSet<Name extends string, User, S> = {\n readonly [K in keyof S]: GuardOf<User, Name, S[K]>\n} & {\n readonly name: Name\n /** The principal's schema, whose fields the row guards read. */\n readonly schema: Schema.Codec<User, unknown>\n /** The server's Context key for who is asking. Authentication provides it. */\n readonly Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>\n /** A stable name for the person, whatever their claims: for what is theirs, as a cache's scope. */\n readonly key: (user: User) => string\n readonly unguarded: 'allow' | 'deny'\n /** The principal's fields as row guards' inputs, encoded as stored values are. */\n readonly inputOf: (user: User) => Readonly<Record<string, unknown>>\n /** The bodies of the principal guards: every one, and nothing else. */\n readonly implement: <R = never>(bodies: {\n readonly [K in PrincipalKeys<S>]: Body<User, R>\n }) => Policy<User, R>\n}\n\n/** The server's half of a guard set: every principal guard's body. */\nexport interface Policy<User, R = never> {\n readonly set: string\n /**\n * Whether `guard` allows `principal`, for a row guard over `row` (its stored,\n * encoded values). A visitor passes no row guard that reads a principal's\n * fields; one over the row alone holds for a visitor too.\n */\n readonly decide: (\n guard: AnyGuard<User>,\n request: {\n readonly principal: Option.Option<User>\n readonly interaction: string\n readonly row?: Readonly<Record<string, unknown>> | undefined\n },\n ) => Effect.Effect<Decision, never, R>\n /**\n * Which rows of `entity` `principal` may read, as a condition over the row\n * with every principal guard already decided. An Entity without guards, or\n * of no set, reads `Always`.\n */\n readonly readable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n ) => Effect.Effect<Condition, never, R>\n /** The read rule of each of `members`, relations included, that has one, decided for `principal`. */\n readonly readMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /**\n * Which rows of `entity` `principal` may write by `interaction` (`Create`,\n * `Update`, `Delete`, or one the application named), as a condition over\n * the row, and what a refusal shows.\n */\n readonly writable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: 'Create' | 'Update' | 'Delete' | InteractionKey,\n ) => Effect.Effect<RowRule, never, R>\n /** The rule of each of `members` that has one for setting it, decided for `principal`. */\n readonly writeMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n interaction: 'Create' | 'Update',\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /** A relation's rule for linking or unlinking a row, when it has one. */\n readonly linkable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n relation: string,\n interaction: 'Link' | 'Unlink',\n ) => Effect.Effect<Option.Option<RowRule>, never, R>\n /** The principal's fields as row guards' inputs; a visitor has none. */\n readonly inputOf: (principal: Option.Option<User>) => Readonly<Record<string, unknown>>\n /**\n * Who the principal is: `declare`'s `key`, the same function as `G.key`,\n * here for a server seam that holds the Policy and not the set. Not\n * `keyOf`, which names a principal by every field, for sharing re-reads.\n */\n readonly key: (user: User) => string\n /**\n * Who is asking, as the rules see it: every field of the principal, encoded,\n * a visitor included. Two requests by one person with the same claims answer\n * alike, so a live hub shares their re-reads; a changed claim is not shared.\n *\n * ```ts\n * RemoteServer.liveHub(sources, { key: Policy.keyOf })\n * ```\n */\n readonly keyOf: (principal: Option.Option<User>) => string\n /**\n * Whether `value` is this set's principal, an `Option` of its schema: for a\n * seam that is handed the principal untyped.\n */\n readonly isPrincipal: (value: unknown) => value is Option.Option<User>\n /**\n * This Policy with services its bodies need provided, such as a membership\n * lookup. The read seams (`GuardDrizzle.visible`, `GuardServer.memory`,\n * `GuardSync`) take a Policy that needs nothing more: a read rule runs inside\n * a read whose requirements are its Source's. Provide what stays put here,\n * once; carry what changes per request in the principal. A seam built from\n * the result counts as built from this Policy: `validate` checks the rules,\n * not the services given them. `GuardSync.authorize` runs bodies\n * synchronously, so what it is given must answer without suspending.\n *\n * ```ts\n * const ReadPolicy = Policy.provide(Context.make(Memberships, memberships))\n * ```\n */\n readonly provide: <Provided extends R>(\n context: Context.Context<Provided>,\n ) => Policy<User, Exclude<R, Provided>>\n}\n\n/** `policy` with `context` provided to every body it runs. */\nconst provided = <User, R, Provided extends R>(\n policy: Policy<User, R>,\n context: Context.Context<Provided>,\n): Policy<User, Exclude<R, Provided>> => {\n const run = <A>(effect: Effect.Effect<A, never, R>) => Effect.provide(effect, context)\n const next: Policy<User, Exclude<R, Provided>> = {\n ...policy,\n decide: (guard, request) => run(policy.decide(guard, request)),\n readable: (entity, principal) => run(policy.readable(entity, principal)),\n readMembers: (entity, principal, members) =>\n run(policy.readMembers(entity, principal, members)),\n writable: (entity, principal, interaction) =>\n run(policy.writable(entity, principal, interaction)),\n writeMembers: (entity, principal, members, interaction) =>\n run(policy.writeMembers(entity, principal, members, interaction)),\n linkable: (entity, principal, relation, interaction) =>\n run(policy.linkable(entity, principal, relation, interaction)),\n provide: more => provided(next, more),\n }\n return providedFrom(next, policy)\n}\n\n/** The builders a guard set's declaration is given, typed by its principal. */\nexport interface Builders<User> {\n /** A guard decided from the principal alone, by a body only the server has. */\n readonly principal: () => PrincipalSpec\n /** A guard over `entity`'s rows: a predicate with the principal's fields as inputs. */\n readonly row: <E extends AnyEntity>(\n entity: E,\n body: (principal: Placeholders<User>) => Predicate,\n ) => RowSpec<E>\n}\n\nconst placeholdersOf = <User>(fields: Schema.Struct.Fields): Placeholders<User> => {\n const inputs: Record<string, InputExpr<unknown>> = {}\n for (const key of Object.keys(fields)) {\n inputs[key] = Expr.input(\n `principal.${key}`,\n fields[key] as unknown as Schema.Codec<unknown, unknown>,\n )\n }\n return Object.freeze(inputs) as Placeholders<User>\n}\n\nexport { Condition, type MemberRead, type RowRule } from './condition.js'\nexport { May, MaySchema, type MayAnswer } from './may.js'\nexport { ME, type MeEntity } from './me.js'\nexport {\n Interaction,\n type All,\n type AnyRule,\n type Attach,\n type Attachment,\n type Deny,\n type Explain,\n type Inherit,\n type InteractionKey,\n type On,\n type Redact,\n type RuleFor,\n type Surface,\n} from './attach.js'\n\nexport const Guards = {\n ...Attaching,\n /**\n * Adds the `may` member, the server's answer to what a principal may do\n * with a row, after its guards are attached:\n * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`.\n */\n may: May.member,\n /**\n * `Me`, the visitor as an Entity: one row, `me`, that everyone reads and no\n * one writes, with `signedIn`, the principal's `key`, and `may` for the\n * interactions named here. Serve it with `GuardServer.me`.\n *\n * ```ts\n * export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })\n * ```\n */\n me,\n /**\n * One application's guards, under `name` (its principal's Context key, and\n * what the matrix prints). `principal` is a `Schema.Struct`: its fields are\n * what a row guard reads, and its codec encodes a principal's values as\n * stored values are encoded.\n *\n * ```ts\n * const G = Guards.declare('Todos', User, guard => ({\n * isAdmin: guard.principal(),\n * isOwner: guard.row(TodoFields, p => Expr.eq(TodoFields.fields.ownerId, p.id)),\n * }), { key: user => user.id })\n * ```\n */\n declare: <\n const Name extends string,\n Fields extends Schema.Struct.Fields,\n const S extends Readonly<Record<string, AnySpec>> & { readonly [K in Reserved]?: never },\n >(\n name: Name,\n principal: Schema.Struct<Fields>,\n build: (guard: Builders<Schema.Struct.Type<Fields>>) => S,\n options: {\n readonly key: (user: Schema.Struct.Type<Fields>) => string\n /**\n * What a surface of a guarded Entity with no rules decides: `'deny'`\n * refuses it, `'allow'` lets everyone. Required, so an open surface is\n * a decision written down; `Guards.matrix` prints it `closed` or `open`.\n */\n readonly unguarded: 'allow' | 'deny'\n },\n ): GuardSet<Name, Schema.Struct.Type<Fields>, S> => {\n type User = Schema.Struct.Type<Fields>\n // The type requires it; a caller without types (or one that spelled it\n // `'Allow'`) would otherwise get a set that denies, silently.\n if (options.unguarded !== 'allow' && options.unguarded !== 'deny')\n throw new Error(\n `[foldkit-guard] ${name}: unguarded must be 'allow' or 'deny', not ${JSON.stringify(options.unguarded)}`,\n )\n const placeholders = placeholdersOf<User>(principal.fields)\n const specs = build({\n principal: () => Object.freeze({ _tag: 'PrincipalSpec' }),\n row: (entity, body) => Object.freeze({ _tag: 'RowSpec', entity, body: body(placeholders) }),\n })\n const guards: Record<string, AnyGuard<User>> = Object.create(null)\n for (const [guard, spec] of Object.entries(specs)) {\n if ((reserved as ReadonlyArray<string>).includes(guard)) {\n throw new Error(\n `[foldkit-guard] ${name}: \"${guard}\" is a name the guard set keeps for itself`,\n )\n }\n guards[guard] = Match.valueTags(spec, {\n PrincipalSpec: (): AnyGuard<User> =>\n Object.freeze({ _tag: 'PrincipalGuard', name: guard, set: name }),\n RowSpec: ({ entity, body }): AnyGuard<User> =>\n Object.freeze({\n _tag: 'RowGuard',\n name: guard,\n set: name,\n entity,\n body,\n // Checks the body reads only this Entity's fields, where it is declared.\n query: Query.from(entity).pipe(Query.where(body)),\n }),\n })\n }\n const principalNames = Object.keys(guards).filter(\n guard => guards[guard]!._tag === 'PrincipalGuard',\n )\n const encoders = Object.fromEntries(\n Object.entries(principal.fields).map(([field, schema]) => [\n field,\n Schema.encodeSync(schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n )\n const inputOf = (user: User): Readonly<Record<string, unknown>> => {\n const input: Record<string, unknown> = {}\n for (const [field, encode] of Object.entries(encoders)) {\n input[`principal.${field}`] = encode((user as Record<string, unknown>)[field])\n }\n return input\n }\n\n const isPrincipal = Schema.is(Schema.Option(principal))\n // Every claim as JSON keeps it, a set, a number past JSON's or a date\n // included: two principals that differ in one never share a key.\n const asJson = Schema.encodeSync(\n Schema.toCodecJson(principal) as unknown as Schema.Codec<unknown, unknown>,\n )\n\n const implement = <R>(bodies: Readonly<Record<string, Body<User, R>>>): Policy<User, R> => {\n const missing = principalNames.filter(guard => !Object.hasOwn(bodies, guard))\n const extra = Object.keys(bodies).filter(guard => !principalNames.includes(guard))\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `[foldkit-guard] ${name}.implement: ${[\n missing.length > 0 ? `no body for ${missing.join(', ')}` : '',\n extra.length > 0 ? `${extra.join(', ')} is not a principal guard` : '',\n ]\n .filter(part => part !== '')\n .join('; ')}`,\n )\n }\n const decide: Policy<User, R>['decide'] = (guard, { principal, interaction, row }) => {\n if (guard.set !== name) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: \"${guard.name}\" belongs to ${guard.set}`),\n )\n }\n return Match.valueTags(guard, {\n PrincipalGuard: ({ name: body }) => {\n const decided = bodies[body]!(principal, { interaction })\n return Effect.isEffect(decided) ? decided : Effect.succeed(decided)\n },\n RowGuard: rowGuard =>\n Effect.succeed(\n row !== undefined &&\n Option.match(principal, {\n // A visitor has no fields: only a guard over the row alone can hold.\n onNone: () =>\n !readsPrincipal(rowGuard) && evaluate(rowGuard.query, {}, [row]).length === 1,\n onSome: user => evaluate(rowGuard.query, inputOf(user), [row]).length === 1,\n }),\n ),\n })\n }\n const decidingFor = (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: string,\n ) => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== name) {\n throw new Error(`[foldkit-guard] ${name}: ${entity.name} carries the guards of ${set}`)\n }\n })\n return deciding(\n guard =>\n Effect.map(decide(guard, { principal, interaction }), decision => decision === true),\n Option.isNone(principal),\n interaction,\n )\n }\n const policy: Policy<User, R> = {\n set: name,\n decide,\n readable: (entity, principal) =>\n Effect.map(\n decidingFor(entity, principal, 'Read').row(entity),\n ({ condition }) => condition,\n ),\n readMembers: (entity, principal, members) =>\n decidingFor(entity, principal, 'Read').members(entity, members),\n writable: (entity, principal, interaction) =>\n decidingFor(entity, principal, interaction).row(entity),\n writeMembers: (entity, principal, members, interaction) =>\n decidingFor(entity, principal, interaction).members(entity, members),\n linkable: (entity, principal, relation, interaction) =>\n decidingFor(entity, principal, interaction).relation(entity, relation),\n inputOf: principal =>\n Option.match(principal, { onNone: () => ({}), onSome: user => inputOf(user) }),\n key: options.key,\n // Prefixed, so no user's key is the visitor's. Not `declare`'s `key`\n // alone: a re-read shared under it would read a newer request as an\n // older one's claims.\n keyOf: principal =>\n Option.match(principal, {\n onNone: () => 'visitor',\n onSome: user => `user:${JSON.stringify(asJson(user))}`,\n }),\n isPrincipal,\n provide: context => provided(policy, context),\n }\n return policy\n }\n\n return Object.freeze({\n ...guards,\n name,\n schema: principal as unknown as Schema.Codec<User, unknown>,\n Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>(\n `foldkit-guard/Principal/${name}`,\n ),\n key: options.key,\n unguarded: options.unguarded,\n inputOf,\n implement,\n }) as unknown as GuardSet<Name, User, S>\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA6GA,MAAM,WAAW;CACf;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AA8HA,MAAM,YACJ,QACA,YACuC;CACvC,MAAM,OAAU,WAAuC,OAAO,QAAQ,QAAQ,OAAO;CACrF,MAAM,OAA2C;EAC/C,GAAG;EACH,SAAS,OAAO,YAAY,IAAI,OAAO,OAAO,OAAO,OAAO,CAAC;EAC7D,WAAW,QAAQ,cAAc,IAAI,OAAO,SAAS,QAAQ,SAAS,CAAC;EACvE,cAAc,QAAQ,WAAW,YAC/B,IAAI,OAAO,YAAY,QAAQ,WAAW,OAAO,CAAC;EACpD,WAAW,QAAQ,WAAW,gBAC5B,IAAI,OAAO,SAAS,QAAQ,WAAW,WAAW,CAAC;EACrD,eAAe,QAAQ,WAAW,SAAS,gBACzC,IAAI,OAAO,aAAa,QAAQ,WAAW,SAAS,WAAW,CAAC;EAClE,WAAW,QAAQ,WAAW,UAAU,gBACtC,IAAI,OAAO,SAAS,QAAQ,WAAW,UAAU,WAAW,CAAC;EAC/D,UAAS,SAAQ,SAAS,MAAM,IAAI;CACtC;CACA,OAAO,aAAa,MAAM,MAAM;AAClC;AAaA,MAAM,kBAAwB,WAAqD;CACjF,MAAM,SAA6C,CAAC;CACpD,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAClC,OAAO,OAAO,KAAK,MACjB,aAAa,OACb,OAAO,IACT;CAEF,OAAO,OAAO,OAAO,MAAM;AAC7B;AAqBA,MAAa,SAAS;CACpB,GAAG;;;;;;CAMH,KAAK,IAAI;;;;;;;;;;CAUT;;;;;;;;;;;;;;CAcA,UAKE,MACA,WACA,OACA,YASkD;EAIlD,IAAI,QAAQ,cAAc,WAAW,QAAQ,cAAc,QACzD,MAAM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
1
|
+
{"version":3,"file":"index.mjs","names":[],"sources":["../src/index.ts"],"sourcesContent":["/**\n * Who may do what, declared once on the domain.\n *\n * A guard set names its guards once, in shared code the client imports too.\n * A **principal guard** is declared by name and implemented only on the\n * server (`G.implement`), so its logic never ships. A **row guard** is an\n * `Expr` over one Entity's fields with the principal's fields as inputs: data,\n * which the SQL compiler and `evaluate` both run. See `guard-DESIGN.md`.\n */\nimport { Context, Effect, Match, Option, Schema } from 'effect'\nimport { Attaching, attached, type InteractionKey } from './attach.js'\nimport {\n deciding,\n readsPrincipal,\n type Condition,\n type MemberRead,\n type RowRule,\n} from './condition.js'\nimport { May } from './may.js'\nimport { me } from './me.js'\nimport { providedFrom } from './origin.js'\nimport {\n Expr,\n Operators,\n Query,\n evaluate,\n type AnyEntity,\n type MemoryOperators,\n type AnyQuery,\n type InputExpr,\n type Predicate,\n} from 'foldkit-entity'\n\n/** A guard's answer: allowed, refused, or refused with a sentence the caller may read. */\nexport type Decision = boolean | { readonly allowed: false; readonly reason: string }\n\n/** What a principal guard is asked about. */\nexport interface About {\n /** The interaction attempted: `Read`, `Update`, or one the application names. */\n readonly interaction: string\n}\n\n/**\n * The principal's fields as a row guard's body sees them: each an input named\n * `principal.<field>`, typed as the field. A body is built once, so it holds\n * these placeholders and never a value: branching on one is a type error.\n */\nexport type Placeholders<User> = {\n readonly [K in keyof User & string]: InputExpr<User[K]>\n}\n\n/** What `guard.principal()` declares: a name whose body the server supplies. */\nexport interface PrincipalSpec {\n readonly _tag: 'PrincipalSpec'\n}\n\n/** What `guard.row(entity, body)` declares: a predicate over one Entity's rows. */\nexport interface RowSpec<E extends AnyEntity> {\n readonly _tag: 'RowSpec'\n readonly entity: E\n readonly body: Predicate\n}\n\ntype AnySpec = PrincipalSpec | RowSpec<AnyEntity>\n\n/**\n * The principal a guard is for, kept in the type so a guard of one principal\n * cannot stand where another's is wanted. A function type, so it is invariant.\n */\ninterface ForPrincipal<User> {\n readonly '~principal'?: (user: User) => User\n}\n\n/** A guard whose body lives on the server, asked of the principal alone. */\nexport interface PrincipalGuard<User, Set extends string = string> extends ForPrincipal<User> {\n readonly _tag: 'PrincipalGuard'\n readonly name: string\n /** The name of the guard set it belongs to. */\n readonly set: Set\n}\n\n/** A guard over the rows of `E`: its predicate, and the query that asks it of rows. */\nexport interface RowGuard<\n User,\n E extends AnyEntity,\n Set extends string = string,\n> extends ForPrincipal<User> {\n readonly _tag: 'RowGuard'\n readonly name: string\n readonly set: Set\n readonly entity: E\n readonly body: Predicate\n /** `from(entity).where(body)`, for an interpreter that runs queries. */\n readonly query: AnyQuery\n}\n\nexport type AnyGuard<User> = PrincipalGuard<User> | RowGuard<User, AnyEntity>\n\ntype GuardOf<User, Set extends string, S> =\n S extends RowSpec<infer E> ? RowGuard<User, E, Set> : PrincipalGuard<User, Set>\n\n/** The keys of a spec record that are principal guards: what `implement` must supply. */\ntype PrincipalKeys<S> = { [K in keyof S]: S[K] extends PrincipalSpec ? K : never }[keyof S]\n\n/** A principal guard's body, on the server. */\nexport type Body<User, R = never> = (\n principal: Option.Option<User>,\n about: About,\n) => Decision | Effect.Effect<Decision, never, R>\n\n/** Names a guard set reserves for itself, which no guard may take. */\nconst reserved = [\n 'name',\n 'schema',\n 'Principal',\n 'key',\n 'unguarded',\n 'inputOf',\n 'implement',\n] as const\ntype Reserved = (typeof reserved)[number]\n\n/** Who is asking, for one guard set: a visitor is `none`. */\nexport interface PrincipalOf<Name extends string> {\n readonly '~guardSet': Name\n}\n\n/** The guard set of one application, as `Guards.declare` returns it. */\nexport type GuardSet<Name extends string, User, S> = {\n readonly [K in keyof S]: GuardOf<User, Name, S[K]>\n} & {\n readonly name: Name\n /** The principal's schema, whose fields the row guards read. */\n readonly schema: Schema.Codec<User, unknown>\n /** The server's Context key for who is asking. Authentication provides it. */\n readonly Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>\n /** A stable name for the person, whatever their claims: for what is theirs, as a cache's scope. */\n readonly key: (user: User) => string\n readonly unguarded: 'allow' | 'deny'\n /** The principal's fields as row guards' inputs, encoded as stored values are. */\n readonly inputOf: (user: User) => Readonly<Record<string, unknown>>\n /**\n * The bodies of the principal guards: every one, and nothing else. `operators`\n * runs the row guards' primitive operators in memory; `Operators.kernel` when\n * not given.\n */\n readonly implement: <R = never>(\n bodies: { readonly [K in PrincipalKeys<S>]: Body<User, R> },\n options?: { readonly operators?: MemoryOperators | undefined },\n ) => Policy<User, R>\n}\n\n/** The server's half of a guard set: every principal guard's body. */\nexport interface Policy<User, R = never> {\n readonly set: string\n /**\n * How a row guard's primitive operators are run in memory: by `decide`,\n * `Condition.holds` and every guarded server judging a row. Given to\n * `implement`; `Operators.kernel` when not.\n */\n readonly operators: MemoryOperators\n /**\n * Whether `guard` allows `principal`, for a row guard over `row` (its stored,\n * encoded values). A visitor passes no row guard that reads a principal's\n * fields; one over the row alone holds for a visitor too.\n */\n readonly decide: (\n guard: AnyGuard<User>,\n request: {\n readonly principal: Option.Option<User>\n readonly interaction: string\n readonly row?: Readonly<Record<string, unknown>> | undefined\n },\n ) => Effect.Effect<Decision, never, R>\n /**\n * Which rows of `entity` `principal` may read, as a condition over the row\n * with every principal guard already decided. An Entity without guards, or\n * of no set, reads `Always`.\n */\n readonly readable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n ) => Effect.Effect<Condition, never, R>\n /** The read rule of each of `members`, relations included, that has one, decided for `principal`. */\n readonly readMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /**\n * Which rows of `entity` `principal` may write by `interaction` (`Create`,\n * `Update`, `Delete`, or one the application named), as a condition over\n * the row, and what a refusal shows.\n */\n readonly writable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: 'Create' | 'Update' | 'Delete' | InteractionKey,\n ) => Effect.Effect<RowRule, never, R>\n /** The rule of each of `members` that has one for setting it, decided for `principal`. */\n readonly writeMembers: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n members: ReadonlyArray<string>,\n interaction: 'Create' | 'Update',\n ) => Effect.Effect<ReadonlyArray<MemberRead>, never, R>\n /** A relation's rule for linking or unlinking a row, when it has one. */\n readonly linkable: (\n entity: AnyEntity,\n principal: Option.Option<User>,\n relation: string,\n interaction: 'Link' | 'Unlink',\n ) => Effect.Effect<Option.Option<RowRule>, never, R>\n /** The principal's fields as row guards' inputs; a visitor has none. */\n readonly inputOf: (principal: Option.Option<User>) => Readonly<Record<string, unknown>>\n /**\n * Who the principal is: `declare`'s `key`, the same function as `G.key`,\n * here for a server seam that holds the Policy and not the set. Not\n * `keyOf`, which names a principal by every field, for sharing re-reads.\n */\n readonly key: (user: User) => string\n /**\n * Who is asking, as the rules see it: every field of the principal, encoded,\n * a visitor included. Two requests by one person with the same claims answer\n * alike, so a live hub shares their re-reads; a changed claim is not shared.\n *\n * ```ts\n * RemoteServer.liveHub(sources, { key: Policy.keyOf })\n * ```\n */\n readonly keyOf: (principal: Option.Option<User>) => string\n /**\n * Whether `value` is this set's principal, an `Option` of its schema: for a\n * seam that is handed the principal untyped.\n */\n readonly isPrincipal: (value: unknown) => value is Option.Option<User>\n /**\n * This Policy with services its bodies need provided, such as a membership\n * lookup. The read seams (`GuardDrizzle.visible`, `GuardServer.memory`,\n * `GuardSync`) take a Policy that needs nothing more: a read rule runs inside\n * a read whose requirements are its Source's. Provide what stays put here,\n * once; carry what changes per request in the principal. A seam built from\n * the result counts as built from this Policy: `validate` checks the rules,\n * not the services given them. `GuardSync.authorize` runs bodies\n * synchronously, so what it is given must answer without suspending.\n *\n * ```ts\n * const ReadPolicy = Policy.provide(Context.make(Memberships, memberships))\n * ```\n */\n readonly provide: <Provided extends R>(\n context: Context.Context<Provided>,\n ) => Policy<User, Exclude<R, Provided>>\n}\n\n/** `policy` with `context` provided to every body it runs. */\nconst provided = <User, R, Provided extends R>(\n policy: Policy<User, R>,\n context: Context.Context<Provided>,\n): Policy<User, Exclude<R, Provided>> => {\n const run = <A>(effect: Effect.Effect<A, never, R>) => Effect.provide(effect, context)\n const next: Policy<User, Exclude<R, Provided>> = {\n ...policy,\n decide: (guard, request) => run(policy.decide(guard, request)),\n readable: (entity, principal) => run(policy.readable(entity, principal)),\n readMembers: (entity, principal, members) =>\n run(policy.readMembers(entity, principal, members)),\n writable: (entity, principal, interaction) =>\n run(policy.writable(entity, principal, interaction)),\n writeMembers: (entity, principal, members, interaction) =>\n run(policy.writeMembers(entity, principal, members, interaction)),\n linkable: (entity, principal, relation, interaction) =>\n run(policy.linkable(entity, principal, relation, interaction)),\n provide: more => provided(next, more),\n }\n return providedFrom(next, policy)\n}\n\n/** The builders a guard set's declaration is given, typed by its principal. */\nexport interface Builders<User> {\n /** A guard decided from the principal alone, by a body only the server has. */\n readonly principal: () => PrincipalSpec\n /** A guard over `entity`'s rows: a predicate with the principal's fields as inputs. */\n readonly row: <E extends AnyEntity>(\n entity: E,\n body: (principal: Placeholders<User>) => Predicate,\n ) => RowSpec<E>\n}\n\nconst placeholdersOf = <User>(fields: Schema.Struct.Fields): Placeholders<User> => {\n const inputs: Record<string, InputExpr<unknown>> = {}\n for (const key of Object.keys(fields)) {\n inputs[key] = Expr.input(\n `principal.${key}`,\n fields[key] as unknown as Schema.Codec<unknown, unknown>,\n )\n }\n return Object.freeze(inputs) as Placeholders<User>\n}\n\nexport { Condition, type MemberRead, type RowRule } from './condition.js'\nexport { May, MaySchema, type MayAnswer } from './may.js'\nexport { ME, type MeEntity } from './me.js'\nexport {\n Interaction,\n type All,\n type AnyRule,\n type Attach,\n type Attachment,\n type Deny,\n type Explain,\n type Inherit,\n type InteractionKey,\n type On,\n type Redact,\n type RuleFor,\n type Surface,\n} from './attach.js'\n\nexport const Guards = {\n ...Attaching,\n /**\n * Adds the `may` member, the server's answer to what a principal may do\n * with a row, after its guards are attached:\n * `TodoFields.pipe(Guards.attach(G, { … }), Guards.may)`.\n */\n may: May.member,\n /**\n * `Me`, the visitor as an Entity: one row, `me`, that everyone reads and no\n * one writes, with `signedIn`, the principal's `key`, and `may` for the\n * interactions named here. Serve it with `GuardServer.me`.\n *\n * ```ts\n * export const Me = Guards.me(G, { interactions: { [OpenAdmin.key]: [G.isAdmin] } })\n * ```\n */\n me,\n /**\n * One application's guards, under `name` (its principal's Context key, and\n * what the matrix prints). `principal` is a `Schema.Struct`: its fields are\n * what a row guard reads, and its codec encodes a principal's values as\n * stored values are encoded.\n *\n * ```ts\n * const G = Guards.declare('Todos', User, guard => ({\n * isAdmin: guard.principal(),\n * isOwner: guard.row(TodoFields, p => Expr.eq(TodoFields.fields.ownerId, p.id)),\n * }), { key: user => user.id })\n * ```\n */\n declare: <\n const Name extends string,\n Fields extends Schema.Struct.Fields,\n const S extends Readonly<Record<string, AnySpec>> & { readonly [K in Reserved]?: never },\n >(\n name: Name,\n principal: Schema.Struct<Fields>,\n build: (guard: Builders<Schema.Struct.Type<Fields>>) => S,\n options: {\n readonly key: (user: Schema.Struct.Type<Fields>) => string\n /**\n * What a surface of a guarded Entity with no rules decides: `'deny'`\n * refuses it, `'allow'` lets everyone. Required, so an open surface is\n * a decision written down; `Guards.matrix` prints it `closed` or `open`.\n */\n readonly unguarded: 'allow' | 'deny'\n },\n ): GuardSet<Name, Schema.Struct.Type<Fields>, S> => {\n type User = Schema.Struct.Type<Fields>\n // The type requires it; a caller without types (or one that spelled it\n // `'Allow'`) would otherwise get a set that denies, silently.\n if (options.unguarded !== 'allow' && options.unguarded !== 'deny')\n throw new Error(\n `[foldkit-guard] ${name}: unguarded must be 'allow' or 'deny', not ${JSON.stringify(options.unguarded)}`,\n )\n const placeholders = placeholdersOf<User>(principal.fields)\n const specs = build({\n principal: () => Object.freeze({ _tag: 'PrincipalSpec' }),\n row: (entity, body) => Object.freeze({ _tag: 'RowSpec', entity, body: body(placeholders) }),\n })\n const guards: Record<string, AnyGuard<User>> = Object.create(null)\n for (const [guard, spec] of Object.entries(specs)) {\n if ((reserved as ReadonlyArray<string>).includes(guard)) {\n throw new Error(\n `[foldkit-guard] ${name}: \"${guard}\" is a name the guard set keeps for itself`,\n )\n }\n guards[guard] = Match.valueTags(spec, {\n PrincipalSpec: (): AnyGuard<User> =>\n Object.freeze({ _tag: 'PrincipalGuard', name: guard, set: name }),\n RowSpec: ({ entity, body }): AnyGuard<User> =>\n Object.freeze({\n _tag: 'RowGuard',\n name: guard,\n set: name,\n entity,\n body,\n // Checks the body reads only this Entity's fields, where it is declared.\n query: Query.from(entity).pipe(Query.where(body)),\n }),\n })\n }\n const principalNames = Object.keys(guards).filter(\n guard => guards[guard]!._tag === 'PrincipalGuard',\n )\n const encoders = Object.fromEntries(\n Object.entries(principal.fields).map(([field, schema]) => [\n field,\n Schema.encodeSync(schema as unknown as Schema.Codec<unknown, unknown>),\n ]),\n )\n const inputOf = (user: User): Readonly<Record<string, unknown>> => {\n const input: Record<string, unknown> = {}\n for (const [field, encode] of Object.entries(encoders)) {\n input[`principal.${field}`] = encode((user as Record<string, unknown>)[field])\n }\n return input\n }\n\n const isPrincipal = Schema.is(Schema.Option(principal))\n // Every claim as JSON keeps it, a set, a number past JSON's or a date\n // included: two principals that differ in one never share a key.\n const asJson = Schema.encodeSync(\n Schema.toCodecJson(principal) as unknown as Schema.Codec<unknown, unknown>,\n )\n\n const implement = <R>(\n bodies: Readonly<Record<string, Body<User, R>>>,\n implementation: { readonly operators?: MemoryOperators | undefined } = {},\n ): Policy<User, R> => {\n const operators = implementation.operators ?? Operators.kernel\n const missing = principalNames.filter(guard => !Object.hasOwn(bodies, guard))\n const extra = Object.keys(bodies).filter(guard => !principalNames.includes(guard))\n if (missing.length > 0 || extra.length > 0) {\n throw new Error(\n `[foldkit-guard] ${name}.implement: ${[\n missing.length > 0 ? `no body for ${missing.join(', ')}` : '',\n extra.length > 0 ? `${extra.join(', ')} is not a principal guard` : '',\n ]\n .filter(part => part !== '')\n .join('; ')}`,\n )\n }\n const decide: Policy<User, R>['decide'] = (guard, { principal, interaction, row }) => {\n if (guard.set !== name) {\n return Effect.die(\n new Error(`[foldkit-guard] ${name}: \"${guard.name}\" belongs to ${guard.set}`),\n )\n }\n return Match.valueTags(guard, {\n PrincipalGuard: ({ name: body }) => {\n const decided = bodies[body]!(principal, { interaction })\n return Effect.isEffect(decided) ? decided : Effect.succeed(decided)\n },\n RowGuard: rowGuard =>\n Effect.succeed(\n row !== undefined &&\n Option.match(principal, {\n // A visitor has no fields: only a guard over the row alone can hold.\n onNone: () =>\n !readsPrincipal(rowGuard) &&\n evaluate(rowGuard.query, {}, [row], { operators }).length === 1,\n onSome: user =>\n evaluate(rowGuard.query, inputOf(user), [row], { operators }).length === 1,\n }),\n ),\n })\n }\n const decidingFor = (\n entity: AnyEntity,\n principal: Option.Option<User>,\n interaction: string,\n ) => {\n Option.map(attached(entity), ({ set }) => {\n if (set !== name) {\n throw new Error(`[foldkit-guard] ${name}: ${entity.name} carries the guards of ${set}`)\n }\n })\n return deciding(\n guard =>\n Effect.map(decide(guard, { principal, interaction }), decision => decision === true),\n Option.isNone(principal),\n interaction,\n )\n }\n const policy: Policy<User, R> = {\n set: name,\n operators,\n decide,\n readable: (entity, principal) =>\n Effect.map(\n decidingFor(entity, principal, 'Read').row(entity),\n ({ condition }) => condition,\n ),\n readMembers: (entity, principal, members) =>\n decidingFor(entity, principal, 'Read').members(entity, members),\n writable: (entity, principal, interaction) =>\n decidingFor(entity, principal, interaction).row(entity),\n writeMembers: (entity, principal, members, interaction) =>\n decidingFor(entity, principal, interaction).members(entity, members),\n linkable: (entity, principal, relation, interaction) =>\n decidingFor(entity, principal, interaction).relation(entity, relation),\n inputOf: principal =>\n Option.match(principal, { onNone: () => ({}), onSome: user => inputOf(user) }),\n key: options.key,\n // Prefixed, so no user's key is the visitor's. Not `declare`'s `key`\n // alone: a re-read shared under it would read a newer request as an\n // older one's claims.\n keyOf: principal =>\n Option.match(principal, {\n onNone: () => 'visitor',\n onSome: user => `user:${JSON.stringify(asJson(user))}`,\n }),\n isPrincipal,\n provide: context => provided(policy, context),\n }\n return policy\n }\n\n return Object.freeze({\n ...guards,\n name,\n schema: principal as unknown as Schema.Codec<User, unknown>,\n Principal: Context.Service<PrincipalOf<Name>, Option.Option<User>>(\n `foldkit-guard/Principal/${name}`,\n ),\n key: options.key,\n unguarded: options.unguarded,\n inputOf,\n implement,\n }) as unknown as GuardSet<Name, User, S>\n },\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AA+GA,MAAM,WAAW;CACf;CACA;CACA;CACA;CACA;CACA;CACA;AACF;;AAyIA,MAAM,YACJ,QACA,YACuC;CACvC,MAAM,OAAU,WAAuC,OAAO,QAAQ,QAAQ,OAAO;CACrF,MAAM,OAA2C;EAC/C,GAAG;EACH,SAAS,OAAO,YAAY,IAAI,OAAO,OAAO,OAAO,OAAO,CAAC;EAC7D,WAAW,QAAQ,cAAc,IAAI,OAAO,SAAS,QAAQ,SAAS,CAAC;EACvE,cAAc,QAAQ,WAAW,YAC/B,IAAI,OAAO,YAAY,QAAQ,WAAW,OAAO,CAAC;EACpD,WAAW,QAAQ,WAAW,gBAC5B,IAAI,OAAO,SAAS,QAAQ,WAAW,WAAW,CAAC;EACrD,eAAe,QAAQ,WAAW,SAAS,gBACzC,IAAI,OAAO,aAAa,QAAQ,WAAW,SAAS,WAAW,CAAC;EAClE,WAAW,QAAQ,WAAW,UAAU,gBACtC,IAAI,OAAO,SAAS,QAAQ,WAAW,UAAU,WAAW,CAAC;EAC/D,UAAS,SAAQ,SAAS,MAAM,IAAI;CACtC;CACA,OAAO,aAAa,MAAM,MAAM;AAClC;AAaA,MAAM,kBAAwB,WAAqD;CACjF,MAAM,SAA6C,CAAC;CACpD,KAAK,MAAM,OAAO,OAAO,KAAK,MAAM,GAClC,OAAO,OAAO,KAAK,MACjB,aAAa,OACb,OAAO,IACT;CAEF,OAAO,OAAO,OAAO,MAAM;AAC7B;AAqBA,MAAa,SAAS;CACpB,GAAG;;;;;;CAMH,KAAK,IAAI;;;;;;;;;;CAUT;;;;;;;;;;;;;;CAcA,UAKE,MACA,WACA,O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O,OAAO,OAAO;GACnB,GAAG;GACH;GACA,QAAQ;GACR,WAAW,QAAQ,QACjB,2BAA2B,MAC7B;GACA,KAAK,QAAQ;GACb,WAAW,QAAQ;GACnB;GACA;EACF,CAAC;CACH;AACF"}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { Record, Schema } from "effect";
|
|
2
2
|
import { Derived, Entity } from "foldkit-entity";
|
|
3
|
-
|
|
3
|
+
// src/may.ts
|
|
4
4
|
/**
|
|
5
5
|
* `may`: what the server says a principal may do with a row, as a derived
|
|
6
6
|
* member the client reads like any other. The client never runs a rule; this
|
|
@@ -70,7 +70,6 @@ const May = {
|
|
|
70
70
|
}
|
|
71
71
|
})
|
|
72
72
|
};
|
|
73
|
-
//#endregion
|
|
74
73
|
export { MaySchema as n, May as t };
|
|
75
74
|
|
|
76
|
-
//# sourceMappingURL=may-
|
|
75
|
+
//# sourceMappingURL=may-DzCAt_5M.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"may-
|
|
1
|
+
{"version":3,"file":"may-DzCAt_5M.mjs","names":[],"sources":["../src/may.ts"],"sourcesContent":["/**\n * `may`: what the server says a principal may do with a row, as a derived\n * member the client reads like any other. The client never runs a rule; this\n * is the server's answer for the row as it was read, a hint for a greyed-out\n * button, never the check (the write is checked again when it is made).\n */\nimport { Option, Record, Schema } from 'effect'\nimport { Derived, Entity, type AnyEntity } from 'foldkit-entity'\nimport type { InteractionKey } from './attach.js'\n\n/**\n * The answer: per row interaction (`Update`, `Delete`, and each one the\n * application named), per member with its own `Update` rule, and per relation\n * with a `Link` or `Unlink` rule; and, for a row interaction refused with an\n * `explain`, its sentence.\n */\nexport const MaySchema = Schema.Struct({\n row: Schema.Record(Schema.String, Schema.Boolean),\n reasons: Schema.Record(Schema.String, Schema.String),\n members: Schema.Record(Schema.String, Schema.Boolean),\n relations: Schema.Record(\n Schema.String,\n Schema.Struct({ Link: Schema.Boolean, Unlink: Schema.Boolean }),\n ),\n})\nexport type MayAnswer = typeof MaySchema.Type\n\ntype MemberKeys<E extends AnyEntity> = (keyof E['fields'] | keyof E['derived']) & string\n\nconst can = (may: MayAnswer, interaction: string): boolean => may.row[interaction] === true\n\n/** The row's `Update`, and the member's own rule when it has one. */\nconst setting = (may: MayAnswer, member: string): boolean =>\n can(may, 'Update') && (!Object.hasOwn(may.members, member) || may.members[member] === true)\n\n/** The row's `Update`, and the relation's own rule for the direction when it has one. */\nconst linking = (may: MayAnswer, relation: string, interaction: 'Link' | 'Unlink'): boolean =>\n can(may, 'Update') &&\n (!Object.hasOwn(may.relations, relation) || may.relations[relation]![interaction])\n\nconst isMay = Schema.is(MaySchema)\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.\n */\n member: Entity.derived({ may: Derived.make(MaySchema) }),\n\n /**\n * Whether the row's rule for `interaction` let the principal, when it was\n * read. An interaction the answer does not name was not ruled where the row\n * was read, and reads `false`: a hint errs on the side of asking.\n */\n can: (may: MayAnswer, interaction: 'Update' | 'Delete' | InteractionKey): boolean =>\n can(may, interaction),\n\n /**\n * Why the row's rule for `interaction` refused, when it was refused with an\n * `explain`: words for whoever asked. None where it was allowed (the server\n * gives none then), or refused without one.\n */\n reason: (\n may: MayAnswer,\n interaction: 'Update' | 'Delete' | InteractionKey,\n ): Option.Option<string> => Record.get(may.reasons, interaction),\n\n /** Whether the principal may set `member` on this row: the row's `Update`, and the member's own rule. */\n canSet: <E extends AnyEntity>(may: MayAnswer, _entity: E, member: MemberKeys<E>): boolean =>\n setting(may, member),\n\n /** Whether the principal may point `relation` at a row, or away from one. */\n canLink: <E extends AnyEntity>(\n may: MayAnswer,\n _entity: E,\n relation: keyof E['relations'] & string,\n interaction: 'Link' | 'Unlink',\n ): boolean => linking(may, relation, interaction),\n\n /**\n * `foldkit-crud`'s `locks` for `entity`: an editor loads `may` beside the\n * form's members and locks each the reader may not set. A relation is locked\n * unless it may be both unlinked and linked. Nothing is locked while `may`\n * is not answered (a Source without the filter): the write is checked anyway.\n *\n * ```ts\n * Crud.editor('todo', { form, mutation: EditTodo, locks: May.locks(Todo) })\n * ```\n */\n locks: (entity: AnyEntity) => ({\n select: { may: true } as const,\n locked: (row: Readonly<Record<string, unknown>>, member: string): boolean => {\n const may = row.may\n if (!isMay(may)) return false\n return Object.hasOwn(entity.relations, member)\n ? !(linking(may, member, 'Unlink') && linking(may, member, 'Link'))\n : !setting(may, member)\n },\n }),\n}\n"],"mappings":";;;;;;;;;;;;;;;AAgBA,MAAa,YAAY,OAAO,OAAO;CACrC,KAAK,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;CAChD,SAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,MAAM;CACnD,SAAS,OAAO,OAAO,OAAO,QAAQ,OAAO,OAAO;CACpD,WAAW,OAAO,OAChB,OAAO,QACP,OAAO,OAAO;EAAE,MAAM,OAAO;EAAS,QAAQ,OAAO;CAAQ,CAAC,CAChE;AACF,CAAC;AAKD,MAAM,OAAO,KAAgB,gBAAiC,IAAI,IAAI,iBAAiB;;AAGvF,MAAM,WAAW,KAAgB,WAC/B,IAAI,KAAK,QAAQ,MAAM,CAAC,OAAO,OAAO,IAAI,SAAS,MAAM,KAAK,IAAI,QAAQ,YAAY;;AAGxF,MAAM,WAAW,KAAgB,UAAkB,gBACjD,IAAI,KAAK,QAAQ,MAChB,CAAC,OAAO,OAAO,IAAI,WAAW,QAAQ,KAAK,IAAI,UAAU,SAAS,CAAE;AAEvE,MAAM,QAAQ,OAAO,GAAG,SAAS;AAEjC,MAAa,MAAM;;;;;;CAMjB,QAAQ,OAAO,QAAQ,EAAE,KAAK,QAAQ,KAAK,SAAS,EAAE,CAAC;;;;;;CAOvD,MAAM,KAAgB,gBACpB,IAAI,KAAK,WAAW;;;;;;CAOtB,SACE,KACA,gBAC0B,OAAO,IAAI,IAAI,SAAS,WAAW;;CAG/D,SAA8B,KAAgB,SAAY,WACxD,QAAQ,KAAK,MAAM;;CAGrB,UACE,KACA,SACA,UACA,gBACY,QAAQ,KAAK,UAAU,WAAW;;;;;;;;;;;CAYhD,QAAQ,YAAuB;EAC7B,QAAQ,EAAE,KAAK,KAAK;EACpB,SAAS,KAAwC,WAA4B;GAC3E,MAAM,MAAM,IAAI;GAChB,IAAI,CAAC,MAAM,GAAG,GAAG,OAAO;GACxB,OAAO,OAAO,OAAO,OAAO,WAAW,MAAM,IACzC,EAAE,QAAQ,KAAK,QAAQ,QAAQ,KAAK,QAAQ,KAAK,QAAQ,MAAM,KAC/D,CAAC,QAAQ,KAAK,MAAM;EAC1B;CACF;AACF"}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { t as Attaching } from "./attach-
|
|
2
|
-
import { t as May } from "./may-
|
|
1
|
+
import { t as Attaching } from "./attach-CRCF5XHS.mjs";
|
|
2
|
+
import { t as May } from "./may-DzCAt_5M.mjs";
|
|
3
3
|
import { Schema } from "effect";
|
|
4
4
|
import { Entity } from "foldkit-entity";
|
|
5
|
-
|
|
5
|
+
// src/me.ts
|
|
6
6
|
/**
|
|
7
7
|
* The visitor as an Entity: one row, `me`, answered for whoever asks. What a
|
|
8
8
|
* client knows about itself (signed in, as whom, what it may open) is read
|
|
@@ -34,7 +34,6 @@ const me = (G, options = {}) => MeFields.pipe(Attaching.attach(G, {
|
|
|
34
34
|
},
|
|
35
35
|
...options.interactions === void 0 ? {} : { interactions: options.interactions }
|
|
36
36
|
}), May.member);
|
|
37
|
-
//#endregion
|
|
38
37
|
export { me as n, ME as t };
|
|
39
38
|
|
|
40
|
-
//# sourceMappingURL=me-
|
|
39
|
+
//# sourceMappingURL=me-BYpuVqJE.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"me-
|
|
1
|
+
{"version":3,"file":"me-BYpuVqJE.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,7 +1,6 @@
|
|
|
1
|
-
import { C as PrincipalGuard, S as Policy } from "./attach-
|
|
1
|
+
import { C as PrincipalGuard, S as Policy } from "./attach-BepaL930.mjs";
|
|
2
2
|
import { Effect, Layer, Option } from "effect";
|
|
3
3
|
import { UploadPolicy } from "foldkit-media/server";
|
|
4
|
-
//#region src/media.d.ts
|
|
5
4
|
export interface UploadPolicyConfig<User, E, R> {
|
|
6
5
|
/**
|
|
7
6
|
* Who is asking, from a request holding the upload's URL, method and
|
|
@@ -25,6 +24,5 @@ declare const uploadPolicy: <User, E, R>(policy: Policy<User>, config: UploadPol
|
|
|
25
24
|
export declare const GuardMedia: {
|
|
26
25
|
readonly uploadPolicy: typeof uploadPolicy;
|
|
27
26
|
};
|
|
28
|
-
//#endregion
|
|
29
27
|
export {};
|
|
30
28
|
//# sourceMappingURL=media.d.mts.map
|
package/dist/media.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"media.d.mts","names":[],"sources":["../src/media.ts"],"mappings":"
|
|
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"}
|
package/dist/media.mjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { Effect, Layer, Option } from "effect";
|
|
2
2
|
import { HttpServerRequest } from "effect/http";
|
|
3
3
|
import { UploadForbidden, UploadPolicy, UploadUnauthenticated } from "foldkit-media/server";
|
|
4
|
-
|
|
4
|
+
// src/media.ts
|
|
5
5
|
/**
|
|
6
6
|
* `foldkit-guard/media`: `foldkit-media`'s `UploadPolicy` decided by a guard
|
|
7
7
|
* set. Who is asking comes from the application's resolver, the one its
|
|
@@ -35,7 +35,6 @@ const uploadPolicy = (policy, config) => Layer.effect(UploadPolicy, Effect.map(E
|
|
|
35
35
|
return yield* new UploadForbidden({});
|
|
36
36
|
}).pipe(Effect.provideContext(context)) })));
|
|
37
37
|
const GuardMedia = { uploadPolicy };
|
|
38
|
-
//#endregion
|
|
39
38
|
export { GuardMedia };
|
|
40
39
|
|
|
41
40
|
//# sourceMappingURL=media.mjs.map
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
|
|
1
|
+
// src/origin.ts
|
|
2
2
|
const origins = /* @__PURE__ */ new WeakMap();
|
|
3
3
|
/** The Policy `G.implement` built that `policy` was provided from: itself, for one it built. */
|
|
4
4
|
const originOf = (policy) => origins.get(policy) ?? policy;
|
|
@@ -7,7 +7,6 @@ const providedFrom = (policy, from) => {
|
|
|
7
7
|
origins.set(policy, originOf(from));
|
|
8
8
|
return policy;
|
|
9
9
|
};
|
|
10
|
-
//#endregion
|
|
11
10
|
export { providedFrom as n, originOf as t };
|
|
12
11
|
|
|
13
|
-
//# sourceMappingURL=origin-
|
|
12
|
+
//# sourceMappingURL=origin-igJoiz74.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"origin-
|
|
1
|
+
{"version":3,"file":"origin-igJoiz74.mjs","names":[],"sources":["../src/origin.ts"],"sourcesContent":["/**\n * Which Policy another was provided from, so a seam built from one counts as\n * built from the other: `Policy.provide` keeps the bodies and rules, and\n * changes only the services they run with. `validate` checks that a seam's\n * rules are the declared ones; it does not check which services they were\n * given.\n */\nimport type { Policy } from './index.js'\n\nconst origins = new WeakMap<object, object>()\n\n/** The Policy `G.implement` built that `policy` was provided from: itself, for one it built. */\nexport const originOf = (policy: Policy<any, any>): object => origins.get(policy) ?? policy\n\n/** Records `policy` as provided from `from`. */\nexport const providedFrom = <P extends Policy<any, any>>(policy: P, from: Policy<any, any>): P => {\n origins.set(policy, originOf(from))\n return policy\n}\n"],"mappings":";AASA,MAAM,0BAAU,IAAI,QAAwB;;AAG5C,MAAa,YAAY,WAAqC,QAAQ,IAAI,MAAM,KAAK;;AAGrF,MAAa,gBAA4C,QAAW,SAA8B;CAChG,QAAQ,IAAI,QAAQ,SAAS,IAAI,CAAC;CAClC,OAAO;AACT"}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
import { r as attached } from "./attach-
|
|
2
|
-
import { t as originOf } from "./origin-
|
|
1
|
+
import { r as attached } from "./attach-CRCF5XHS.mjs";
|
|
2
|
+
import { t as originOf } from "./origin-igJoiz74.mjs";
|
|
3
3
|
import { Option } from "effect";
|
|
4
|
-
|
|
4
|
+
// src/placed.ts
|
|
5
5
|
/**
|
|
6
6
|
* What each guard seam built, and for which Policy and Entities, so
|
|
7
7
|
* `GuardServer.validate` can tell a Source that applies a guard set's rules
|
|
@@ -34,7 +34,6 @@ const rowRules = record(/* @__PURE__ */ new WeakMap());
|
|
|
34
34
|
const memberRules = record(/* @__PURE__ */ new WeakMap());
|
|
35
35
|
/** Write rules: `GuardServer.writer`'s. */
|
|
36
36
|
const writeRules = record(/* @__PURE__ */ new WeakMap());
|
|
37
|
-
//#endregion
|
|
38
37
|
export { rowRules as n, writeRules as r, memberRules as t };
|
|
39
38
|
|
|
40
|
-
//# sourceMappingURL=placed-
|
|
39
|
+
//# sourceMappingURL=placed-BvdNmZJu.mjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"placed-
|
|
1
|
+
{"version":3,"file":"placed-BvdNmZJu.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"}
|
package/dist/server.d.mts
CHANGED
|
@@ -1,9 +1,8 @@
|
|
|
1
|
-
import { S as Policy, k as MeEntity, l as InteractionKey } from "./attach-
|
|
1
|
+
import { S as Policy, k as MeEntity, l as InteractionKey } from "./attach-BepaL930.mjs";
|
|
2
2
|
import { Effect, Option } from "effect";
|
|
3
3
|
import { AnyEntity, AnyQuery } from "foldkit-entity";
|
|
4
4
|
import { EntitySource, EntityWriter, MemoryReadable, MutationOutcome, MutationRefused, MutationSource, ReadPlan, RemoteServerError, ServerDefinition } from "foldkit-remote-server";
|
|
5
5
|
import { MutationDescriptor, RemoteForbidden } from "foldkit-remote";
|
|
6
|
-
//#region src/server.d.ts
|
|
7
6
|
export declare const GuardServer: {
|
|
8
7
|
/**
|
|
9
8
|
* `Guards.me`'s Source: the one row, `me`, as the asker is, with `may`
|
|
@@ -145,5 +144,4 @@ export declare const GuardServer: {
|
|
|
145
144
|
readonly server: ServerDefinition<any, any>;
|
|
146
145
|
}) => void;
|
|
147
146
|
};
|
|
148
|
-
//#endregion
|
|
149
147
|
//# sourceMappingURL=server.d.mts.map
|
package/dist/server.d.mts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"server.d.mts","names":[],"sources":["../src/server.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"server.d.mts","names":[],"sources":["../src/server.ts"],"mappings":";;;;;qBA4Ea;;;;;;;;;;EAUX,KAAK,MAAM,GAAC,QACF,UAAQ,QACR,OAAO,MAAM,OACpB,aAAa,OAAO,OAAO,OAAO;;;;;;;;;;EA6CrC,SAAS,MAAM,GAAC,QAAU,WAAS,QAAU,OAAO,MAAM,QAAE,WAG3C,OAAO,OAAO,OAAK,8BAE7B,OAAO,OAAO,iBAAiB;;;;;;;EAuEtC,SAAS,MAAI,QAAU,OAAO,OAAK,UAAY,cAAc;IAC3D,WAAQ,WAEO,OAAO,OAAO,OAAK,MACxB,gBAAgB,eAAe,OAAO,OAAO,SAAS,8BAC3D,OAAO,OAAO;IA4CnB;OAzHY,aAAA,WAAA,OAAA,OAAA,OAAA,8BAAiB,OAAA,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;EA+J/B,SAAS,UAAU,WAAW,MAAM,GAAG,IAAE,QAC/B,GAAC,QACD,OAAO,MAAM,IAAE,QACf,aAAa,OAAO,OAAO,OAAO,KAAG;aAElC,sBACG,WAAW,gBAAgB,MAAM,SAAS,YAAY;aAEzD,iBAAiB;QAE3B,aAAa,OAAO,OAAO,OAAO,IAAI;;;;;;;;;;;;;;;;;;;;;EA6hBzC,WAAW,MAAM,GAAG,IAAI,IAAI,qBAAqB,OAAO,QAAQ,SAAO,UAC3D,mBAAmB,MAAM,OAAO,QAAQ,UAAQ;aAE/C,QAAQ;aACR,QAAQ,OAAO,MAAM;aACrB,8CAA8C;;;;;;aAM9C,OAAO,OAAO,mBAAmB,OAAO;;aAExC,QAAQ,aAAa,OAAO,OAAO,OAAO;;aAE1C,SAAS;KACnB,MACK;aACK,OAAO;aACP,WAAW,OAAO,OAAO;aACzB;aACA,KAAK,OAAO,OAAO,SAAS;QACjC,OAAO,OACX,gBAAgB,SAChB,oBAAoB,kBAAkB,iBACtC,QAED,eAAe,OAAO,OAAO,OAAO,IAAI,KAAK;;;;;;;;;;;;;;;;;;EA6FhD,WAAW,MAAM,GAAC,QACR,OAAO,MAAM,IAAE;aAEZ,UAAU,cAAc;;aAExB;eACE;iBACE,SAAS;mBAEL;mBAA0B,OAAO;;;;aAIzC,QAAQ"}
|
package/dist/server.mjs
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { t as Condition } from "./condition-
|
|
3
|
-
import "./me-
|
|
4
|
-
import { n as rowRules, r as writeRules, t as memberRules } from "./placed-
|
|
1
|
+
import { c as readRowsRuled, i as attachedRules, l as readRuled, r as attached } from "./attach-CRCF5XHS.mjs";
|
|
2
|
+
import { t as Condition } from "./condition-Dx54lL7v.mjs";
|
|
3
|
+
import "./me-BYpuVqJE.mjs";
|
|
4
|
+
import { n as rowRules, r as writeRules, t as memberRules } from "./placed-BvdNmZJu.mjs";
|
|
5
5
|
import { Effect, Match, Option, Schema, SchemaAST } from "effect";
|
|
6
|
-
import { Entity, Query } from "foldkit-entity";
|
|
6
|
+
import { Entity, Expr, Query, QueryEvaluateError, Write, dependenciesOf, supported } from "foldkit-entity";
|
|
7
7
|
import { RemoteInvalid, RemoteServer, RemoteServerError } from "foldkit-remote-server";
|
|
8
|
-
|
|
8
|
+
// src/server.ts
|
|
9
9
|
/**
|
|
10
10
|
* A guard set's read rules as `foldkit-remote-server`'s seams: an
|
|
11
11
|
* `EntitySource.filter` from each member's Read rule, and `RemoteServer.memory`'s
|
|
@@ -91,7 +91,7 @@ const GuardServer = {
|
|
|
91
91
|
apply: (record) => {
|
|
92
92
|
const values = { ...record.values };
|
|
93
93
|
for (const { member, condition, redacted } of decided) {
|
|
94
|
-
if (Condition.holds(condition, record.values, input, () => false)) continue;
|
|
94
|
+
if (Condition.holds(condition, record.values, input, () => false, policy.operators)) continue;
|
|
95
95
|
Option.match(redacted, {
|
|
96
96
|
onNone: () => {
|
|
97
97
|
delete values[member];
|
|
@@ -134,7 +134,7 @@ const GuardServer = {
|
|
|
134
134
|
onSome: (target) => holds(ref.entity, target, /* @__PURE__ */ new Set([...seen, key]))
|
|
135
135
|
});
|
|
136
136
|
}
|
|
137
|
-
}));
|
|
137
|
+
}), policy.operators);
|
|
138
138
|
};
|
|
139
139
|
return (entity, values) => holds(entity, values, /* @__PURE__ */ new Set());
|
|
140
140
|
}), policy, entities),
|
|
@@ -192,7 +192,7 @@ const GuardServer = {
|
|
|
192
192
|
if (writer.entity !== entity.name) throw new Error(`[foldkit-guard] GuardServer.writer: ${entity.name}'s rules over a writer for ${writer.entity}`);
|
|
193
193
|
const read = writer.read;
|
|
194
194
|
if (read === void 0) throw new Error(`[foldkit-guard] GuardServer.writer: ${entity.name}'s writer reads no row as its writer may see it; bind it with a visible rule (GuardDrizzle.visible)`);
|
|
195
|
-
const holds = (rule, values, principal) => Condition.holds(rule.condition, values, policy.inputOf(principal), () => false);
|
|
195
|
+
const holds = (rule, values, principal) => Condition.holds(rule.condition, values, policy.inputOf(principal), () => false, policy.operators);
|
|
196
196
|
/** Fails with the first rule of `rules` that does not hold over `values`. */
|
|
197
197
|
const require = (rules, values, principal) => Option.match(Option.fromUndefinedOr(rules.find((rule) => !holds(rule, values, principal))), {
|
|
198
198
|
onNone: () => Effect.void,
|
|
@@ -257,11 +257,12 @@ const GuardServer = {
|
|
|
257
257
|
}));
|
|
258
258
|
const told = (error) => error instanceof RemoteInvalid && Option.exists(error.rule, (rule) => unnamed.has(rule)) ? RemoteServer.invalid("The row would be invalid") : error;
|
|
259
259
|
/**
|
|
260
|
-
* Fails a write whose `when` reads,
|
|
261
|
-
* a Read rule: Unmet or written,
|
|
260
|
+
* Fails a write whose `when` reads, whose `expect` names, or whose
|
|
261
|
+
* computed assignment reads, a member with a Read rule: Unmet or written,
|
|
262
|
+
* Conflict or not, and the computed value answered, would answer for it.
|
|
262
263
|
* `validate` refuses the same at startup; this holds where it was not run.
|
|
263
264
|
*/
|
|
264
|
-
const discloses = (expect, when) => Option.match(attachment, {
|
|
265
|
+
const discloses = (expect, when, assignments = {}) => Option.match(attachment, {
|
|
265
266
|
onNone: () => Effect.void,
|
|
266
267
|
onSome: (ruled) => {
|
|
267
268
|
const read = Option.match(when, {
|
|
@@ -278,7 +279,15 @@ const GuardServer = {
|
|
|
278
279
|
onNone: () => [],
|
|
279
280
|
onSome: ({ field }) => readRuled(ruled, field) ? [field] : []
|
|
280
281
|
});
|
|
281
|
-
const
|
|
282
|
+
const computed = Write.boundReads({
|
|
283
|
+
increments: {},
|
|
284
|
+
assignments
|
|
285
|
+
}).filter((field) => readRuled(ruled, field));
|
|
286
|
+
const hidden = [.../* @__PURE__ */ new Set([
|
|
287
|
+
...read,
|
|
288
|
+
...expected,
|
|
289
|
+
...computed
|
|
290
|
+
])];
|
|
282
291
|
return hidden.length === 0 ? Effect.void : Effect.fail(new RemoteServerError({ message: `${entity.name}'s write reads ${hidden.join(", ")}, which a Read rule hides from its writer` }));
|
|
283
292
|
}
|
|
284
293
|
});
|
|
@@ -301,28 +310,62 @@ const GuardServer = {
|
|
|
301
310
|
};
|
|
302
311
|
const memberRead = GuardServer.filter(entity, policy);
|
|
303
312
|
/** Refused before any rule, for what the write declares rather than what the row holds. */
|
|
304
|
-
const admitUpdate = (context) => Effect.andThen(discloses(context.expect, context.when), () => Object.keys(context.increments).length > 0 && Option.isNone(context.expect) && revision === void 0 ? Effect.fail(new RemoteServerError({ message: `${entity.name}'s
|
|
313
|
+
const admitUpdate = (context) => Effect.andThen(discloses(context.expect, context.when, context.assignments), () => Object.keys(context.increments).length + Object.keys(context.assignments).length > 0 && Option.isNone(context.expect) && revision === void 0 ? Effect.fail(new RemoteServerError({ message: `${entity.name}'s write moves a field and expects no revision, and its writer pins none, so its rules would judge a value over a row that may move; give the writer a revision` })) : Effect.void);
|
|
305
314
|
/** The rules an update must meet: the row's, each member it sets, each relation it points. */
|
|
306
315
|
const updateRules = (context) => Effect.gen(function* () {
|
|
307
316
|
return {
|
|
308
317
|
row: yield* policy.writable(entity, context.principal, "Update"),
|
|
309
|
-
members: yield* policy.writeMembers(entity, context.principal, [
|
|
318
|
+
members: yield* policy.writeMembers(entity, context.principal, [
|
|
319
|
+
...Object.keys(context.values),
|
|
320
|
+
...Object.keys(context.increments),
|
|
321
|
+
...Object.keys(context.assignments)
|
|
322
|
+
], "Update"),
|
|
310
323
|
relating: yield* linkRules(context.principal, context.links)
|
|
311
324
|
};
|
|
312
325
|
});
|
|
313
|
-
/**
|
|
326
|
+
/**
|
|
327
|
+
* The row as its writer may see it, with every field the rules and the
|
|
328
|
+
* version read, and those the write's amounts and assignments read to
|
|
329
|
+
* work out the row it leaves.
|
|
330
|
+
*/
|
|
314
331
|
const readBefore = (context, rules) => read({
|
|
315
332
|
id: context.id,
|
|
316
333
|
fields: fieldsOf([
|
|
317
334
|
rules.row,
|
|
318
335
|
...rules.members,
|
|
319
336
|
...ruleOf(rules.relating)
|
|
320
|
-
], [
|
|
337
|
+
], [
|
|
338
|
+
...Object.keys(context.links),
|
|
339
|
+
...versionFields(context.expect),
|
|
340
|
+
...Write.boundReads(context)
|
|
341
|
+
]),
|
|
321
342
|
principal: context.principal
|
|
322
343
|
});
|
|
344
|
+
/**
|
|
345
|
+
* The memory table the row a write leaves is worked out by: the writer's,
|
|
346
|
+
* so the rules judge the value its statement writes, else the policy's.
|
|
347
|
+
*/
|
|
348
|
+
const computing = writer.operators ?? policy.operators;
|
|
349
|
+
/**
|
|
350
|
+
* The row `context` would leave `before` as. An operator's refusal (text
|
|
351
|
+
* holding NUL, an implementation that throws) is a server error, as the
|
|
352
|
+
* writer answers what it cannot compile: logged here, and never sent, since
|
|
353
|
+
* an implementation's own message may say anything. So is a field it cannot
|
|
354
|
+
* work out at all: judging its old value would let a rule over it pass.
|
|
355
|
+
*/
|
|
356
|
+
const leaves = (before, context) => Effect.suspend(() => {
|
|
357
|
+
const unworkable = Effect.fail(new RemoteServerError({ message: `${entity.name}'s write could not be worked out to judge its rules` }));
|
|
358
|
+
try {
|
|
359
|
+
const applied = Write.apply(before, context, { operators: computing });
|
|
360
|
+
return applied.unknown.length === 0 ? Effect.succeed(applied.row) : unworkable;
|
|
361
|
+
} catch (error) {
|
|
362
|
+
if (!(error instanceof QueryEvaluateError)) throw error;
|
|
363
|
+
return Effect.logError("[foldkit-guard] a computed value could not be worked out", error).pipe(Effect.andThen(unworkable));
|
|
364
|
+
}
|
|
365
|
+
});
|
|
323
366
|
/** The rules, over the row as it is and as the write would leave it. */
|
|
324
367
|
const decideUpdate = (context, rules, before) => Effect.gen(function* () {
|
|
325
|
-
const { principal,
|
|
368
|
+
const { principal, links } = context;
|
|
326
369
|
const linked = Object.keys(links);
|
|
327
370
|
const stored = writer.linked === void 0 || linked.length === 0 ? Option.none() : yield* writer.linked({
|
|
328
371
|
id: context.id,
|
|
@@ -338,25 +381,33 @@ const GuardServer = {
|
|
|
338
381
|
exact: true
|
|
339
382
|
})
|
|
340
383
|
})));
|
|
341
|
-
const after = {
|
|
342
|
-
...before,
|
|
343
|
-
...values,
|
|
344
|
-
...Object.fromEntries(Object.entries(increments).map(([field, amount]) => [field, Number(before[field]) + amount])),
|
|
345
|
-
...Object.fromEntries(Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]))
|
|
346
|
-
};
|
|
347
384
|
yield* require([
|
|
348
385
|
rules.row,
|
|
349
386
|
...rules.members,
|
|
350
387
|
...relations
|
|
351
388
|
], before, principal);
|
|
389
|
+
const after = {
|
|
390
|
+
...yield* leaves(before, context),
|
|
391
|
+
...Object.fromEntries(Object.entries(links).map(([relation, link]) => [relation, linkKey(link)]))
|
|
392
|
+
};
|
|
352
393
|
yield* require([rules.row], after, principal);
|
|
353
394
|
});
|
|
354
395
|
const guarded = {
|
|
355
396
|
entity: writer.entity,
|
|
356
397
|
...writer.preconditions === true ? { preconditions: true } : {},
|
|
357
398
|
...writer.increments === true ? { increments: true } : {},
|
|
399
|
+
...writer.assignments === true ? { assignments: true } : {},
|
|
400
|
+
...revision === void 0 ? {} : { pins: true },
|
|
358
401
|
...writer.ledger === true ? { ledger: true } : {},
|
|
359
402
|
...writer.invariants === true ? { invariants: true } : {},
|
|
403
|
+
refuses: (write) => [
|
|
404
|
+
...writer.refuses?.(write) ?? [],
|
|
405
|
+
...write.assignments.flatMap(({ field, expr }) => Expr.unsupported([expr], {
|
|
406
|
+
operations: supported,
|
|
407
|
+
operators: computing
|
|
408
|
+
}).map((missing) => `its assignment to "${field.key}" calls ${missing}, which the guard cannot work out`)),
|
|
409
|
+
...(write.increments.length > 0 || write.assignments.length > 0) && write.expect === void 0 && revision === void 0 ? ["it moves a field and expects no revision, and the guarded writer pins none, so its rules would judge a value over a row that may move; give the writer a revision"] : []
|
|
410
|
+
],
|
|
360
411
|
...writer.recorded === void 0 ? {} : { recorded: writer.recorded },
|
|
361
412
|
read: ({ id, fields, principal }) => seenRow({ filter: memberRead }, (seen) => read({
|
|
362
413
|
id,
|
|
@@ -478,7 +529,7 @@ const GuardServer = {
|
|
|
478
529
|
const input = policy.inputOf(principal);
|
|
479
530
|
if (Option.isNone(target)) {
|
|
480
531
|
const unset = Condition.unsetting(rule.condition, new Set(ruled));
|
|
481
|
-
if (!Condition.holds(unset, {}, input, () => false)) return yield* Effect.fail(refused(rule.deny));
|
|
532
|
+
if (!Condition.holds(unset, {}, input, () => false, policy.operators)) return yield* Effect.fail(refused(rule.deny));
|
|
482
533
|
return yield* shown(yield* run({
|
|
483
534
|
...context,
|
|
484
535
|
row: Option.none()
|
|
@@ -490,7 +541,7 @@ const GuardServer = {
|
|
|
490
541
|
...guard.fields ?? []
|
|
491
542
|
])];
|
|
492
543
|
const row = Option.fromUndefinedOr(yield* rowOf(source, principal, fields, target.value));
|
|
493
|
-
if (Option.isNone(row) || !Condition.holds(rule.condition, row.value, input, () => false)) return yield* Effect.fail(refused(rule.deny));
|
|
544
|
+
if (Option.isNone(row) || !Condition.holds(rule.condition, row.value, input, () => false, policy.operators)) return yield* Effect.fail(refused(rule.deny));
|
|
494
545
|
return yield* shown(yield* run({
|
|
495
546
|
...context,
|
|
496
547
|
row
|
|
@@ -546,10 +597,12 @@ const GuardServer = {
|
|
|
546
597
|
onNone: () => [],
|
|
547
598
|
onSome: (body) => hiddenOf(attachment, Query.dependencies(body).predicate)
|
|
548
599
|
});
|
|
600
|
+
const computed = write.assignments.flatMap((assignment) => hiddenOf(attachment, dependenciesOf(assignment.expr).fields).map((member) => `write ${mutation} computes ${name}'s ${assignment.field.key} from its ${member}, which has a Read rule`));
|
|
549
601
|
const expected = write.expect?.field.key;
|
|
550
602
|
const pin = typeof writer === "object" && writer !== null ? pins.get(writer) : void 0;
|
|
551
603
|
return [
|
|
552
604
|
...when.map((member) => `write ${mutation}'s precondition reads ${name}'s ${member}, which has a Read rule`),
|
|
605
|
+
...computed,
|
|
553
606
|
...expected !== void 0 && readRuled(attachment, expected) ? [`write ${mutation} expects ${name}'s ${expected}, which has a Read rule`] : [],
|
|
554
607
|
...expected !== void 0 && pin !== void 0 && Option.exists(pin, (field) => field !== expected) ? [`write ${mutation} expects ${name}'s ${expected}, but its writer pins ${Option.getOrThrow(pin)}`] : []
|
|
555
608
|
];
|
|
@@ -565,6 +618,7 @@ const GuardServer = {
|
|
|
565
618
|
if (!byName.has(target)) return [...own, `${name}'s Source shares ${member}, whose ${target} is not validated`];
|
|
566
619
|
return rowsRuled(byName.get(target)) ? [...own, `${name}'s Source shares ${member}, whose rows have a Read rule`] : own;
|
|
567
620
|
})];
|
|
621
|
+
const operatorProblems = attachedRules(attachment).flatMap((rule) => rule._tag === "RowGuard" ? Query.unsupported(rule.query, supported, policy.operators).map((missing) => `${name}'s ${rule.name} calls ${missing}, which the policy does not run`) : []);
|
|
568
622
|
const liveProblems = config.server.live.has(name) ? [`${name} has a live Source of its own; serve its changes through a live hub`] : [];
|
|
569
623
|
return [
|
|
570
624
|
...sourceProblems,
|
|
@@ -572,6 +626,7 @@ const GuardServer = {
|
|
|
572
626
|
...bodyProblems,
|
|
573
627
|
...writeProblems,
|
|
574
628
|
...sharedProblems,
|
|
629
|
+
...operatorProblems,
|
|
575
630
|
...liveProblems
|
|
576
631
|
];
|
|
577
632
|
}
|
|
@@ -628,7 +683,7 @@ const mayOf = (entity, policy, principal) => {
|
|
|
628
683
|
})))
|
|
629
684
|
]), ([rows, members, relations]) => {
|
|
630
685
|
const input = policy.inputOf(principal);
|
|
631
|
-
const holds = (condition, values) => Condition.holds(condition, values, input, () => false);
|
|
686
|
+
const holds = (condition, values) => Condition.holds(condition, values, input, () => false, policy.operators);
|
|
632
687
|
const allows = (rule, values) => Option.match(rule, {
|
|
633
688
|
onNone: () => true,
|
|
634
689
|
onSome: ({ condition }) => holds(condition, values)
|
|
@@ -699,7 +754,6 @@ const linkKey = (link) => Option.match(link, {
|
|
|
699
754
|
});
|
|
700
755
|
/** Whether a query's result is a connection over `entity`. */
|
|
701
756
|
const lists = (result, entity) => typeof result === "object" && result !== null && "entity" in result && result.entity === entity;
|
|
702
|
-
//#endregion
|
|
703
757
|
export { GuardServer };
|
|
704
758
|
|
|
705
759
|
//# sourceMappingURL=server.mjs.map
|