Sync / foldkit-durable

Validation and authorization

validate and authorize run inside the append transaction while the write lock is held, so keep them pure, synchronous or local, and free of external Effect services:

ts
import { InvalidOperationError } from 'foldkit-durable'

const hooks: Pick<JournalOptions<Operation, Snapshot, Principal>, 'validate' | 'authorize'> = {
  // Structural checks: throw, or fail with InvalidOperationError.
  validate: ({ operation }) =>
    operation.title.length === 0
      ? Effect.fail(new InvalidOperationError({ message: 'title is empty' }))
      : Effect.void,
  // Policy: true, false, a refusal with its reason, or an Effect of either.
  authorize: ({ principal, operation }) =>
    principal.actorId === operation.opId.split(':')[0] || {
      allowed: false,
      reason: 'an operation must be committed by the tab that created it',
    },
}

A refused authorize check fails with OperationRejectedError (carrying reason as message). The principal comes from your transport authentication rather than the operation payload, preventing callers from spoofing another actor.

Laws. judge runs after reduce over { before, after } and the stamped operation, returning true or the first broken law (OperationRejectedError with rule and path):

ts
const capped: Pick<JournalOptions<Operation, Snapshot, Principal>, 'judge'> = {
  judge: ({ after }) =>
    after.todos.length <= 100 || {
      rule: 'atMost100Todos',
      message: 'A list holds 100 todos',
      path: ['todos'],
    },
}

judge checks after strictly regardless of before, so a document already breaking a newly added law accepts only operations that repair it. A throwing judge or reduce produces InvalidOperationError. Sync contracts pass laws here via journalContract().

Replica binding. When replicaId is provided (supplied by journalContract()), the first commit from a replica binds that replica id to its actor for that document, and later commits from other actors using that replica id are refused before validate. Use unguessable or server-assigned replica ids. If migrating an older compacted database created before schema 6, supply legacyReplicaId so existing ids can be recovered.