Protected application updates
Authorize and commit one PostgreSQL resource/action update with a durable receipt.
createPostgresProtectedWriteAdapter() runs a resource/action authorization check and your
application SQL callback in one adapter-owned SERIALIZABLE PostgreSQL transaction. Before committing,
it seals the authority used by the decision and records a durable receipt and outbox event atomically
with the application change. This is a local, embedded TypeScript API.
The Python, Go and Rust HTTP clients call the Sharing HTTP API. Their requests do not extend this SQL transaction across processes or provide a remote protected-write callback.
What the callback may change
This API admits only a resource-wide action. A field-only grant cannot admit its raw SQL callback.
The callback must advance the resource to the intent’s postVersion while retaining its incarnation,
ancestry, owner and sharing state. Changes to those authorization boundaries fail the postcondition
and roll back. Use the lifecycle API for deletes and moves.
For a declared field patch with before/after policy enforcement, use managed updates.
The application owns the SQL, input validation and meaning of the payload. Rolebook captures and hashes
payload for durable idempotency; it does not map payload fields to columns, inspect arbitrary SQL
for field safety, or enforce a managed field-level post-state policy. Resource/action authorization
is not permission to treat opaque SQL as a field-mediated update. SQL remains trusted application code:
confine the callback to the intended mutation and obey every participating source writer’s revision
and fence contract. Arbitrary SQL that bypasses that contract is not made safe by SERIALIZABLE.
Bind the existing instances
Use the same createPgExecutor(pool) for the resource adapter and policy store, and configure the
matching createPostgresPolicyFence. Pass the original PostgreSQL Sharing adapter and the
createVersionedSharing() instance built with it. Reconstructed structural copies cannot supply
transaction authority.
Configure the resource adapter with both fences returned by createPostgresLocalIdentityProjection():
lockEligibleSubjects and revalidateAuthorizationFacts. Its identity resolver reads the complete
local projection through the transaction. See authorization fences.
import type { SharingResourceConfigurations, VersionedResourceSharing } from "@rolebook/sharing";
import {
createPostgresLocalIdentityProjection,
createPostgresProtectedWriteAdapter,
type PostgresSharingAdapter,
} from "@rolebook/sharing-postgres";
const projection = createPostgresLocalIdentityProjection({
table: ["app", "authz_identity_projection"],
});
// These original instances were configured with the same checked executor,
// policy fence and both projection fences described above.
declare const sharingAdapter: PostgresSharingAdapter;
declare const versionedSharing: VersionedResourceSharing<SharingResourceConfigurations>;
const protectedAdapter = createPostgresProtectedWriteAdapter({
adapter: sharingAdapter,
sharing: versionedSharing,
identity: projection.identity,
environmentId: "production",
authorityEpoch: "installation-epoch-1",
journalPrefix: "app_authorization",
maxLifetimeMs: 5_000,
});
const scoped = protectedAdapter.forScope({
tenantId: "workspace_1",
actor: { type: "user", id: "user_123" },
});
declare const incarnationId: string;
declare const nextVersion: string;
const intent = {
resource: { type: "document", id: "document_1" },
incarnationId,
action: "update",
idempotencyKey: "rename-document_1-once",
payload: { title: "New title" },
postVersion: nextVersion,
};
const outcome = await scoped.withAuthorizedTransaction(intent, async (guard) => {
const changed = await guard.executor.query(
`UPDATE app.document SET title = $1, version = $2
WHERE tenant_id = $3 AND id = $4 AND version = $5`,
["New title", nextVersion, "workspace_1", "document_1", guard.resourceVersion],
);
if (changed.rowCount !== 1) throw new Error("Update conflict");
return { version: nextVersion };
}); The callback must return JSON-compatible data, including an explicit value rather than undefined.
Every callback query uses guard.executor and must finish before the callback returns. The handle
expires at callback completion, before authority sealing begins. Do not issue transaction control,
use another executor, alter fence settings or perform external effects inside the callback.
Complete local identity authority
The projection is application-owned, with a primary key on (tenant_id, subject_type, id):
| Column | PostgreSQL type | Meaning |
|---|---|---|
tenant_id, subject_type, id | text NOT NULL | Authorization namespace and actor identity. |
eligible | boolean NOT NULL | Whether the subject remains eligible. |
revision | bigint NOT NULL | Revision of the complete projection row. |
assignments, groups | jsonb NOT NULL | Complete arrays, including empty sets. |
attributes | jsonb NOT NULL | Complete policy-visible subject attributes. |
expires_at | nullable timestamptz | Earliest validity boundary of all represented facts. |
Every relevant writer must update this row and advance its revision, including empty/nonempty group and assignment transitions. Facts in additional unfenced tables are outside this contract. The adapter makes no claim about freshness relative to an external identity provider. The scope may be an application authorization namespace; it need not represent a SaaS organization.
The decision metadata records separate policy, tenant-role, sharing and identity/projection
revisions. A policyVersion string alone is not the complete authority key. Expiry is checked in SQL
against the advancing database clock at the common seal, not at an exact commit wall-clock instant.
Ordinary Sharing test clocks do not override protected-write database time.
Migrations and deployment ownership
Run the journal migration through your application’s migration owner before serving protected writes. It is repeatable and validates existing table shape; incompatible schemas fail closed. It is not run implicitly by adapter construction. Resource, policy and projection setup remain separate prerequisites.
import {
applyPostgresMigrations,
createProtectedWriteMigrations,
type ParameterizedSqlExecutor,
} from "@rolebook/sharing-postgres";
declare const executor: ParameterizedSqlExecutor;
await applyPostgresMigrations(
executor,
createProtectedWriteMigrations({ tablePrefix: "app_authorization" }),
); Timeouts, retry and uncertain commits
No transaction or callback is automatically retried. Preserve serialization (40001), deadlock
(40P01) and timeout errors for application policy. A caught query failure still aborts the operation.
The transaction deadline rejects late guarded SQL and bounds SQL statement/lock waits; cancellation
of JavaScript work is cooperative through guard.signal. Pool acquisition and initial driver setup
precede that deadline, and COMMIT follows it. Also configure the pool’s connectionTimeoutMillis and a request deadline.
For COMMIT_OUTCOME_UNKNOWN, call scoped.lookupReceipt(theExactOriginalIntent) on a fresh connection.
A matching receipt proves the prior committed result. Absence alone does not prove an in-flight commit
cannot succeed. An exact replay returns its durable receipt without invoking the callback; reuse of
the key with a changed intent conflicts. Receipt lookup is a trusted server operation bound to the
environment, namespace and actor, and does not replace request authentication.
Retain receipts for the complete retry/reconciliation horizon. Purging one ends its durable replay guarantee. Operators own recovery policy, retention and dead-letter administration; these are not provided as console routes by this API.
Deliver committed outbox events
createPostgresProtectedWriteOutbox({ executor, tablePrefix, environmentId }) exposes
claim({ limit, leaseMs }) and acknowledge(deliveryToken) for a separate worker. Deliver after commit,
deduplicate the stable eventId at the sink, and acknowledge only after successful delivery using
the exact returned token. Delivery is at least once; an expired or superseded lease cannot acknowledge
a later claim, and tokens are bound to the environment.
The committed journal/outbox event is not automatically added to Sharing’s existing listAudit()
feed, the console’s audit routes, or an external audit sink. Wire those consumers deliberately. Worker
scheduling, delivery, retention and operational recovery remain application responsibilities.
See the API reference for exact signatures
and error types. The @rolebook/sharing/internal/transaction-runtime path is a first-party implementation
boundary, not a supported application API.
Scoped outcome lookup and worker recovery
For a server route that already knows the authenticated actor, tenant and original idempotency key, use the receipt factory with the opaque route from the protected-write adapter:
import {
createPostgresProtectedWriteAdapter,
createPostgresProtectedWriteReceipts,
createPostgresProtectedWriteOutbox,
type ParameterizedSqlExecutor,
} from "@rolebook/sharing-postgres";
declare const journalExecutor: ParameterizedSqlExecutor;
declare const protectedWrites: ReturnType<typeof createPostgresProtectedWriteAdapter>;
// These values must come from authenticated server context, after application access checks.
declare const authenticatedScope: {
tenantId: string;
actor: { type: string; id: string };
};
const receipts = createPostgresProtectedWriteReceipts({
receiptRoute: protectedWrites.receiptRoute(),
});
const committedOutcome = await receipts.forScope(authenticatedScope).lookup({
idempotencyKey: "rename-document_1-once",
});
const worker = createPostgresProtectedWriteOutbox({
executor: journalExecutor, tablePrefix: "app_authorization", environmentId: "production",
});
const pending = await worker.inspectPending({ limit: 100 });
declare const deliver: (event: { eventId: string; kind: string; payload: unknown }) => Promise<void>;
for (const event of await worker.claim({ limit: 1, leaseMs: 30_000 })) {
try {
await deliver(event); // Destination durably accepts and deduplicates by environment/event ID.
} catch {
await worker.retry(event.deliveryToken, { delayMs: 5_000 });
continue;
}
const acknowledged = await worker.acknowledge(event.deliveryToken);
// false means the lease was lost; delivery may be repeated.
} Key-only lookup reports the original committed result; it does not compare a new proposed
payload. An empty, oversized, or NUL-bearing idempotency key is rejected before a read opens.
schemaVersion is the stored metadata version, not a journal-table schema. A flat batch stays
version 1. An enrolled batch of one update stays version 2. With admission
protected_batch_receipt_floor 2, the default for every tenant and for an upgraded row, a
multi-target enrolled batch stores version 2 from the UTF-16-first target. That one hierarchy
block is evidence for its links[0] target only, not for the other result updates. Floor 3,
set on the admission row after decoders and old writers are drained, records version 3: one
targets entry per result update, each hierarchy block evidence for that target and not a
capability. There is no top-level hierarchy and no separate control command. Select the entry
whose resource matches the result update. Apply the admission migration first. If the receipt-floor column is
missing, admission reads return HIERARCHY_UNAVAILABLE with reason profile_mismatch. Running it again leaves existing rows at floor 2. An old binary cannot
enforce a column it does not know. A serialization failure while opening an enrolled batch is
HIERARCHY_UNAVAILABLE / serialization_conflict. A floor outside 2 or 3, or a floor that
changes at the final fence, is HIERARCHY_UNAVAILABLE / protocol_floor.
An enrolled tenant passes the current gate in that checked read before any journal
access: the adapter port, captured authority epoch, current admission and bootstrap, and whether
this resource type is enrolled. A successful gate returns the stored outcome verbatim, or
undefined when no row matches. A refused gate — missing port, epoch mismatch, quarantine,
corrupt admission, or a type that is not enrolled — throws and does not read the journal, so the
refusal discloses neither a receipt nor a miss. Use lookupReceipt, lookupManagedReceipt or
lookupManagedUpdatesReceipt with the exact original intent for retry validation. undefined
after a successful gate means not observed, not proof that an uncertain transaction cannot still
commit. Never mint a new key solely because lookup is empty.
Inspection is an oldest-pending snapshot (limit 1–1000), including leased rows and excluding
delivered rows. It does not decode payloads, so a poison payload remains visible. Retry requires
the current unexpired claim and a delay of 0–300000ms; it immediately invalidates the old token.
Stale, expired, delivered and foreign-environment tokens return false. Generation counters also
advance on retry, so they are not exact attempt counts. Restrict these operations to trusted
workers/operators; they do not authenticate callers. A deferred retry appears as leased until
its database deadline, even though the previous worker has released ownership.
Delivery is at least once. ACK only after durable acceptance; destination effects must be
idempotent by (environmentId, eventId). Executor errors propagate. If a worker crashes or cannot
release its lease, normal claim recovers after expiry. Size batches and leases to finish delivery
before expiry; lease renewal is not provided. Do not hold business transactions during delivery.
Receipts and all outbox rows are retained indefinitely, including delivered rows. Explicit quarantine/requeue is described below; deletion, scheduler and HTTP/console routes remain outside this API. Permanent failures remain pending unless explicitly quarantined. Exhausted generation counters remain visible but cannot be reclaimed; operators must investigate rather than reset fencing history.
Quarantine and explicit operator recovery
Stop and drain all old outbox workers before running the explicit protected-write migrations,
then start only upgraded workers. The additive <prefix>_dead_v1 table leaves the original event
and receipt schemas intact. Old workers do not consult quarantine state, so mixed-version delivery
or rollback to old workers with active quarantines is unsupported. New worker operations fail
closed when the side table is missing. Apply the existing migration API through the application’s
migration owner; construction does not migrate. PostgreSQL’s generated migration step now ends in
:v1:quarantine-v1:relation-admission-v1:operator-history-v1; SQLite validates and adds the new side-table definition.
The PostgreSQL migration locks and requires all three journal relations to be ordinary permanent
tables without inheritance in either direction, partitions, RLS, rewrite rules or user triggers.
Foreign tables and views are rejected before shape DDL. The new step name makes runners that
track applied names revalidate earlier installations. Trusted schema ownership remains required
after migration; changing DDL afterwards is outside this runtime contract.
The environment-wide operator below must be authenticated and authorized by your application. This uses an exact-event inspection lease so even a payload that normal claim cannot decode can be quarantined. It never steals an existing lease; allow that lease to expire first.
import { createPostgresProtectedWriteOutbox, type ParameterizedSqlExecutor } from "@rolebook/sharing-postgres";
declare const executor: ParameterizedSqlExecutor;
const operator = createPostgresProtectedWriteOutbox({
executor, tablePrefix: "app_authorization", environmentId: "production",
});
declare const eventId: string;
const lease = await operator.claimForInspection({ eventId, leaseMs: 30_000 });
if (lease) {
const quarantine = await operator.quarantine(lease, { reason: "destination-rejected-event" });
// undefined means the lease is no longer eligible; inspect current state before proceeding.
}
const deadLetters = await operator.inspectDeadLetters({ limit: 100 });
// In a separate authorized recovery action, after resolving the cause:
declare const approvedForRequeue: boolean;
const selected = deadLetters.find((event) => event.eventId === eventId);
if (approvedForRequeue && selected) {
const requeued = await operator.requeue(selected.quarantineToken);
// true makes the original event available for ordinary claim; it does not deliver it.
} Quarantine requires a current unexpired token and a nonblank 1–1024-character reason with no NUL; it advances the generation, clears the lease and persists the quarantine atomically. Never put credentials or whole payloads in the reason. Requeue requires the exact active quarantine token and advances the generation again. Old ACK, retry and operator tokens cannot act on later state. Foreign-environment tokens are rejected. Worker limits remain 1–1000 records and 1–300000ms leases. Quarantine reserves headroom for requeue and a subsequent claim; generations at or above 9223372036854775805 cannot be quarantined. Counters are never reset or wrapped.
Dead-letter inspection omits payload decoding and returns immutable identity, kind, reason, time and token. It is a bounded oldest-active snapshot, not pagination or an authentication boundary. The side row retains the latest quarantine/requeue state per event; it is not a full history of operator actions; the separate history log records successful post-upgrade transitions. Pending inspection excludes quarantined events; use dead-letter inspection for them. Neither operation changes or deletes the original payload or receipt.
A crash before quarantine leaves ordinary lease expiry/reclaim in effect. A committed quarantine persists until explicit requeue; inspection recovers its token after a lost acknowledgment. An absent active quarantine is not proof of delivery. Serialization/busy/connection failures propagate without automatic replay. PostgreSQL can commit a normal claim’s lease before payload decoding fails; SQLite rolls its claim transaction back. Inspection leasing must respect any remaining live lease in either case.
Quarantine cannot recall an external delivery already in flight. Destinations must continue to
deduplicate by (environmentId, eventId) across requeue cycles. Requeue does not repair malformed
payloads: resolve the producer/schema/decoder or destination cause first. No payload-edit, scheduler,
automatic retry policy, route/console integration, retention expiry or deletion is added.
For callback-free single-resource deletion, use managed deletion. The raw update callback still cannot delete resources.
Retained operator-action history
After the explicit operator-history migration, every successful quarantine/requeue atomically
appends a record to <prefix>_actions_v1. An append failure rolls back the transition. Stale,
foreign, expired and exhausted tokens do not create successful records. Original events and
receipts remain unchanged. The log is append-only through the library API, not tamper-evident
against database administrators; there is no pruning, failed-attempt log or administrative UI.
Bind an optional operator: { type, id } when constructing the outbox worker. The factory copies
this application-attested identity; authenticate and authorize it in the application first.
Existing factories without an operator record null, never an inferred or authenticated actor.
Both identity fields must be nonblank strings of at most 1024 characters with no NUL.
inspectOperatorActions({ eventId, limit, afterGeneration? }) returns immutable records for
that event in the factory’s environment. Limit is 1–1000. Records include stable actionId,
environmentId, eventId, resulting decimal generation, action, nullable operator, nullable
reason and ISO recordedAt. Requeue reasons are null. Times describe the transition inside the
transaction, not exact COMMIT time. The exclusive cursor defaults to "0"; use the last returned
generation for the next page. Pagination follows numeric generation, so clock changes cannot skip
records. Gaps are normal. This is a live per-event traversal, not a frozen or cross-event feed.
Malformed records fail closed; inspection does not decode the event payload.
Stop/drain old operator binaries, run the explicit migration, then start upgraded workers only. The additive table retains previous schemas and data. History starts at this rollout: existing quarantines have no fabricated historical action. Their later requeue is recorded. An empty history cannot prove there were no pre-upgrade actions. Mixed-version operators can leave gaps and are unsupported. Record the rollout boundary in application operations records.
import { createPostgresProtectedWriteOutbox, type ParameterizedSqlExecutor } from "@rolebook/sharing-postgres";
declare const executor: ParameterizedSqlExecutor;
// Obtain this identity only after application authentication and operator authorization.
declare const trustedOperator: { type: string; id: string };
declare const eventId: string;
const worker = createPostgresProtectedWriteOutbox({
executor, tablePrefix: "app_authorization", environmentId: "production",
operator: trustedOperator,
});
const firstPage = await worker.inspectOperatorActions({ eventId, limit: 100 });
const last = firstPage.at(-1);
if (last) {
const nextPage = await worker.inspectOperatorActions({
eventId, limit: 100, afterGeneration: last.generation,
});
} Stored-text fidelity in managed operations
Managed updates, batch entries, deletion pre-state and moves validate stored text before calling the application resource projection or evaluating policy. The check covers the complete configured projection, including keys, versions and policy attributes that are not writable patch fields. A value that the driver has shortened or otherwise changed fails closed; it is never silently normalized into a different policy value. Generated-write post-state and batch final reloads use the same loader. Rejection rolls back the business write and its receipt/event together. Exact retained receipt replay still occurs before current schema or authorization checks.
PostgreSQL compares SQL string scalars returned as driver strings to independently queried UTF-8 hex of the same columns while holding the existing row/schema locks. The evidence preserves padded character values and default JSON scalar strings. Normal PostgreSQL text values are preserved; a configured lossy string decoder is rejected. PostgreSQL itself rejects embedded NUL text storage. Non-string driver values retain the existing scalar-codec and application projection contracts; this is not a new arbitrary-type codec. SQL evidence and the executor remain trusted: a custom executor that falsifies both values and their evidence cannot be verified by this guard.
This is a string-valued projection guarantee. Custom parsers that turn SQL TEXT into null, objects or other non-string representations are outside it and remain trusted application configuration. The guard does not claim to validate arbitrary parser behavior.