Guard / foldkit-guard
Attaching guards to an Entity
A guard set names rules; Guards.attach places them on each surface (row,
member, relation) and interaction. Here a todo links to a Project via
project (stored as projectId), and Project has no guards so anyone can
read it:
ts
import { Relation } from 'foldkit-entity'
import { Interaction } from 'foldkit-guard'
const ProjectFields = Entity.define(
'Project',
Schema.Struct({ id: Schema.String, name: Schema.String }),
)
const Related = Entity.relate(
{ Todo: TodoFields, Project: ProjectFields },
{ Todo: { project: Relation.one(ProjectFields) } },
)
const Project = Related.Project
const Archive = Interaction.make('Archive')
const Todo = Related.Todo.pipe(
Guards.attach(G, {
row: {
Read: [G.isOwner, G.inProject, G.isAdmin],
Write: [G.isOwner],
},
interactions: {
[Archive.key]: Guards.on([G.isAdmin], Guards.explain('Only an admin may archive.')),
},
members: { ownerId: { Update: [G.isAdmin] } },
}),
Guards.may, // adds the derived `may` hint member: see What the client may do
)
Guards.matrix([Todo])
// Todo.Read: isOwner | inProject | isAdmin → not_found
// Todo.Create: isOwner → forbidden
// Todo.Update: isOwner → forbidden
// Todo.Delete: isOwner → forbidden
// Todo.Archive: isAdmin → explain("Only an admin may archive.")
// Todo.ownerId.Create: isAdmin → forbidden
// Todo.ownerId.Update: isAdmin → forbiddenCombining rules and interactions
- Lists on a surface act as a disjunction ("owner, or project member, or
admin"). Use
Guards.all(a, b)for conjunctions, andalways: [...]for rules ANDed across every surface (such as tenant isolation or requiring a signed-in user). Writeexpands toCreate,Update, andDelete; adding a specific slot such asDeletealongsideWriteappends its rules and replacesWrite's refusal. A member'sUpdaterule also governsCreateunlessCreateis listed separately.- Custom interactions (
Interaction.make('Archive')) live underinteractionskeyed by[Archive.key], catching typos at compile time. Guards.inherit('project')delegates a row'sReadto itsonerelation'sReadrule.- Surfaces left unguarded on a guarded Entity fall back to
unguardedfromGuards.declare('deny'printsclosed,'allow'printsopen).
Refusals, descriptors, and guard fields
- Default refusals vary by surface: row reads return not found (hiding
existence), member and relation reads omit the value, and writes return
Forbidden. UseGuards.on(guards, Guards.redact(value))to replace a hidden member with a typed fallback, orGuards.on(guards, Guards.explain(reason))to attach a message to a refused write. - Unknown member keys, guards from another Entity or set, and misspelled interactions are type errors.
Guards.attachreturns a new descriptor carrying the rules (Entity.sameis stilltrue); pass that returned descriptor to every enforcement API (GuardServer.writer,filter,memory,mutation,GuardDrizzle.visible, andGuardSync.document), which throw if given an unguarded descriptor of a guarded Entity.Guards.guardFields(Todo, 'Read')lists the row's own fields read by itsReadrules (plus inherited relations) so live updates know when to refetch.
What a row guard may read
A row guard is an Expr over its Entity's row and the principal's fields:
- Compare a
onerelation directly to the linked ID (guard.row(Like, p => Expr.eq(Like.relations.user, p.id))) without storing a duplicate field. - Pass
{ viewer: User }toGuards.declareso rules can referenceExpr.viewer(User), matched againstPolicy.viewer(principal)(RemoteServer.make({ viewer: Policy.viewer })). - Scope rules per variant case (
Entity.defineVariants) withExpr.is:guard.row(Domain, p => Expr.is(Domain, 'Available', ({ price }) => Expr.lte(price, p.budget))). - Reach across relations in row
Read,Update, andDeleterules usingExpr.path,Expr.exists, or a viewer path (Expr.eq(Note.fields.orgId, orgOfViewer)).Readrules compile to SQL;UpdateandDeleterules run inside the write statement (Rules that read another row).