Guard / foldkit-guard
guard
In most applications, permission checks live scattered across route handlers,
SQL WHERE clauses, form field locks, and UI buttons. Adding a role or an
endpoint means hunting down every check by hand, and a single missed WHERE
clause leaks another customer's rows.
foldkit-guard lets you declare who may read and change each row once on your
data model, in the shared domain code both client and server import. You split
rules into server-only checks on the signed-in user (principal guards) and
data rules over each row (row guards, written as expressions). On the server,
those rules compile into SQL filters and check every write; on the client, a
may hint tells your UI which actions to enable.
Read How Guard works for an end-to-end walkthrough, or
see it running in examples/auth and
examples/chirp (live at
foldkit-chirp-demo.pages.dev).
How rules are split and who owns what
A guard set splits every rule into two parts so shared domain code stays safe in the browser:
- A principal guard is declared by name in shared code, while its body
lives only on the server (
G.implement), keeping server-only role or membership lookups out of the client bundle. - A row guard is an
Exprover one Entity's fields and the principal's fields. Because it is pure data, the SQL compiler and in-memory evaluator both run it; see the Expressions guide.
| Fact | Owner |
|---|---|
| Who is asking | Your authentication layer, provided as G.Principal |
| Who may do what | The guard set, declared once in shared domain code |
| Principal guard bodies | G.implement, on the server only |
| Which rows a read returns | Each binding's visible, compiled from the rules |
| Server enforcement | Subpaths for foldkit-remote-server, -drizzle, and foldkit-sync |
| Client button and lock hints | The server's may answer, foreseen locally for pending writes |
Authentication stays outside this package: your auth layer resolves G.Principal
per request, and the server checks every write against the rules even when the
client already holds a may hint.
Use a guard for rules about who may read or change a row. Rules about
what a row may hold regardless of who writes it belong in
Entity.invariant, which fails with Invalid rather than Forbidden.
One domain declaration shows both on one Entity, and
Auth and Guard traces sign-in through to a
guarded row.
How a rule is enforced across your app
Shared domain code declares the rules with Guards.declare and attaches them to
Entities with Guards.attach. On the server, G.implement supplies the
principal guard bodies to produce a Policy. Every seam enforces that same
Policy:
- Reads:
GuardDrizzle.visibleandGuardServer.memoryfilter rows;GuardServer.filterfilters members, relations, andmay. - Writes:
GuardServer.writerandGuardServer.mutationcheck rules before writing and filter the returned row. - Sync:
GuardSync.authorize,admit, andopensguard replicated edits through the journal. - Agents:
GuardAgentgates capabilities andmayhints. - Startup:
GuardServer.validateverifies every guarded Source and write at boot.
When deciding a rule, the server evaluates each principal guard once per request, leaving a boolean condition over row fields that SQL or the in-memory evaluator runs.
Install
pnpm add effect foldkit-entity foldkit-guardfoldkit-guard holds the shared declarations. Its subpaths integrate with
optional peer packages: foldkit-guard/server (foldkit-remote,
foldkit-remote-server), /drizzle (foldkit-remote-drizzle, drizzle-orm),
/sync (foldkit-sync, foldkit-remote-server), /agent (foldkit-remote),
and /media (foldkit-media).
A first guard set
This declares a Todo entity with three guards (isAdmin, isOwner,
inProject), implements the server-only check, and evaluates a read for Ada
(the owner) and Bo (someone else):
import { Effect, Option, Schema } from 'effect'
import { Entity, Expr } from 'foldkit-entity'
import { Guards } from 'foldkit-guard'
const User = Schema.Struct({
id: Schema.String,
role: Schema.Literals(['admin', 'member']),
projectIds: Schema.Array(Schema.String),
})
const TodoFields = Entity.define(
'Todo',
Schema.Struct({ id: Schema.String, ownerId: Schema.String, projectId: Schema.String, title: Schema.String }),
)
const G = Guards.declare('Todos', User, guard => ({
isAdmin: guard.principal(),
isOwner: guard.row(TodoFields, p => Expr.eq(TodoFields.fields.ownerId, p.id)),
inProject: guard.row(TodoFields, p => Expr.in(TodoFields.fields.projectId, p.projectIds)),
}), { key: user => user.id, unguarded: 'deny' })
const Policy = G.implement({
isAdmin: principal => Option.exists(principal, user => user.role === 'admin'),
})
const sampleTodo = { id: 't1', ownerId: 'ada', projectId: 'p1', title: 'Write the README' }
const decide = (id: string) =>
Effect.runSync(Policy.decide(G.isOwner, { principal: Option.some({ id, role: 'member', projectIds: [] }), interaction: 'Read', row: sampleTodo }))
decide('ada') // true
decide('bo') // falseAda owns t1, so decide('ada') returns true; Bo's ID differs from
ownerId, so decide('bo') returns false.
Guards.declarebuilds each row guard's predicate once using placeholders (p.idstands forprincipal.id) and rejects predicates over another Entity or direct JavaScript branching on placeholders at compile time.G.implementsupplies the body for every principal guard (missing or extra keys fail typechecking and runtime validation). Pass{ operators }as a second argument when row guards call custom primitive operators (defaults toOperators.kernel).Policy.decidereturns anEffectyieldingtrue,false, or{ allowed: false, reason }. Anonymous visitors passOption.none()and fail row guards that read principal fields, while passing row-only predicates such asisPublished.G.Principalis the serverContextkey holdingOption<Principal>;G.key(user)returns the stable user identifier for cache scoping (see Who is asking).