RolebookDocs

@rolebook/sharing/checkpoints

The exports of the opt-in consistency checkpoint entry point of @rolebook/sharing.

import { ... } from "@rolebook/sharing/checkpoints". An opt-in, server-side consistency foundation: checkpoint capture, comparable-floor registration, an authenticated token codec, and a bounded admission waiter. The main @rolebook/sharing API does not issue or consume checkpoint tokens on its own.

A checkpoint is freshness evidence, never an authorization grant. An admitted result does not replace the normal authorization check, and a later protected write must prove the required floors again inside its own transaction. This foundation does not wire SQL atLeast reads, issue tokens from committed receipts, or provide an operational restore-safety protocol. Applications must handle unavailable results explicitly.

Keep the codec’s keys and trusted state on trusted servers. Signing keys hold 32 to 64 bytes of secret random data. Tokens expire within five minutes (checkpointLimits.maxLifetimeMs), and a positive wait has one deadline of at most five seconds (checkpointLimits.maxWaitMs). The initial profile supports policy, tenant-role, resource-sharing and principal-identity floors. Group-membership floors and tenant-list operations are not supported yet.

Contract

createCheckpointObservationRegistry() records the application’s trusted producer contracts. It cannot establish that a database snapshot or restore process is correct. Comparable revisions are canonical decimal integers, compared exactly.

captureCheckpointPayload

function captureCheckpointPayload(value: unknown): CheckpointPayload;

captureCheckpointContext

function captureCheckpointContext(value: unknown): CheckpointContext;

checkpointFloorKey

function checkpointFloorKey(floor: CheckpointFloor): string;

canonicalCheckpointFloors

function canonicalCheckpointFloors(value: readonly CheckpointFloor[]): readonly CheckpointFloor[];

checkpointCompatibility

function checkpointCompatibility(payload: CheckpointPayload, context: CheckpointContext): "compatible" | "incompatible_checkpoint" | "unsupported_mode";

createCheckpointObservationRegistry

function createCheckpointObservationRegistry(context: CheckpointContext, registrations: readonly CheckpointProducerRegistration[]): CheckpointObservationRegistry;

compareCheckpointFloors

function compareCheckpointFloors(payload: CheckpointPayload, context: CheckpointContext, registry: CheckpointObservationRegistry, snapshot: CheckpointSnapshot, nowMs: number): CheckpointFloorComparison;

checkpointLimits

const checkpointLimits: Readonly<{
  encodedBytes: 8192;
  floors: 64;
  scopeBytes: 512;
  identifierBytes: 128;
  opaqueIdBytes: 256;
  opaqueIdCodeUnits: 128;
  maxDepth: 8;
  maxNodes: 1024;
  maxLifetimeMs: 300000;
  maxClockSkewMs: 30000;
  maxUnixMs: 253402300799999;
  maxWaitMs: 5000;
  maxStaleMs: 60000;
}>;

CheckpointAuthority

interface CheckpointAuthority {
  readonly application: string;
  readonly environment: string;
  readonly tenant: string;
  readonly authoritySet: string;
  readonly restoreEpoch: string;
}

CheckpointPrincipal

interface CheckpointPrincipal {
  readonly type: string;
  readonly id: string;
}

CheckpointOperationScope

type CheckpointOperationScope = {
  readonly kind: "resource";
  readonly resourceType: string;
  readonly resourceId: string;
  readonly incarnation: string;
} | {
  readonly kind: "tenantList";
  readonly resourceType: string;
  readonly listingDomain: string;
};

CheckpointFloor

type CheckpointFloor = {
  readonly domain: "policy";
  readonly scope: {
    readonly kind: "authorityPolicy";
  };
  readonly revision: string;
} | {
  readonly domain: "tenantRoles";
  readonly scope: {
    readonly kind: "tenantRoles";
  };
  readonly revision: string;
} | {
  readonly domain: "sharing";
  readonly scope: {
    readonly kind: "resourceSharing";
    readonly resourceType: string;
    readonly resourceId: string;
    readonly incarnation: string;
  };
  readonly revision: string;
} | {
  readonly domain: "identityProjection";
  readonly scope: {
    readonly kind: "principalProjection";
    readonly projection: string;
    readonly principalType: string;
    readonly principalId: string;
  };
  readonly revision: string;
} | {
  readonly domain: "groupMembership";
  readonly scope: {
    readonly kind: "groupMember";
    readonly projection: string;
    readonly groupType: string;
    readonly groupId: string;
    readonly memberType: string;
    readonly memberId: string;
  };
  readonly revision: string;
};

CheckpointContext

interface CheckpointContext {
  readonly issuer: string;
  readonly audience: string;
  readonly authority: CheckpointAuthority;
  readonly principal: CheckpointPrincipal;
  readonly operationScope: CheckpointOperationScope;
  readonly profile: "local-authority-v1";
}

CheckpointPayload

interface CheckpointPayload extends CheckpointContext {
  readonly schema: 1;
  readonly checkpointId: string;
  readonly issuedAtMs: number;
  readonly expiresAtMs: number;
  readonly floors: readonly CheckpointFloor[];
}

