Guard / foldkit-guard

Sync

foldkit-guard/sync checks foldkit-sync/entity cell edits in two stages: principal guards synchronously under the journal lock (authorize), and row/row field rules against the database before admitting operations (admit), plus connection gating (opens):

ts
import { GuardSync } from 'foldkit-guard/sync'
import { databaseLayer } from 'foldkit-remote-drizzle'
import { EditableEntity } from 'foldkit-sync/entity'
import { journalExchange } from 'foldkit-sync/journal'

// Edits to titles: a member with a Read rule of its own could not be one.
const TodoEdits = EditableEntity.make(Todo, { members: ['title'] })

// Who may open it: its readers, each in the rows' Read rule. Only an admin reads every todo.
const Edits = GuardSync.document(TodoEdits, { readers: [G.isAdmin] })

// Under the journal's lock: the principal's own guards, for the Sync contract's authorize.
const authorize = { EditedTodos: GuardSync.authorize(Policy, Edits) }

// Each exchange, as its principal: whether they may open it, and each edit against its row.
journalExchange({
  sync,
  journal,
  principal,
  opens: GuardSync.opens(Policy, Edits, principal),
  admit: operation =>
    GuardSync.admit(Policy, Edits, { principal, source: TodoSource, changesOf })(operation).pipe(
      Effect.provide(databaseLayer(db)),
    ),
})
  • authorize evaluates principal guards synchronously for row Update and changed member rules.
  • admit loads each target row through the guarded source and checks row and member Update rules before and after all edits in the operation.
  • GuardSync.document requires one shared audience (readers must match top-level principal guards in the Entity's Read rule; edited fields must lack per-member Read rules and always rules).
  • Presence sockets gate connections with Sync.presence.serve(socket, hub, { peerId, opens: GuardSync.opens(Policy, Edits, principal) }).