Guard / foldkit-guard
Serving writes
A declared write (Mutation.write) runs through RemoteServer.write (see the
declared writes guide). Wrap its writer with
GuardServer.writer to enforce write rules before any row changes:
import { Write } from 'foldkit-entity'
import { Mutation } from 'foldkit-remote'
import { writer } from 'foldkit-remote-drizzle'
const EditTodo = Mutation.write(
'EditTodo',
Write.update(Entity.input(Todo, Schema.Struct({ id: Schema.String, title: Schema.String })), {
id: 'id',
}),
)
RemoteServer.write(EditTodo, GuardServer.writer(Todo, Policy, writer(Db.Todo)))How writes and cascades are checked
- Reads before writing: updates and deletes load the row under the writer's
visibility. Hidden rows fail updates as
Forbiddenand answer deletes as already deleted. - Row rules:
Createchecks proposed values (fields left unset fail any guard reading them).Updatechecks the row both before and after the write so writers can move rows only within their own visibility.Deletechecks the existing row. - Member and link rules: each set or incremented member requires its
CreateorUpdaterule, and changed relations requireUnlinkon the old target andLinkon the new one. Updates evaluate each member/link rule against the new row with that one change reverted, preventing multi-field bypasses while letting transition rules like "updatestatusonly whiledraft" pass. - Refusals and readback: signed-in failures return
Forbidden(withGuards.explaintext); visitors (Option.none()) returnUnauthenticatedso clients prompt for sign-in and outbox writes retry cleanly. Accepted writes return only fields and relations the writer may read, reporting rows that left the writer's visibility indeleted. - Cascades and link clearing: for
onDelete: 'cascade'andonDelete: 'setNull'relations, pass{ children: [Like] }toGuardServer.writer. Cascades check every child'sDeleterule (unlessauthorizedBy: 'parent') andsetNullchecks each child'sUpdateandUnlinkrules in the same statement/batch, refusing the whole delete on any failure without leaking child IDs.
A revision closes the gap between the check and the write
Because loading a row and writing it are separate statements, another write can
land in between. Add a numeric revision field and pass { revision: 'revision' }
to GuardServer.writer so every update and delete pins the revision it checked:
GuardServer.writer(Todo, Policy, writer(Db.Todo), { revision: 'revision' })If another write moves the row first, the guard reloads and re-evaluates up to
three times before failing with an Internal error (ServerDefect logged as
"changed while it was written"). Client inputs with stale expect revisions
fail immediately with Conflict. GuardServer.validate emits an
UnpinnedWrites diagnostic for updates or deletes on Entities without a
revision pin.
Preconditions, increments and invariants
- Preconditions (
when): the writer checkswhenafter guards pass, in the order: hidden row (Forbidden), stale expected revision (Conflict), failed guard (Forbidden), unmet precondition (Unmet).GuardServer.validateand the writer reject preconditions orexpectover fields withReadrules to prevent oracle leaks. - Increments and computed assignments: increments require the member's
Updaterule and check row rules over the resulting sum; computed assignments run throughWrite.applywith youroperatorstable (emittingComputeRefusedon operator errors) and reject reads fromRead-guarded members. Both require eitherexpector a writerrevisionpin. - Invariants (
Entity.invariant): invariants run after guards pass and fail withInvalid. Invariants reading aRead-guarded member still run, reporting a generic"The row would be invalid"message without naming hidden values.
Retries
When a writer uses a ledger (writer(binding, { ledger })), retries of an
already-applied operation replay from the ledger immediately, while failed or
first-time requests evaluate against the current principal and row.
The writer's binding
Give GuardServer.writer the same binding (Db.Todo) used by the Entity's
Source so its visible filter matches GuardDrizzle.visible.
Fields the server sets
Use Entity.sets (Expr.viewer, Expr.now) in foldkit-entity for fields
such as ownerId so RemoteServer.write populates them before guards run.
Inputs attempting to set those fields fail declaration checks, and visitors
fail with Unauthenticated. Duplicate creates return Refusal.taken uniformly,
while ledger retries replay the original row to the same creator.
Handlers
Custom mutation handlers (RemoteServer.mutation) use GuardServer.mutation to
check one interaction rule before executing:
const ArchiveTodo = Mutation.make('ArchiveTodo', { Input: { id: Schema.String }, Output: {} })
GuardServer.mutation(
ArchiveTodo,
{ entity: Todo, policy: Policy, interaction: Archive.key, id: input => input.id, source: TodoSource },
({ input, row }) => Effect.succeed({ output: {} }), // `row`: the todo, as its writer sees it
)idloads the target row throughsource(rejecting hidden rows); omittingidchecks principal/create rules, and returning anOptionhandles both create (Option.none()) and edit (Option.some(id)).- Pass
fieldsto select extra columns for your handler; returned Entity rows pass back throughsource'sauthorizeandfilter, marking newly hidden rows as deleted.
Rules that read another row
Read, Update, and Delete row guards can traverse relations (Expr.path,
Expr.exists, or viewer paths). Read rules compile into SQL subqueries, while
Update and Delete rules pass remaining cross-row conditions to
remote-drizzle's writer via requires (update … where … and <rule>) so
they evaluate atomically at write time on SQLite and Postgres (Postgres apps
call postgres() from foldkit-remote-drizzle/pg at startup).
- Cross-row
Update/Deleterules read the stored row, blocking writes that would move a row out of reach (such as moving a note to another team). mayleaves cross-row interactions undecided (May.answerreturns anUnknownVerdict). Keep forms editable and hide controls withMay.refusedrather than!May.can, letting the server render the final decision.GuardServer.writerthrows if given a writer withoutrequiressupport; single-row seams (GuardServer.mutation,GuardSync.document,GuardServer.memory) reject cross-row rules on those surfaces by name.