CheckpointProducerRegistration

type CheckpointProducerRegistration = CheckpointFloor extends infer F ? F extends {
  readonly domain: infer D;
  readonly scope: infer S;
} ? D extends "groupMembership" ? never : {
  readonly producerId: string;
  readonly domain: D;
  readonly scope: S;
} : never : never;

CheckpointObservationRegistry

interface CheckpointObservationRegistry {
  readonly [registryBrand]: true;
}

CheckpointObservation

interface CheckpointObservation {
  readonly producerId: string;
  readonly floor: CheckpointFloor;
}

CheckpointSnapshot

interface CheckpointSnapshot {
  readonly context: CheckpointContext;
  readonly mode: "consistentLocalSnapshot";
  readonly snapshotId: string;
  readonly observedAtMs: number;
  readonly validUntilMs: number;
  readonly observations: readonly CheckpointObservation[];
}

CheckpointFloorComparison

type CheckpointFloorComparison = {
  readonly status: "met";
} | {
  readonly status: "unmet";
} | {
  readonly status: "unavailable";
  readonly reason: "unsupported_mode" | "incompatible_checkpoint" | "dependency_unavailable" | "projection_expired";
};

CheckpointContractError

class CheckpointContractError extends TypeError {
  readonly code: "INVALID_CHECKPOINT";
  constructor();
}

Token codec

createCheckpointCodec() takes a trusted clock, issuer, audience, authority namespace, and leased keyring and restore-epoch state. issue({ context, registry, snapshot, ttlMs }) derives floors from registered observations in one application-provided consistent snapshot. verify() authenticates a received token and checks the expected context, key state, epoch and time bounds. Keyring and epoch replacements through replaceTrustedState() need monotone generations. To revoke the last signing key, set signingKeyId to null and mark that key revoked, or remove it, in a newer generation.

createCheckpointCodec

function createCheckpointCodec(options: CheckpointCodecOptions): CheckpointCodec;

CheckpointUnavailableReason

type CheckpointUnavailableReason = "invalid_checkpoint" | "expired_checkpoint" | "incompatible_checkpoint" | "revoked_checkpoint" | "dependency_unavailable" | "epoch_unavailable" | "unsupported_mode" | "projection_expired" | "unmet_floor" | "waiter_capacity_exceeded" | "deadline_exceeded" | "cancelled";

CheckpointResult

type CheckpointResult<T> = {
  readonly status: "ok";
  readonly value: T;
} | {
  readonly status: "unavailable";
  readonly reason: CheckpointUnavailableReason;
};

CheckpointKey

interface CheckpointKey {
  readonly issuer: string;
  readonly keyId: string;
  readonly algorithm: "HS256";
  readonly state: "staged" | "signing" | "verify-only" | "revoked";
  readonly notBeforeMs: number;
  readonly signUntilMs: number;
  readonly verifyUntilMs: number;
  readonly secret: Uint8Array;
}

CheckpointTrustedState

interface CheckpointTrustedState {
  readonly keyring: {
    readonly generation: string;
    readonly observedAtMs: number;
    readonly expiresAtMs: number;
    readonly signingKeyId: string | null;
    readonly keys: readonly CheckpointKey[];
  };
  readonly epochLease: {
    readonly authority: Omit<CheckpointAuthority, "restoreEpoch">;
    readonly restoreEpoch: string;
    readonly generation: string;
    readonly observedAtMs: number;
    readonly expiresAtMs: number;
  };
}

CheckpointCodecOptions

interface CheckpointCodecOptions {
  readonly issuer: string;
  readonly audience: string;
  readonly authority: Omit<CheckpointAuthority, "restoreEpoch">;
  readonly now: () => number;
  readonly trustedState: CheckpointTrustedState;
  readonly clockSkewMs?: number;
  readonly maxInFlight?: number;
  readonly operationTimeoutMs?: number;
}

CheckpointIssueInput

interface CheckpointIssueInput {
  readonly context: CheckpointContext;
  readonly registry: CheckpointObservationRegistry;
  readonly snapshot: CheckpointSnapshot;
  readonly ttlMs: number;
}

CheckpointCodec

interface CheckpointCodec {
  issue(input: CheckpointIssueInput): Promise<CheckpointResult<{
    readonly token: string;
    readonly checkpoint: CheckpointPayload;
  }>>;
  verify(input: {
    readonly token: string;
    readonly expected: CheckpointContext;
  }): Promise<CheckpointResult<CheckpointPayload>>;
  replaceTrustedState(next: CheckpointTrustedState): void;
}

Waiter

createCheckpointWaiter() verifies before admission, before each retry and after a successful probe. Its trusted probe must prove all floors in one snapshot and release storage resources before settling. A zero waitMs makes one attempt under a separate bounded operation timeout. Process-local verification and admission limits reject excess work, and a timed-out or cancelled operation keeps its capacity until the underlying work actually settles.

createCheckpointWaiter

function createCheckpointWaiter(options: CheckpointWaiterOptions): CheckpointWaiterWithDiagnostics;

CheckpointWaiterClock

