Access-change webhooks
Notify other systems, with signed HTTP requests, when access to a resource changes.
Rolebook can POST a signed JSON request to an endpoint you configure each time access to a resource changes. Delivery reads only committed audit rows, so a change is never announced before its transaction commits, and a rolled-back change is never announced at all. It runs outside the authorization transaction and never changes it.
Delivery is at least once. The same change can arrive more than once (after a timeout, a lost
acknowledgement or a requeue), always with the same rolebook-webhook-id. Receivers must drop
duplicates by that ID. Rolebook does not claim exactly-once delivery.
Events
One request is sent for each audit event with one of these actions. Every other audit action
(invitation.revoked, resource.initialized, resource.deleted, resource.moved) is not sent.
type | Sent when |
|---|---|
member.granted | A member is granted a role. |
member.role_changed | A member’s role changes. |
member.revoked | A member is removed. |
ownership.transferred | Ownership moves to another subject. |
invitation.issued | An invitation is created. |
invitation.consumed | An invitation is accepted. |
Audit rows written before the delivery migrations ran have no delivery position and are never sent. Delivery starts with the first change committed after them, whichever release wrote it.
Payload
The body is JSON. event is exactly the Sharing HTTP API’s audit event
(WireAuditEvent); the body is built field by field from that allow-list, so an invitation
token, a token digest, an idempotency key, incarnation or lineage data, and any field outside the
allow-list are never sent.
{
"id": "evt_5f0c1d7a9e2b4c6d8f0a1b2c3d4e5f60",
"type": "invitation.issued",
"environmentId": "production",
"event": {
"id": "audit_01",
"tenantId": "org_123",
"resourceType": "project",
"resourceId": "project_42",
"actor": { "type": "user", "id": "user_1" },
"action": "invitation.issued",
"invitationId": "inv_7",
"occurredAt": "2026-11-22T12:00:00.000Z"
}
} id is stable for one audit event: evt_ and 32 hex characters derived from the resource type,
tenant, resource ID and audit event ID. Every retry and requeue sends the same bytes with the same
id. occurredAt is the instant the sharing module stamped; it is not the delivery order (see
ordering).
Signature
Each request carries three headers:
| Header | Value |
|---|---|
rolebook-webhook-id | The body’s id. |
rolebook-webhook-timestamp | When this attempt was signed, in Unix seconds. |
rolebook-webhook-signature | v1= and the lowercase hex HMAC-SHA-256 of the input. |
The signed input is <id>.<timestamp>.<raw body>, keyed by the UTF-8 bytes of the endpoint’s
secret. Secrets are 32–512 characters; both the sender and the verifier refuse shorter ones. The
verifier accepts several secrets, and the signature header may carry several space-separated
v1= values, so a receiver can accept the old and new secret while you rotate. The sender signs
with one secret per endpoint.
Verify with verifyAccessChangeWebhook from @rolebook/http/webhooks. Pass the raw body before
any parsing, preferably as bytes: they are copied once, refused over 64 KiB, and decoded as strict
UTF-8, so a byte sequence that does not decode, or a byte-order mark, is not silently rewritten.
The verifier reads the body exactly once and returns the event it authenticated. It compares
signatures in constant time and rejects a timestamp more than 300 seconds (configurable up to
3600) from the receiver’s clock in either direction.
import { verifyAccessChangeWebhook } from "@rolebook/http/webhooks";
declare const secret: string;
declare const inbox: {
/** Records the ID and applies the change in one transaction; false when the ID was recorded. */
applyOnce(id: string, change: { type: string; resourceId: string }): Promise<boolean>;
};
export async function receive(request: Request): Promise<Response> {
const declared = Number(request.headers.get("content-length") ?? "0");
if (!Number.isFinite(declared) || declared > 64 * 1024) return new Response(null, { status: 413 });
const body = new Uint8Array(await request.arrayBuffer());
const result = await verifyAccessChangeWebhook({ secret, headers: request.headers, body });
if (!result.ok) return new Response(null, { status: 400 });
// At least once: the same id can arrive again, even concurrently. Record it and apply the
// change atomically, so a duplicate or a crash between the two never applies it twice.
await inbox.applyOnce(result.id, {
type: result.webhook.type,
resourceId: result.webhook.event.resourceId,
});
return new Response(null, { status: 204 });
} The failure reasons are missing-header, malformed-header, stale-timestamp,
invalid-signature and malformed-body. Answer any 2xx status once the change is safely
recorded; anything else is a failed attempt. A receiver that takes webhooks from several
environments deduplicates on environmentId and id together.
Storage
Delivery state lives in its own tables, apart from the audit tables: the tenant each subscription
is bound to, a cursor per subscription and resource type, and a queue of entries. Draining never
updates or deletes an audit row. Delivery writes to an audit table in only two places: the SQLite
trigger below sets delivery_seq as a row is inserted, and the PostgreSQL operator action
rebaseline clears every position after a logical restore. Audit retention
and the sealed auditHistory() cursors work exactly as before.
A queued entry keeps its own copy of the allow-listed event, so retention may remove an audit row once every subscription has queued it. An audit row removed before a subscription drained it is never sent to that subscription. Delivery can fall behind (a receiver that is down does not stop draining, but a failing drain, a stopped worker, or on PostgreSQL a long-running transaction, does), so retention must keep audit rows until every subscription’s cursor is past them, and should keep a margin on top.
Run the migrations as the schema owner.
PostgreSQL. createResourceSharingMigrations gives each audit table the column
delivery_xid (xid8, defaulting to pg_current_xact_id()), in step
<owner>:audit-delivery-position, and the index <audit>_dpos_idx on
(tenant_id, delivery_xid), in step <owner>:audit-delivery-index. The default is a function any
role may call, so an application role that can insert audit rows needs no new privilege, and a
process of the previous release keeps writing rows that will be delivered. Existing rows keep
NULL and the table is not rewritten. The column step takes ACCESS EXCLUSIVE only for those
catalog changes; the index step builds the index under SHARE, which lets reads continue and
makes writes wait for the build. To avoid that pause on a large audit table, create the same index
first with CREATE INDEX CONCURRENTLY <audit>_dpos_idx ON <audit> (tenant_id, delivery_xid); the
step then does nothing. createAccessChangeDeliveryMigrations({ tablePrefix }) creates
<prefix>_access_subscription_v1, <prefix>_access_cursor_v1 and <prefix>_access_delivery_v1.
SQLite. applyResourceSharingMigrations adds the column delivery_seq and its index.
applyAccessChangeDeliveryMigrations(executor, { tablePrefix, resources }) creates the delivery
tables, a per-audit-table position counter <prefix>_access_position_v1, and on each audit table a
trigger that gives every inserted row the counter’s next value, overwriting any position its
writer supplied. The trigger runs in the inserting transaction, under the database write lock, so
positions follow commit order; it fires for a writer of any release; and because the counter only
grows, deleting audit rows never makes a position be used twice. It reads the counter by its key
and updates the new row by its primary key, so its cost does not grow with the table. The
migration seeds each counter above the table’s highest position and every cursor’s, so
reinstalling after a counter row was lost never reuses a position; an insert fails while its
counter row is missing. Managed deletion and movement admit exactly this generated trigger on the
audit table, and still refuse any other or altered trigger there. They hold the counter table to
the same rules as the audit table: a permanent table in main, unshadowed, without triggers.
A cursor records the audit table it reads. Two audit tables that expose the same resource type
need stores with different delivery prefixes, and choosing them is the operator’s responsibility.
The store diagnoses a clash only per subscription: when a subscription’s cursor for a resource
type was recorded by a store over another audit table, a drain is refused with code
source-conflict. When the two stores’ first drains race, the conflict is reported at the latest
on the next drain that reads a page. Two stores whose
subscriptions never share an ID are not detected.
Upgrade order on SQLite: an instance of an earlier release refuses managed deletes and moves
once the trigger exists, so upgrade every instance first, then run
applyAccessChangeDeliveryMigrations.
The queue grows by one row per change and subscription. Each delivery pass deletes delivered
entries older than deliveredRetentionMs (one day by default), at most pruneLimit per
endpoint; store.pruneDelivered does the same on demand. Dead-lettered and undelivered entries
are never pruned.
Run it in your application
createWebhookDelivery from @rolebook/server/webhooks validates everything at construction and
throws WebhookConfigurationError before any storage or network call. Each runOnce() drains
each endpoint’s tenant into its queue, runs one bounded pass of the shared
outbox delivery worker, and prunes delivered entries. run()
repeats passes until its signal aborts, and gives each pass’s report to onReport: a stage that
throws is listed in the endpoint’s failed ("drain", "delivery" or "prune") and explained
in errors (see retries and dead letters). A failed drain does not
stop the delivery of entries already queued.
import { createWebhookDelivery } from "@rolebook/server/webhooks";
import {
createPostgresAccessChangeDeliveryStore,
type ParameterizedSqlExecutor,
type PostgresResourceDescriptor,
} from "@rolebook/sharing-postgres";
declare const executor: ParameterizedSqlExecutor;
declare const projects: PostgresResourceDescriptor;
declare const crmSecret: string;
declare const log: (report: unknown) => void;
const store = createPostgresAccessChangeDeliveryStore({
executor,
tablePrefix: "app",
environmentId: "production",
resources: [projects],
});
const delivery = createWebhookDelivery({
store,
endpoints: [
{ id: "crm", tenantId: "org_123", url: "https://hooks.example.com/rolebook", secret: crmSecret },
],
});
const stop = new AbortController();
void delivery.run({
signal: stop.signal,
intervalMs: 1_000,
onReport: (report) => {
if (report.endpoints.some((endpoint) => endpoint.failed)) log(report);
},
}); createSqliteAccessChangeDeliveryStore takes the same options with a SQLite executor.
Configuration from environment variables
webhookDeliveryFromEnv({ env, store }) is the startup helper for a server process. It returns
undefined, and nothing runs, when no ROLEBOOK_WEBHOOK_* variable is set. When any is set, the
URL, secret and tenant are required and every value must validate, or it throws
WebhookConfigurationError, naming the variable and never its value.
webhookConfigurationFromEnv checks presence, format and the ROLEBOOK_WEBHOOK_INTERVAL_MS
range. The other numeric ranges are checked when the delivery is built, and
webhookDeliveryFromEnv reports those failures under the variable’s name too.
| Variable | Meaning | Default |
|---|---|---|
ROLEBOOK_WEBHOOK_URL | Endpoint URL. Required. | |
ROLEBOOK_WEBHOOK_SECRET | HMAC secret, 32–512 characters. Required. | |
ROLEBOOK_WEBHOOK_TENANT_ID | The one tenant this endpoint receives. Required. | |
ROLEBOOK_WEBHOOK_ENDPOINT_ID | Subscription ID. | default |
ROLEBOOK_WEBHOOK_MAX_ATTEMPTS | Attempts before dead-letter, 1–1000. | 300 |
ROLEBOOK_WEBHOOK_BACKOFF_BASE_MS | First retry delay, 1–300000. | 1000 |
ROLEBOOK_WEBHOOK_BACKOFF_CAP_MS | Largest retry delay, up to 300000. | 300000 |
ROLEBOOK_WEBHOOK_TIMEOUT_MS | Whole-request deadline, 1–60000. | 10000 |
ROLEBOOK_WEBHOOK_MAX_RESPONSE_BYTES | Largest response body read, 0–1048576. | 65536 |
ROLEBOOK_WEBHOOK_DELIVERED_RETENTION_MS | How long a delivered entry is kept, 0–999999999. | 86400000 |
ROLEBOOK_WEBHOOK_INTERVAL_MS | Pause between passes, 10–600000. | 1000 |
The environment ID is the store’s, chosen where you build the store, not read from the environment.
import { webhookDeliveryFromEnv } from "@rolebook/server/webhooks";
import type { AccessChangeDeliveryStore } from "@rolebook/sharing";
declare const store: AccessChangeDeliveryStore;
declare const env: Readonly<Record<string, string | undefined>>;
const configured = webhookDeliveryFromEnv({ env, store });
if (configured) {
const stop = new AbortController();
void configured.delivery.run({ signal: stop.signal, intervalMs: configured.intervalMs });
} Retries and dead letters
A 2xx response is a delivery. Every other outcome is a failed attempt: another status, a redirect,
a response body over the cap, a timeout, or a network error. After failed attempt n the entry
waits min(cap, base × 2^(n−1)) milliseconds and is tried again. With the defaults that is 1 s,
2 s, 4 s, … up to 5 minutes, for 300 attempts: a receiver can be down for about a day before an
entry is dead-lettered. The reason is a fixed code such as
dead-lettered after 300 attempts: http-503; response bodies and exception messages are never
stored. An attempt counts a claim, so a worker that crashes after claiming also uses one.
A dead-lettered entry stays in the queue. It holds back the later changes of its own resource,
so they are never delivered ahead of it, and it does not affect any other resource. List entries
with store.inspectDeadLetters({ subscriptionId, tenantId, limit }). Fix the receiver and put one back with
store.requeue(entry.token), which restarts it with a fresh attempt count and the same id, or
drop it with store.discardDeadLetter(entry.token), which deletes it so the rest of its resource
is delivered; that change is then never sent.
A claimed entry whose stored copy no longer matches its own queue row (it does not decode, or
names another tenant, resource or delivery ID) is dead-lettered on its own with the reason
dead-lettered: the stored entry does not decode, under the same fence as any settlement, and
the rest of the batch is delivered. The pass report lists those delivery IDs in deadLettered.
Its listing has no kind when that is what failed to decode. inspectDeadLetters, requeue and
discardDeadLetter are scoped to the subscription’s tenant, and touch only an entry that is not
leased.
Each pass reports, per endpoint, the stages that threw (failed) and why (errors). A store
refusal keeps its code (foreign-cluster, missing-origin, tenant-bound, tenant-spelling,
invalid-row, missing-privilege, source-conflict) and message, including when it happened while claiming; anything else is
unexpected, without its message. run() passes every report to onReport. Without one, it
writes each failure to console.warn as a fixed sentence for its code (never the store’s own
message), at most once every ten minutes for the same endpoint, stage and code.
Ordering and duplicates
- Per resource, in commit order. Changes to one resource are delivered one at a time, in the order their transactions committed. The next change of a resource is not sent until the previous one is acknowledged; a failing one is retried first, and a dead-lettered one blocks its resource until it is requeued or discarded.
- Across resources, no order. That is the whole guarantee: there is no order across resources, resource types or the subscription as a whole. Different resources are delivered independently and concurrently, up to the batch size, so a later change to another resource can arrive first, including while an earlier change is waiting for a retry.
- Nothing skipped.
occurred_atis the module’s clock, read before the transaction, so two transactions can commit in the opposite order of their timestamps. Delivery does not read by timestamp. On PostgreSQL each audit row records its transaction ID, and a drain reads only rows from transactions older than every transaction still running in the cluster, so a row committed later can never land behind the cursor. An old open or prepared transaction anywhere in the cluster, in any database, holds back every audit row whose transaction ID is at or above its own, for every tenant and subscription, until it ends; watch for old transactions (pg_stat_activity.backend_xid,pg_prepared_xacts). Sharing mutations write at most one access change per resource per transaction and update the resource’s revision underSERIALIZABLE, so for one resource transaction-ID order is commit order. Rows of one transaction are paged by resource and event ID. On SQLite each audit row’s position is assigned under the write lock its transaction holds until it commits. - Duplicates. A crash after the request but before the acknowledgement, a timeout after the
receiver had already processed the request, or a requeue sends the same
idagain. A crash after claiming but before sending loses nothing: the lease expires and the entry is claimed again. A worker whose lease expired can no longer settle the entry; the next claim owns it.
PostgreSQL positions belong to one cluster
Transaction IDs are local to a PostgreSQL cluster. The step that adds delivery_xid to an audit
table also records, in rolebook_access_delivery_origin, one row for that table: the cluster’s
system_identifier and an epoch. Every drain, before it binds a subscription or reads a row,
compares each of its resources’ rows with the cluster it runs on, and refuses with code
foreign-cluster when one differs. A drain that finds a position at or beyond the cluster’s next
transaction ID also refuses, and halts that subscription, so the refusal does not clear itself
once the counter catches up. Entries already queued are still delivered while a drain refuses. A
drain’s queue transaction is SERIALIZABLE and rechecks the table’s epoch and the subscription’s
halt. Under one delivery prefix, a rebaseline that commits alongside it makes it queue nothing.
Under another prefix over the same audit table, a page read before that rebaseline can still be
queued, but its cursor then belongs to an earlier epoch and starts again from changes committed
afterwards on its next drain.
Which action to take depends on how the database got where it is:
| How | Identity | Counter | Action |
|---|---|---|---|
| Physical backup, promoted standby | kept | kept | none |
pg_upgrade | may change | kept | store.adoptCluster() |
pg_dump and pg_restore, logical replication | changes | not kept | store.rebaseline() |
Adopt (adoptCluster) records this cluster for the store’s audit tables and keeps every cursor
and position. Use it only after pg_upgrade or a physical copy: a successful adopt does not prove
the counter is continuous. It refuses, with code foreign-cluster, when any position is at or
beyond the next transaction ID, and when any subscription is halted, because both mean a logical
restore.
Rebaseline (rebaseline) is for a logical restore. Run it after the restore and before the
application writes anything on the new cluster: a change written between the restore and the
rebaseline is not delivered, or is delivered out of order. For the store’s audit tables, in one
transaction, it:
- Queues the outstanding restored changes, in their original order, of every subscription of the store’s environment that exists at that moment, has drained the resource, and has a tenant the tenant column can hold.
- Clears every audit row’s position, for every tenant.
- Advances the tables’ epoch, so every cursor of an earlier epoch, in any store, starts again from changes committed afterwards. Queued entries and the ordinal that orders them are kept.
- Records this cluster, and clears the halts of the store’s environment.
It returns what it did:
subscriptions: how many had at least one change queued.entries: the changes queued.positionsCleared: the audit rows whose position was cleared.rowsSkipped: the restored access changes that did not decode, which are set aside and not queued.
What this does not cover:
-
Subscriptions that do not exist at the rebaseline, including those of another environment or another store over the same tables. Changes committed before the rebaseline are delivered only to subscriptions that existed when it ran. A subscription created later starts from changes committed afterwards.
-
Other stores’ resources. A store over other audit tables keeps refusing until it is rebaselined itself, and its refusal says so.
-
A restore that did not carry the origin row (
missing-origin). A missing row usually means the migration role could not readpg_control_system(), on a database that was never restored: grant it and run the migration again.rebaselinerefuses this case unless called withforce: true, which is only for a real restore.- The recorded epoch. Forced, it records the table at an epoch above every epoch the prefix’s cursors hold and above the current time in milliseconds. That is a large number, by design, so it never meets another prefix’s cursors; do not reset it.
- Cursors at the newest epoch are read from where they stand, so what they already passed is never queued again.
- Cursors at an older epoch start again from the start of the table.
Then the positions are cleared and the epoch advances, as in any rebaseline.
If that is not acceptable, drain everything before the dump:
- Stop writes.
- Make sure no transaction that was open before the stop is still open or prepared
(
pg_stat_activity,pg_prepared_xacts). Committed changes behind such a transaction are not yet visible to a drain, socaughtUpcan be true while they are still pending. - Drain every subscription until
caughtUp.
rebaseline returns rebaselined: false and changes nothing when the store’s positions already
belong to this cluster and no subscription is halted. Pass force: true to run it anyway; discarded
and pruned entries are not brought back.
Privileges, per action:
| Action | Needs |
|---|---|
| Drain and deliver | SELECT on the audit tables and on rolebook_access_delivery_origin; SELECT, INSERT, UPDATE and DELETE on the three delivery tables; execute on pg_control_system() (granted to PUBLIC by default) |
adoptCluster | The above, plus UPDATE on rolebook_access_delivery_origin |
rebaseline | The above, plus UPDATE on the audit tables (it clears delivery_xid) and INSERT on rolebook_access_delivery_origin |
| Sharing migration | Its usual privileges, plus execute on pg_control_system() and INSERT on rolebook_access_delivery_origin |
Run the operator actions with the schema owner’s executor. The drain runs on the primary. In a
drain, every permission error is reported as missing-privilege, and the message names the
grants a drain needs. That covers reading the cluster identity and the origin table, and every
later step: the audit tables, the delivery tables and the queue transaction. adoptCluster and
rebaseline also report missing-privilege when they cannot read the cluster identity, naming
the grant, or lock and update the origin table, naming the grant and the schema owner’s executor;
their other
permission errors, and those of the worker port’s claim and settlement calls, surface as they
are. If the migration role may not read pg_control_system()
or insert into the origin table, the migration still succeeds but leaves the origin unrecorded,
and delivery refuses with code missing-origin until the grant is made and the migration runs
again.
Outbound safety
- The URL is validated at startup:
https:only, orhttp:for a loopback host (localhost,127.0.0.0/8,[::1]). URLs with credentials or a fragment are refused. - Redirects are not followed; a 3xx response is a failed attempt.
- Each request has a deadline (
requestTimeoutMs), and at mostmaxResponseBytesof the response body is read. - Secrets are never logged, returned by
describe(), or included in reports or error messages.
The URL is an operator decision. Nothing here blocks private or link-local addresses (such as
10.0.0.1 or 169.254.169.254), loopback over https:, or a public name that resolves to a
private address, and nothing pins the address at connect time. That is fine for a URL you
configure yourself. Do not accept endpoint URLs from tenants unless every request leaves through
an egress proxy or network policy that enforces which addresses may be reached.
Tenant and environment isolation
A subscription is bound to the tenant of its first drain, for every resource type at once. A
drain for another tenant throws (reported as failed: ["drain"]), and the worker port is bound to
the endpoint’s tenant: it claims only that tenant’s entries, and the sender refuses, as a dead
letter with reason tenant-mismatch, any entry whose event names another tenant. So reusing an
endpoint ID for another tenant never sends the first tenant’s changes to it. On PostgreSQL a
drain also compares the tenant ID exactly as stored: where the tenant column is a uuid, another
spelling of the same value (such as upper case) is refused with code tenant-spelling, so use the
canonical lowercase form. Every subscription,
cursor and queue row carries the store’s environment ID; a store for another environment never
claims, settles or requeues them, and the environment ID is part of every body and of the signed
bytes. Give each environment its own audit tables: two environments that drain the same audit
table each deliver its changes under their own environment ID.
@rolebook/http/webhooks
The body, signature and verification helper. This entry has no runtime dependency on @rolebook/sharing and needs only Web Crypto.
serializeAccessChangeWebhook
function serializeAccessChangeWebhook(input: {
readonly id: string;
readonly environmentId: string;
readonly event: unknown;
}): string; The exact request body for one access change. Only allow-listed fields are copied, in a fixed order, so the same input always gives the same string. Throws a TypeError for an event, delivery ID or environment ID that does not validate, or an action that is not an access change.
timingSafeEqualBytes
function timingSafeEqualBytes(left: Uint8Array, right: Uint8Array): boolean; Constant-time comparison of two byte arrays; arrays of different lengths are unequal.
signAccessChangeWebhook
function signAccessChangeWebhook(input: {
readonly secret: string;
readonly id: string;
readonly timestamp: number;
readonly body: string;
}): Promise<string>; The rolebook-webhook-signature value for one request: v1= and the hex HMAC-SHA-256 of <id>.<timestamp>.<body>. Throws on a secret outside 32–512 characters or a negative timestamp.
verifyAccessChangeWebhook
function verifyAccessChangeWebhook(input: {
readonly secret: string | readonly string[];
readonly headers: WebhookHeaderSource;
readonly body: string | Uint8Array;
readonly toleranceSeconds?: number;
readonly now?: () => number;
}): Promise<AccessChangeWebhookVerification>; Checks the signature against every given secret (1–8, for rotation) in constant time, the timestamp against toleranceSeconds (default 300, 1–3600) either side of now, the body size, and that the body is an allow-listed access change whose id matches the header. The body is read once: bytes are copied, size-checked and decoded as strict UTF-8; a string is used as given. Throws on invalid options; answers a failed check with ok: false and a reason.
WEBHOOK_ID_HEADER
const WEBHOOK_ID_HEADER = "rolebook-webhook-id"; Header carrying the stable delivery ID.
WEBHOOK_TIMESTAMP_HEADER
const WEBHOOK_TIMESTAMP_HEADER = "rolebook-webhook-timestamp"; Header carrying the signing time in Unix seconds.
WEBHOOK_SIGNATURE_HEADER
const WEBHOOK_SIGNATURE_HEADER = "rolebook-webhook-signature"; Header carrying one or more space-separated v1= signatures.
DEFAULT_WEBHOOK_TOLERANCE_SECONDS
const DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300; The verifier’s default timestamp tolerance.
MAX_WEBHOOK_TOLERANCE_SECONDS
const MAX_WEBHOOK_TOLERANCE_SECONDS = 3600; The largest toleranceSeconds the verifier accepts.
MIN_WEBHOOK_SECRET_LENGTH
const MIN_WEBHOOK_SECRET_LENGTH = 32; Shortest secret the sender and verifier accept.
MAX_WEBHOOK_SECRET_LENGTH
const MAX_WEBHOOK_SECRET_LENGTH = 512; Longest secret the sender and verifier accept.
MAX_WEBHOOK_BODY_BYTES
const MAX_WEBHOOK_BODY_BYTES: number; Bodies larger than this are refused by the verifier before parsing.
WireAccessChangeWebhook
interface WireAccessChangeWebhook {
readonly id: string;
readonly type: AccessChangeAction;
readonly environmentId: string;
readonly event: WireAuditEvent;
} One request body. event is a WireAuditEvent.
ACCESS_CHANGE_WEBHOOK_TYPES
const ACCESS_CHANGE_WEBHOOK_TYPES: readonly AccessChangeAction[]; The six type values a body can have.
AccessChangeWebhookVerification
type AccessChangeWebhookVerification = {
readonly ok: true;
readonly id: string;
readonly timestamp: number;
readonly webhook: WireAccessChangeWebhook;
} | {
readonly ok: false;
readonly reason: "missing-header" | "malformed-header" | "stale-timestamp" | "invalid-signature" | "malformed-body";
}; The verifier’s answer.
WebhookHeaderSource
type WebhookHeaderSource = {
get(name: string): string | null;
} | Readonly<Record<string, string | readonly string[] | undefined>>; A Headers object or a plain record of header values; names are compared case-insensitively.
@rolebook/server/webhooks
The sender: configuration, URL checks, signing, retry policy and the drain-and-deliver loop.
webhookRetryDelayMs
function webhookRetryDelayMs(attempt: number, baseMs: number, capMs: number): number; The wait after failed attempt attempt (1-based): min(capMs, baseMs × 2^(attempt−1)).
validateWebhookUrl
function validateWebhookUrl(value: unknown, label?: string): string; Validates and normalizes an endpoint URL: absolute, https: or loopback http:, no credentials, no fragment. The error message never echoes the value.
createWebhookDelivery
function createWebhookDelivery(options: WebhookDeliveryOptions): WebhookDelivery; Validates the options and returns the delivery loop. Throws WebhookConfigurationError before any storage or network call.
webhookConfigurationFromEnv
function webhookConfigurationFromEnv(env: Readonly<Record<string, string | undefined>>): WebhookEnvConfiguration | undefined; Reads ROLEBOOK_WEBHOOK_*. Returns undefined when none is set; throws WebhookConfigurationError on a partial or malformed configuration. It checks presence, format and the ROLEBOOK_WEBHOOK_INTERVAL_MS range; the other numeric ranges are checked when the delivery is built (createWebhookDelivery, which webhookDeliveryFromEnv calls and whose errors it reports under the variable’s name).
webhookDeliveryFromEnv
function webhookDeliveryFromEnv(input: {
readonly env: Readonly<Record<string, string | undefined>>;
readonly store: AccessChangeDeliveryStore;
readonly fetch?: typeof fetch;
}): {
readonly delivery: WebhookDelivery;
readonly intervalMs: number;
} | undefined; webhookConfigurationFromEnv followed by createWebhookDelivery with one endpoint. Returns undefined when webhooks are not configured.
WebhookEndpoint
interface WebhookEndpoint {
readonly id: string;
readonly tenantId: string;
readonly url: string;
readonly secret: string;
} One receiver, bound to one tenant of the store’s environment.
WebhookDeliveryOptions
interface WebhookDeliveryOptions {
readonly store: AccessChangeDeliveryStore;
readonly endpoints: readonly WebhookEndpoint[];
readonly maxAttempts?: number;
readonly backoffBaseMs?: number;
readonly backoffCapMs?: number;
readonly requestTimeoutMs?: number;
readonly maxResponseBytes?: number;
readonly batchSize?: number;
readonly leaseMs?: number;
readonly drainLimit?: number;
readonly deliveredRetentionMs?: number;
readonly pruneLimit?: number;
readonly fetch?: typeof fetch;
readonly now?: () => number;
} Delivery options; see the defaults in WEBHOOK_DEFAULTS. leaseMs must exceed requestTimeoutMs by more than one second. deliveredRetentionMs and pruneLimit bound how long delivered entries are kept and how many each pass deletes.
WebhookConfigurationError
class WebhookConfigurationError extends Error {
constructor(message: string);
} Thrown for an invalid configuration. Messages name the option or variable, never its value.
WEBHOOK_DEFAULTS
const WEBHOOK_DEFAULTS: Readonly<{
maxAttempts: 300;
backoffBaseMs: 1000;
backoffCapMs: 300000;
requestTimeoutMs: 10000;
maxResponseBytes: 65536;
batchSize: 16;
leaseMs: 60000;
drainLimit: 100;
deliveredRetentionMs: 86400000;
pruneLimit: 100;
intervalMs: 1000;
}>; Default option values.
WebhookEndpointReport
interface WebhookEndpointReport {
readonly endpointId: string;
readonly enqueued: number;
readonly outcomes: readonly OutboxDeliveryOutcome[];
readonly pruned: number;
readonly failed?: readonly WebhookStage[];
readonly errors?: readonly WebhookStageError[];
readonly deadLettered?: readonly string[];
} One endpoint’s result for one pass. failed lists the stages that threw, in order, and errors says why for each, as a WebhookStageError. deadLettered lists the delivery IDs the store set aside while claiming because their stored entry did not match its row. A failed drain does not stop delivery of entries already queued.
WebhookStage
type WebhookStage = "drain" | "delivery" | "prune"; A stage of one endpoint’s pass, as listed in WebhookEndpointReport.failed.
WebhookStageError
interface WebhookStageError {
readonly stage: WebhookStage;
readonly code: AccessChangeDeliveryErrorCode | "unexpected";
readonly message?: string;
} Why a stage failed. A store’s AccessChangeDeliveryError keeps its code and message, which carry no row data; any other error is unexpected, without its message, which could hold driver or network details.
WebhookDeliveryReport
interface WebhookDeliveryReport {
readonly endpoints: readonly WebhookEndpointReport[];
} The result of one pass, one report per endpoint, in configuration order.
WebhookDelivery
interface WebhookDelivery {
runOnce(input?: {
readonly signal?: AbortSignal;
}): Promise<WebhookDeliveryReport>;
run(input: {
readonly signal: AbortSignal;
readonly intervalMs?: number;
readonly onReport?: (report: WebhookDeliveryReport) => void | Promise<void>;
}): Promise<void>;
describe(): readonly {
readonly id: string;
readonly tenantId: string;
readonly host: string;
}[];
} runOnce runs one pass and rejects when a pass is already running; run repeats passes until its signal aborts, gives each report to onReport (a reporter that throws does not stop the loop), and returns promptly when the signal aborts during a pass; describe lists endpoint IDs, tenants and hosts.
WEBHOOK_ENV
const WEBHOOK_ENV: Readonly<{
url: "ROLEBOOK_WEBHOOK_URL";
secret: "ROLEBOOK_WEBHOOK_SECRET";
tenantId: "ROLEBOOK_WEBHOOK_TENANT_ID";
endpointId: "ROLEBOOK_WEBHOOK_ENDPOINT_ID";
maxAttempts: "ROLEBOOK_WEBHOOK_MAX_ATTEMPTS";
backoffBaseMs: "ROLEBOOK_WEBHOOK_BACKOFF_BASE_MS";
backoffCapMs: "ROLEBOOK_WEBHOOK_BACKOFF_CAP_MS";
requestTimeoutMs: "ROLEBOOK_WEBHOOK_TIMEOUT_MS";
maxResponseBytes: "ROLEBOOK_WEBHOOK_MAX_RESPONSE_BYTES";
deliveredRetentionMs: "ROLEBOOK_WEBHOOK_DELIVERED_RETENTION_MS";
intervalMs: "ROLEBOOK_WEBHOOK_INTERVAL_MS";
}>; The environment variable names webhookConfigurationFromEnv reads.
WebhookEnvConfiguration
interface WebhookEnvConfiguration {
readonly endpoint: WebhookEndpoint;
readonly options: Omit<WebhookDeliveryOptions, "store" | "endpoints" | "fetch" | "now">;
readonly intervalMs: number;
} An environment configuration whose presence, format and interval are checked; its other numeric ranges are checked by createWebhookDelivery.