interface CheckpointWaiterClock {
  now(): number;
  setTimeout(callback: () => void, milliseconds: number): unknown;
  clearTimeout(handle: unknown): void;
}

CheckpointProbeResult

type CheckpointProbeResult = {
  readonly status: "met" | "unmet";
} | {
  readonly status: "unavailable";
  readonly reason: CheckpointUnavailableReason;
};

CheckpointWaiterOptions

interface CheckpointWaiterOptions {
  readonly verifier: {
    verify(input: {
      readonly token: string;
      readonly expected: CheckpointContext;
    }): Promise<CheckpointResult<CheckpointPayload>>;
  };
  readonly probe: (checkpoint: CheckpointPayload, input: {
    readonly signal: AbortSignal;
    readonly remainingMs: number;
  }) => Promise<CheckpointProbeResult>;
  readonly clock?: CheckpointWaiterClock;
  readonly pollMs?: number;
  readonly operationTimeoutMs?: number;
  readonly limits?: {
    readonly total?: number;
    readonly tenant?: number;
    readonly principal?: number;
    readonly verification?: number;
  };
  readonly diagnostics?: CheckpointWaiterDiagnosticsOptions | undefined;
}

diagnostics is optional; see waiter diagnostics. Omitted, run is the original method and nothing is recorded except the live capacity counts.

CheckpointWaiterRequest

interface CheckpointWaiterRequest {
  readonly checkpoint: string;
  readonly context: CheckpointContext;
  readonly waitMs: number;
  readonly signal?: AbortSignal;
}

CheckpointAdmission

type CheckpointAdmission = {
  readonly status: "admitted";
} | {
  readonly status: "unavailable";
  readonly reason: CheckpointUnavailableReason;
};

CheckpointWaiter

interface CheckpointWaiter {
  run(request: CheckpointWaiterRequest): Promise<CheckpointAdmission>;
}

CheckpointWaiterWithDiagnostics

interface CheckpointWaiterWithDiagnostics extends CheckpointWaiter {
  diagnostics(): CheckpointWaiterDiagnostics;
}

What createCheckpointWaiter() returns. CheckpointWaiter itself is unchanged.

Waiter diagnostics

Optional and waiter-local. With diagnostics set, each run call is observed once, on its final public result, through a wrapper that returns the same admission object and rethrows the identical exception without awaiting the observer. admitted in an observation is freshness evidence that the floors were met, never an authorization allow. Durations use a separately captured performance.now, never the waiter clock, and are timing: "unavailable" when it faults. The observer, queue and timeout behave exactly as for sharing diagnostics: one call at a time, bounded FIFO with counted drops, report-only timeout that keeps the slot until settlement, no abort signal, and synchronous CPU work cannot be preempted. At most one observation is delivered per timer turn, so bursts can drop even with a fast observer; totals are updated before queueing and keep counting. Ambient asynchronous context in the observer may belong to another request: never attribute an observation to it or export identifiers read from it.

CheckpointWaiterDiagnosticsOptions

interface CheckpointWaiterDiagnosticsOptions {
  readonly observe?: CheckpointWaitObserver;
  readonly queueLimit?: number;
  readonly observerTimeoutMs?: number;
}

The same strict capture and ranges as SharingDiagnosticsOptions; every failure is TypeError("Invalid checkpoint waiter diagnostics options"), checked after every existing option.

CheckpointWaitObserver

type CheckpointWaitObserver = (observation: CheckpointWaitObservation) => void | PromiseLike<void>;

CheckpointWaitObservation

interface CheckpointWaitObservation {
  readonly type: "checkpoint";
  readonly sequence: number;
  readonly operation: "checkpointWait";
  readonly settlement: "returned" | "rejected";
  readonly result: "admitted" | "unavailable" | "unknown" | "rejected";
  readonly reason: CheckpointUnavailableReason | null;
  readonly timing: "measured" | "unavailable";
  readonly durationMs: number | null;
}

No token, context, authority, tenant, principal, floor, payload or exception text.

CheckpointWaiterDiagnostics

interface CheckpointWaiterDiagnostics {
  readonly scope: "factory-local";
  readonly enabled: boolean;
  readonly capacity: {
    readonly total: number;
    readonly verifying: number;
  };
  readonly totals: {
    readonly admitted: number;
    readonly unavailable: Readonly<Record<CheckpointUnavailableReason, number>>;
    readonly unknown: number;
    readonly rejected: number;
  };
  readonly timingUnavailable: number;
  readonly observation: {
    readonly status: "disabled" | "healthy" | "degraded" | "stalled";
    readonly queueLimit: number;
    readonly queued: number;
    readonly outstanding: 0 | 1;
    readonly completed: number;
    readonly failed: number;
    readonly timedOut: number;
    readonly dropped: number;
  };
}

capacity is read live and is only this waiter’s aggregate occupancy: reserved probe slots and verifications in flight, including work that outlived its caller’s deadline or cancellation and still holds capacity until it settles. Per-tenant and per-principal buckets and their keys never leave the waiter. Not admission state, a distributed limiter, or proof of freshness or reachability.