Connect to Rolebook Console
The connector that lets Rolebook Console, the hosted console, change sharing in your app, through your own Sharing instance and database.
@rolebook/connector connects your application to Rolebook Console, the hosted console. The console sends
signed commands (grant a role, change a role, revoke a member, transfer ownership, issue or revoke an
invitation, explain a decision); the connector checks each one and runs it through your application’s
own Sharing instance, in your database. Your database stays the only place where memberships live.
What the connector does
-
It dials out. The connector opens one outbound WebSocket connection to the console. Your application opens no inbound port.
wss://is required;ws://is accepted only for a loopback host, for local development. -
It checks every command before running it. In this order: the Ed25519 signature against the signing keys you configured, by key ID; the environment the command was signed for; the command’s validity window (expired, issued too far in the future, or a window longer than the console issues for that command: 15 seconds for reads, 60 seconds for changes and previews, 120 seconds for
policy.activate,guardrails.activateandtenantRoles.set); a repeated envelope ID (different bytes answerDUPLICATE_MISMATCH; the same bytes answer a change’s cached result, and are evaluated again for reads and desired-state commands); the capability; whether the console is enabled for the command’s tenant. A clock that returns an invalid date refuses every command. -
It runs changes through the public Sharing API. A change runs as
sharing.forTenant({ tenantId, actor: consolePrincipal }).execute(...). Its idempotency key is derived from the environment ID and the console’s command ID, so two environments never share one. Fences, the delegation ceiling and idempotency are Sharing’s own: the connector grants the console principal nothing. Your identity adapter decides what that principal may do in each tenant. -
It calls Sharing at most once per change. Before anything runs, the connector records an admission in your database: the command ID (bound once per environment), the tenant, the sequence, the resource, the signed expiry and the SHA-256 of the command name and parameters. A command that reuses the ID with different parameters, in any tenant, is refused
DUPLICATE_MISMATCH. One executor moves the admission frompendingtostartedin a conditional write that only one can win. It then asks the tenant check again, reads the clock again and calls Sharing in that same continuation, only if both deadlines still hold: the admission’s own signed expiry and the signed expiry of the delivery it is handling. If the admission’s expiry has passed, it records the admissionexpired. If only the delivery’s expiry has passed, or the clock is invalid, or the tenant check no longer allows the tenant, it hands the admission back topendingwithout calling Sharing, so a later valid delivery can start it. That write is tried once and never repeated: a store call that failed may still commit, and a repeat could hand back an admission another executor has started since. If the hand-back cannot be recorded, the admission staysstarteduntil the sweep records itunknown, although Sharing was never called. A store that fails before anything ran (reading the admission, the sweep, the check for earlier admissions) answersBUSY; a stored admission that does not decode answersINTERNAL. Nothing calls Sharing twice for one admission. -
When it cannot prove an outcome, it says so and stops. Each admission ends in one recorded state:
committed: Sharing committed it. The exact envelope that delivered it gets its originalAPPLIEDresult again only if that result was cached: from the same process, within the 10-minute dedup window. Any other delivery (another envelope, another instance, after a restart, later, or after a first delivery that timed out and whose commit was recorded late), before or after its expiry, getsALREADY_APPLIED.refused: Sharing refused the one call; every later delivery gets the same refusal. A refusal code the wire cannot carry is answeredINTERNALwith that code as its message and is final too. Some of those are transient in Sharing (POLICY_GENERATION_CHANGED,TENANT_ROLES_CHANGED,POLICY_UNAVAILABLE,HIERARCHY_UNAVAILABLE,DELEGATION_UNAVAILABLE): to try again, the console issues a new command ID.expired: its expiry passed before Sharing was called; it never ran (COMMAND_EXPIRED).unknown: the start was recorded and no result was: Sharing failed or was given up on aftercommandTimeoutMs, or the process stopped after the start write, before or during the call (INTERNAL, messageOutcome unknown).
The connector never re-runs a change to find out. It reads Sharing’s own record of the call instead: Sharing writes an idempotency record in the change’s transaction, under a key derived from the environment and the command ID, bound to the tenant, the console principal and the change, and
lookupExecutionreads it without executing anything. A call that failed (rather than one given up on while it still runs) is looked up at once, and anunknownadmission is looked up again on every delivery of the same change. When the record proves the commit, the admission is recordedcommittedand the delivery answersALREADY_APPLIEDwith the commit’s revision. Any other answer leaves itunknown: a record not found is not proof that nothing committed, and a record of another command under the key is not proof either. Every such answer comes from a conditional write or a fresh read of the admission, never from an earlier read. While another executor owns a started call, or before the change may start, a delivery answersBUSY. A commit reported after the connector gave up on the call is still recorded and replacesunknown. -
It keeps changes in sequence order. Sequences start at 1. A change that was never admitted is refused
STALEwhen another admission of the environment, refused or expired ones included, has an equal or higher sequence, andINVALID_PARAMS(detailscode: "SEQUENCE_JUMP") when its sequence is more than 2^32 above every admission. A change starts only when every admission with a lower sequence has a final state; until then it answersBUSY(retryable). This holds across processes that share the database. An admission nobody will finish gets its final state on its own: once a console has accepted this instance’shello(and with it its clock), a sweep runs then, every 10 seconds and before each change. It markspendingadmissions past their expiryexpired, andstartedonesunknownonly 60 seconds (the clock difference the console allows between instances) after the latest moment their owner could still be waiting for Sharing, which the owner recorded when it started. Until a console has accepted this instance’shello, it does not sweep at all. Terminal admissions are kept: each one binds its command ID and holds its sequence for good, so the table grows by one small row per change. The sweeps and the predecessor check read only an index of unresolved admissions. -
It does not send invitation tokens unless you allow it. An invitation token is a bearer secret. By default
issueInvitationis refusedUNSUPPORTED_COMMAND(detailsreason: "INVITATION_TOKENS_NOT_EXPORTED") before anything is admitted. An invitation admitted by an instance with the option on is never started by one with it off; that instance answersBUSYwith the same reason, and the admission is started elsewhere or expires. WithexportInvitationTokens: truethe first result carries the token withdelivery: "not_configured"so the console can hand it to the recipient. A token is sent only while the clock is valid and the command’s signed window is open; otherwise the result goes without it. If no open connection accepted that result, the connector keeps it in memory until that deadline. A redelivery receives it afterisTenantEnabledis asked again and the deadline checked again: a refusal drops the token, a failing check keeps it for a later try.stop()drops every kept token, and so does a restart. A redelivery of a committed change after its tenant was disabled answersTENANT_NOT_ENABLED, by design. -
It answers explain only when you enable inspection.
access.explainis advertised only when you passinspection: trueand your Sharing instance was created with aninspectionconfiguration. It runsTenantSharing.explainas the console principal, so it needs the resource’s configured inspect permission, is rate limited by your limiter, and is recorded by your inspection audit sink before any detail is returned. -
It copies audit events from your outbox. With the
auditoption, the connector becomes the delivery worker of your protected-write outbox and sends committed events to the console. See Audit copies. -
It reports codes and counts, not data. The
eventssurface carries command names, outcome codes and counts. It never carries a tenant, subject, resource or command identifier, a key, the service key or a signature.
The four settings
| Variable | Value |
|---|---|
ROLEBOOK_CONSOLE_URL | The console’s connector endpoint, wss://…. |
ROLEBOOK_ENVIRONMENT_ID | The environment this deployment belongs to. Commands signed for another environment are refused. |
ROLEBOOK_SERVICE_KEY | The environment’s service key. It is sent only inside the authenticated hello frame. |
ROLEBOOK_SIGNING_KEYS | A comma-separated list of 1 to 8 base64url Ed25519 public keys, each optionally prefixed by its key ID and a colon (sk_…:key). A stated key ID must match the key. |
Set all four, or none. With none set, nothing is started. With some set, or any of them malformed,
startConsoleConnector throws at startup, naming the variables but never printing their values.
import {
createSqlConnectorStateStore,
connectorStateMigrations,
startConsoleConnector,
} from "@rolebook/connector";
import type { ConsoleSharing } from "@rolebook/connector";
import type { AppSchema } from "@rolebook/connector-protocol";
declare const sharing: ConsoleSharing; // your createVersionedSharing() instance
declare const schema: AppSchema; // the resource types, roles and actions the console may show
declare const executor: {
query(sql: string, values?: readonly (string | number | null)[]): Promise<{ rows: readonly Record<string, unknown>[] }>;
};
declare function consoleEnabledFor(tenantId: string): Promise<boolean>;
for (const sql of connectorStateMigrations({ dialect: "postgres" })) await executor.query(sql);
const connector = startConsoleConnector({
sharing,
schema,
consolePrincipal: { type: "service", id: "rolebook-console" },
isTenantEnabled: consoleEnabledFor,
// Built only when all four settings are present, for the configured environment.
state: (environmentId) =>
createSqlConnectorStateStore({ executor, dialect: "postgres", environmentId }),
});
connector?.events.on("halted", (event) => console.error("Rolebook Console refused the connection", event.code)); startConsoleConnector builds the state store only when the connector is enabled, so the example
runs unchanged with none of the four settings. To configure the connector from somewhere other than
the environment, call
createConsoleConnector({ url, environmentId, serviceKey, signingKeys, ... }) and then start().
Trust model
-
Your database is authoritative. Memberships, ownership, invitations and their audit rows are written by Sharing in your database, in the same transaction as the change. The console does not store memberships; it learns of them from command outcomes and from the audit events you map.
-
The connector stores only bookkeeping.
connectorStateMigrations()creates three tables in your database: command admissions (command ID, tenant, sequence, resource, signed expiry, command hash, state and outcome), a per-environment sequence row that PostgreSQL uses to serialize admissions, and a small key-value table for the active console policy, each prepared policy publish and the custom-role revisions the console set. The state store you pass must belong to the connector’s environment; another environment’s store is refused at construction. On PostgreSQL the statements expect READ COMMITTED, the default; a serialization failure or deadlock answersBUSY. -
Commands are signed by the console and checked locally. A command with an unknown key ID, a bad signature, another environment, an unknown command name, an unknown frame type or another protocol version is refused. An unknown frame, command name or version closes the connection. Rotating keys means changing
ROLEBOOK_SIGNING_KEYS; a key you remove is refused from the next start. -
The console acts as one principal. Every change and explanation runs as
consolePrincipal, bounded by what your identity adapter grants it in that tenant and byisTenantEnabled. Nothing is attributed to a person the console names. -
Policy, guardrails and custom roles need your authorization. Sharing records the actor of a policy publish or a custom-role change but does not authorize it, and nothing else authorizes a guardrail set. So
policy.console,guardrailsandtenantRolesare advertised only when you passauthorizeAdministration(tenantRolesonly when Sharing offerscustomRoles.set,guardrailsonly with theguardrailsoption), and eachpolicy.activate,guardrails.activateandtenantRoles.setasks it first, with the operation, the console principal and, for roles, the tenant. Anything other thantruerefuses the command (UNSUPPORTED_COMMAND, detailsreason: "NOT_AUTHORIZED"); a check that times out or loses a database race answersBUSY, and one that throws otherwiseINTERNAL, retryable. The check is asked again right before each effect, and a refusal stops only what comes after it. Before a policy’s draft, no draft is written; the number stays reserved for that document. Before its publish, the saved draft and its audit row stay and nothing is published. Before a role set’s one Sharing call, nothing of the set is written; the refusal answersUNSUPPORTED_COMMAND. -
Policy. When your app schema says
policySource: "console"and Sharing is a versioned instance,policy.activatechecks that the document matches its signed hash, saves it as a policy version and publishes it through the policy store (policies.saveDraftandpolicies.publish), as the console principal. Each policy number is reserved once, with its hash, before anything is prepared: the generation it is published against and the policy it is built on. Another hash under a reserved number answersSTALE(detailscode: "NUMBER_RESERVED"). A number lower than one already reserved is not reserved, drafted or published, on a retry too (STALE, detailscode: "NEWER_POLICY"), unless it is already the active number with the same hash and still in place: that is confirmed before the newer reservation is checked. A number below the recorded active one, or the active number with another hash, answersSTALEwithout details. Across processes that check and the publish are separate steps, so what holds is this: a publish is always against its own reserved generation, so it never overwrites a policy published after that reservation; if another publish won, the command failsSTALE(detailscode: "GENERATION_CONFLICT"). The recorded active policy only moves through a compare-and-set from the value read. If the publish succeeded but cannot be recorded, the command answersINTERNAL, messagePolicy published, not recorded, retryable: a retry of the same command finds the policy active and records it. A repeat of the active number and hash is confirmed only while that policy is still the active one; after a local publish it answersSTALE(detailscode: "POLICY_CHANGED"). WithpolicySource: "code"it is refusedPOLICY_SOURCE_CODE. -
Custom roles.
tenantRoles.setrefuses a set whose roles do not match its signed hash or that lists a role twice (POLICY_INVALID). What is already done is read from Sharing’s live roles, never from the connector’s notes: a role is in place when it is live, usable (statusavailable) and has exactly these contents, or absent when the set removes it. The set is applied by onecustomRoles.setcall, so Sharing writes all of it or none of it: the complete result is every live role the console does not list, unchanged, and every role it lists as available; a role it lists as unavailable is left out, and Sharing removes it. Sharing validates that whole result: every role gets the checks a singledefinemakes, and the per-tenant limits are counted on the result, so a set that removes one role and adds another at the limit applies. A role the console does not list is validated too: one that the active policy no longer admits refuses the set until the console lists it (available with a valid definition, or unavailable, so it is removed) or it is fixed locally. A stored role row that does not decode refuses every set (CUSTOM_ROLE_UNREADABLE, naming it), listed or not, until the row is repaired in the database: Sharing cannot tell whether it is live or retired. A refusal answersPOLICY_INVALIDwith Sharing’s code (and, for one role,role). The call carries the revision and the policy generation the roles were listed under, so a local role change or policy publish that commits between the connector’s read of the roles and its call answersBUSY, with nothing written.tenantRolesis advertised only when Sharing offerscustomRoles.set, which needs a policy store that implementswriteTenantRoleSet(the first-party stores do).Before its call the connector reserves the set revision in its own record, by a compare-and-set from the record it read before listing the roles. A set revision below a recorded, reserved or (from the previous connector version) claimed one answers
STALE, and so does the same revision under another hash. A set revision another executor reserves after this one read the record makes the reservation fail (BUSY), and the retrySTALE. A call that fails or is given up on answersINTERNAL, messageRole set outcome unknown, retryable: Sharing applied all of it or none of it. A commit that cannot be recorded answersINTERNAL, messageRole set applied, not recorded, retryable. The reservation keeps the Sharing revision the first call of that set revision was made against. From then on, a retry continues only from that revision; if Sharing has moved since, the set is recorded only when it is exactly in place, and otherwise answersSTALE(detailscode: "ROLES_CHANGED"), not retryable, so a local change made after a lost commit is never overwritten; the console issues a new set revision. A later attempt never clears that baseline, whatever happens to its own call. Only the attempt that set it clears it (best effort), when its own call was not made (a host or clock check refused it) or Sharing refused it, and only while the record is still its own reservation: each reservation carries an attempt ID, so one executor’s refusal never clears another executor’s reservation of the same set revision. A repeat of a completed set is confirmed only while every role is still in place; otherwise it answersSTALE(detailscode: "ROLES_CHANGED").A claim the previous connector version left under
roles/<tenant>is read, never written: its set revision still orders sets, and the per-role revisions it recorded are still the console’s. A claim of the same set revision that was not released before a write, whether or not it was marked done, may have written: the set is applied by one atomic set only while Sharing is still at the revision the claim last recorded, or recorded when it is exactly in place, and otherwise answersSTALEwithROLES_CHANGED. A leftover claim that recorded no Sharing revision is accepted only when the set is exactly in place, and a reservation written for it keeps that rule after the claim is released. Stop every process of the previous connector version before starting this one on the same state store. The two must not run at the same time: the previous version neither reads the reservation nor keeps the per-role revisions this one records. -
Results are re-checked before release. Reads,
access.explainand the desired-state commands run again on every delivery, so a duplicate passes the tenant gate, Sharing’s inspect check, limiter and audit again. A duplicate read that arrives while the first is still running answersBUSY; the first keeps its own connection. A duplicate change,policy.activate,guardrails.activateortenantRoles.setwaits in the change queue and runs after the first: a change is then answered from this process’s cache of its result, or else from its admission, after the tenant check, and the others run again against current state. A read’s result is released only ifisTenantEnabledstill allows its tenant when it finishes. Every result of a change or a role set, and every error answer that carries tenant data in its details (a role-set conflict with its stored revisions, say), is released only afterisTenantEnabledis asked again, on its first delivery and on every repeat; error answers with a fixed code only are not. The commit itself stays recorded. If that check fails without refusing, a change’s successful result is kept for a redelivery; an error answer, or apolicy.activateortenantRoles.setresult, is not, and a redelivery runs the command again. Approval is per tenant, not one snapshot: a multi-tenant answer (hello,directory.listCustomers, the two tenants of a move’s audit event) asks each tenant again just before release and drops one no longer allowed.directory.listCustomerslists only tenantsisTenantEnabledallows. ItsnextCursor, and that ofdirectory.listResources, is bound to the command and tenant it was issued for and is the host’s continuation sealed with a key that never leaves the connector; a cursor from another instance, from before a restart, or altered, answersINVALID_PARAMS.directory.getCustomerreturns only the customer the request named.
Failure behaviour
For the same situations as a table of what happens and what to do, see What happens when.
- Console unreachable or disconnected. Local sharing keeps working: your application’s own reads
and writes do not go through the connector. The connector reconnects after a random delay of up to
1 second, a bound that doubles with each failed attempt to at most 60 seconds, and resets it after a
connection that stayed up for a minute. A connection on which the console sends nothing for 60
seconds is closed and reopened. While disconnected, no command reaches the connector, so nothing is
applied. A command that arrives after its expiry is refused
COMMAND_EXPIRED, except that a delivery of a change can still read that change’s recorded outcome. - Refused connection. After an authentication, environment, replacement or protocol-version
refusal (close codes 4401, 4403, 4409, 4426) the connector stops reconnecting and emits
halted. - Crash or disconnect after a commit. If the process stops after the start write, a redelivery
does not call Sharing again: it answers
BUSYwhile the call’s owner may still be waiting. After that the admission isunknown, and the redelivery reads Sharing’s idempotency record: when it proves the commit, the delivery answersALREADY_APPLIEDand the admission is recordedcommitted; otherwiseOutcome unknown. - Command lookup.
command.lookupanswersfound: truefrom a committed receipt for the same resource. Anything else answersfound: false, definitive: false: the connector cannot terminate a local transaction, so it never claims a command did not commit. It reads only the connector’s receipts, not Sharing’s record, because the record is bound to the change, which the lookup does not carry; a redelivery of the change reads it. - Overload. At most 16 read commands run at once; more answer
BUSY(retryable). Per connection, at most 64 commands andmaxPendingBytes(8 MiB by default) of them wait for an answer, verification included; across connections at most 96 are queued. A connection that sends more is closed with code 4429 and the eventframe_rejectedwith reasonoverloaded. Commands queued from a closed connection that have not started are dropped, and the console redelivers them. One already running finishes on its own connection; if that connection is gone, a later delivery of the change is answered from its admission. - Bounded calls. Every call to Sharing, the state store,
isTenantEnabled,authorizeAdministrationand the directory is waited for at mostcommandTimeoutMs; outbox calls are waited for at most the audit lease. A store or host call given up on before any effect answersBUSY. The Sharing call of a change or a policy publish given up on answersOutcome unknown, and a role set’s callINTERNALwithRole set outcome unknown, retryable. A database that reports a serialization failure, a deadlock, or SQLite busy or locked (as a code or a numeric result code) answersBUSY, and so does a tenant check, administration check or policy refresh that times out or loses such a race. A tenant check that throws otherwise answersINTERNAL, retryable. - Duplicate envelopes. Envelope IDs are remembered for 10 minutes, reads and changes apart. Reads
are capped at 4096 entries, oldest first; changes are never forgotten inside that window, and a
change that would exceed 4096 entries answers
BUSY.helloreports custom-role revisions only for tenantsisTenantEnabledallows.
Limits
What the connector cannot rule out, and what it does instead. None of these ever re-runs a change.
- The admission, the Sharing change and the receipt are three transactions. If the process stops
between them, or the call fails, the admission is recorded
unknown. Sharing’s idempotency record, written in the change’s own transaction, then resolves it when it can: a failed call is looked up at once, and every later delivery of the same change looks up anunknownadmission again. It staysunknownwhen the record cannot prove the commit: the call is still running (a call given up on is not looked up until a redelivery), the record was pruned by retention (pruneSettledRecords, no sooner than one day after the commit), the resource was deleted or moved to another tenant since (both delete the record at the source key), the key holds another command’s record, the console principal no longer resolves as a member of the tenant or was changed (the lookup is bound to the current one), the tenant’s hierarchy enrollment has started (Sharing does not read an enrolled tenant’s records for a lookup), the lookup fails or is given up on, or the Sharing tenant has nolookupExecution(an adapter withoutlookupMutationIdempotency). - A call given up on can still commit. A timer stops the connector waiting, not Sharing. A call
that is given up on, or whose executor stopped, can commit after it was recorded
unknown, and after a change with a higher sequence ran. A late commit that reaches the connector is recorded, and so is one a later delivery finds in Sharing’s record. - What the console does with
Outcome unknown. The change may or may not have taken effect. Redeliver the same change with the same command ID: it never runs again, and answersALREADY_APPLIEDonce Sharing’s record proves the commit.command.lookupreads only the connector’s receipts. If the outcome stays unknown, check the membership, and issue a new command with a new ID if it is still needed. - A role set that changes nothing writes nothing. Sharing answers it without a write, so it does not fence on Sharing’s revision: an older executor’s role set already in flight against the same revision can still commit after this one is recorded. The reservation stops an older set revision from starting once a newer one is reserved, not one whose call already started.
- Two refused calls can strand a set revision. When two executors run the same set revision
and both calls are refused cleanly (a local change moved Sharing first), the second inherited the
first’s baseline and the first’s release lost its compare-and-set, so the baseline stays. Every
later retry of that set revision then answers
STALE(ROLES_CHANGED) unless the set happens to be exactly in place, although nothing of it committed. It fails closed: the console issues a new set revision. - One connector version at a time. The previous connector version wrote role sets one role at a time under a claim it does not share with this version’s reservation. Running both against one state store can apply an older set after a newer one; stop the previous version’s processes first.
- A retried role set does not overwrite a local change. When a set’s commit may have been lost
and Sharing has moved since, the retry cannot tell its own commit followed by a local change from a
local change alone, so it answers
STALE(ROLES_CHANGED) unless the set is exactly in place, and the console issues a new set revision. - Two host answers, two calls. Before the role set’s one Sharing call the connector asks
isTenantEnabledfirst andauthorizeAdministrationlast, right before the clock check and the call. They are separate calls, so the last one asked is the freshest; a tenant disabled between the two answers is not caught for that call. - Several processes. Admissions, single ownership of each call and sequence order are enforced
through the shared database, which must run the store’s statements at READ COMMITTED on PostgreSQL.
A change another process owns makes later changes answer
BUSYuntil it has a final state. - A role list can be a cached view. Sharing serves
customRoles.listfrom a per-process snapshot refreshed on itsrefreshIntervalMs. A repeat of a completed set is confirmed from that view, so a local change made through another process may take up to that interval to be seen. Writes are not affected: the set is a compare-and-set on Sharing’s revision. A set decided from a stale view conflicts and answersBUSY; the conflict drops that process’s cached view, so the retry reads the stored roles. - Audit quarantine is permanent. An audit event that names a tenant
isTenantEnabledrefused when it was checked, at collection or again at send, is quarantined and is not sent if the tenant is enabled later.
Audit copies
The connector reuses your existing protected-write outbox
(createPostgresProtectedWriteOutbox or createSqliteProtectedWriteOutbox) through Sharing’s run-once
delivery worker. You map each committed outbox event to the console’s audit shape:
import type { ConsoleAuditOptions } from "@rolebook/connector";
import type { OutboxDeliveryPort } from "@rolebook/sharing";
declare const outbox: OutboxDeliveryPort;
const audit: ConsoleAuditOptions = {
outbox,
toEvent(event) {
if (event.kind !== "app.member.granted") return undefined;
const payload = event.payload as {
tenantId: string;
resource: { type: string; id: string };
actor: { type: string; id: string };
at: string;
};
return {
id: event.eventId,
tenantId: payload.tenantId,
resourceType: payload.resource.type,
resourceId: payload.resource.id,
actor: payload.actor,
action: "member.granted",
occurredAt: payload.at,
};
},
}; - Only the primary connection sends audit batches, one at a time. Rows are acknowledged in the outbox
only after the console’s
audit.ack. A nack retries them; a disconnect or timeout leaves them for replay after the lease expires. - Delivery is at least once. The event ID is the outbox event ID, so a redelivered event has the same ID and the console deduplicates on it.
- An event your mapping returns
undefinedfor is quarantined with the reasonNot a console audit event, visible ininspectDeadLetters, and never sent. - The outbox must be created with the connector’s environment ID. An event from another environment is left pending: neither mapped, sent nor quarantined.
- The lease is measured from before the claim. A batch is not sent once less than a quarter of the lease (at most one second) remains, nor on a connection other than the one it was collected for; an event whose lease expires while its batch is collected is dropped from it. Each batch sent carries the events of one tenant (or one move’s pair of tenants), checked right before it is sent; a pair is checked twice. The tenant groups of one claim are sent one after another, in claim order, each after the console answered the previous one, while the lease margin holds; what is left goes back to the outbox.
- An event that names a tenant
isTenantEnableddoes not allow, on either side of a move, is quarantined with the reasonTenant not enabled for the consoleand never sent. A gate that throws leaves the event for a later attempt. - The connector becomes that outbox’s consumer: do not run a second delivery worker on it.
- Sharing’s own membership changes write their audit rows to the sharing audit table, not to the outbox, so a console grant is not copied by this path unless your application also records it in the outbox.
Guardrails
Rolebook Console can publish one set of guardrails for the whole environment.
The connector records the set in its state store, and createConsoleGuardrails() gives each of
your processes the compiled set to run:
import { createConsoleConnector, createConsoleGuardrails } from "@rolebook/connector";
import type { ConsoleConnectorOptions } from "@rolebook/connector";
import { createGuardedAuthorizer, createGuardrails } from "@rolebook/guardrails";
import type { Authorizer } from "rolebook";
declare const authorizer: Authorizer; // your createAuthorizer(policy)
declare const options: ConsoleConnectorOptions; // as above, with authorizeAdministration
const guardrails = createConsoleGuardrails({ compile: createGuardrails, state: options.state });
await guardrails.load(); // stop here if the recorded set cannot be read
guardrails.start(); // then read it again refreshMs after each read ends
// Every check runs the recorded set.
const guarded = createGuardedAuthorizer(authorizer, guardrails.current);
const connector = createConsoleConnector({ ...options, guardrails });
await connector.start(); - Offered when you pass
guardrailsandauthorizeAdministration. Your administration check is asked withoperation: "guardrails.activate"when the command starts and again right before the set is recorded. If your check has a fall-through branch, give this operation its own. - One store. Pass
createConsoleGuardrails()the samestateobject you pass the connector. The connector refuses an instance that reads another one, even of the same environment. - What a command does. The connector checks that the document is the one its signed hash names,
compiles a copy of it with your
compile, and replaces the one record in the state store with a compare-and-set. Nothing is recorded thatcompilerefused, andcompilemust answer synchronously. The process that took the command runs the new set at once, dated from just before the write, or before the read that found it already recorded when the command is a repeat. A write the store took longer thanmaxStaleMsto answer leaves the set stale until a read confirms it. If the process loaded a newer set while the command ran, it keeps that one and the command answersSTALE, withRUNNING_NEWERin its details when the write had already happened. - Other processes run the set from their next successful read. A started instance reads again
refreshMs(5 seconds unless you set it) after each read ends, so that is usually withinrefreshMsplus the time of one read. A process that only decides checks needscreateConsoleGuardrails()over the same store and no connector. - When the record cannot be confirmed.
guardrails.current()throws until a read succeeded, and again when the store last agreed with the running set more thanmaxStaleMsago (60 seconds, or three timesrefreshMswhen that is larger, unless you set it; never less than three timesrefreshMs: one read, the wait and the next read. Time yourcompiletakes, and a busy event loop, come on top of that, so leave room if either is slow). A check that your roles allow then answersGUARDRAIL_ERROR, which is a denial; a check your roles deny keeps its own code. A process that cannot confirm its set stops allowing instead of running one that may have been replaced. While reads fail, a process keeps the previous set for up tomaxStaleMs.onErrorreceives each failed read. A store call that never answers is not joined by another untilmaxStaleMshas passed. - Before any set is published, and after the console publishes an empty one, the set has no policies and every check keeps its role decision.
- A store that went back. A process never runs an older set than the one it runs, and the
connector answers
STALEto a number below it. If the store’s record goes back (a restored database), each such process keeps allowing under its set untilmaxStaleMshas passed and denies from then on, until the console publishes that set again or a newer one, or the process restarts and reads the store. A record that is absent after such a restore is reported as no set. - A record the connector cannot run. The connector says hello only after it has checked that
the stored record is the document its hash names and that
compileaccepts it. A record it cannot read or run keeps it from connecting. Processes that already run a set keep it untilmaxStaleMshas passed and then deny; a process that starts denies at once. A connector that is still connected repairs a record whose document was damaged when the console sends that set again, or a newer one, provided the record still parses and has its number, its hash and a document. A record without those, and any record once no connector can connect, has to be repaired in the store.
startConsoleConnector() takes the same guardrails option. Build the store for
ROLEBOOK_ENVIRONMENT_ID once, give it to createConsoleGuardrails(), and return that same
object from the state function.
API
@rolebook/connector
createConsoleConnector
function createConsoleConnector(input: ConsoleConnectorOptions): ConsoleConnector; ConsoleConnector
maxConcurrentMutations is a diagnostic: the highest number of state-changing commands that ran at
once, which is always at most 1.
interface ConsoleConnector {
start(): Promise<void>;
stop(): Promise<void>;
readonly events: ConsoleConnectorEvents;
readonly maxConcurrentMutations: number;
} startConsoleConnector
Starts the connector from ROLEBOOK_CONSOLE_URL, ROLEBOOK_ENVIRONMENT_ID, ROLEBOOK_SERVICE_KEY
and ROLEBOOK_SIGNING_KEYS. With none set it returns undefined and builds nothing; with some set,
or any malformed, it throws naming the variables, never their values. An unreachable console does not
fail startup.
function startConsoleConnector(options: StartConsoleConnectorOptions): ConsoleConnector | undefined; StartConsoleConnectorOptions
type StartConsoleConnectorOptions = Omit<ConsoleConnectorOptions, "url" | "environmentId" | "serviceKey" | "signingKeys" | "state"> & {
readonly env?: Readonly<Record<string, string | undefined>>;
readonly state: (environmentId: string) => ConsoleConnectorOptions["state"];
}; ConsoleConnectorOptions
interface ConsoleConnectorOptions {
readonly url: string;
readonly environmentId: string;
readonly serviceKey: string;
readonly signingKeys: readonly SigningPublicKey[];
readonly sharing: ConsoleSharing;
readonly consolePrincipal: ResourceRef;
readonly isTenantEnabled: (tenantId: string) => boolean | Promise<boolean>;
readonly schema: AppSchema;
readonly state: ConnectorStateStore;
readonly directory?: ConsoleDirectory;
readonly inspection?: boolean;
readonly audit?: ConsoleAuditOptions;
readonly guardrails?: ConsoleGuardrails<unknown>;
readonly authorizeAdministration?: (request: ConsoleAdministrationRequest) => boolean | Promise<boolean>;
readonly exportInvitationTokens?: boolean;
readonly connector?: {
readonly name: string;
readonly version: string;
};
readonly instanceId?: string;
readonly clock?: () => Date;
readonly random?: () => number;
readonly WebSocket?: typeof WebSocket;
readonly idleTimeoutMs?: number;
readonly commandTimeoutMs?: number;
readonly maxPendingBytes?: number;
} ConsoleAdministrationRequest
type ConsoleAdministrationRequest = {
readonly operation: "policy.activate";
readonly principal: ResourceRef;
} | {
readonly operation: "guardrails.activate";
readonly principal: ResourceRef;
} | {
readonly operation: "tenantRoles.set";
readonly principal: ResourceRef;
readonly tenantId: string;
}; createConsoleGuardrails
The guardrail set a process runs, read from the connector’s state store. See Guardrails.
function createConsoleGuardrails<TGuardrails>(options: ConsoleGuardrailsOptions<TGuardrails>): ConsoleGuardrails<TGuardrails>; ConsoleGuardrailsOptions
compile must answer synchronously and is given its own copy of the document. state is the
object the connector is given. refreshMs is an integer from 100 to 300,000 and defaults to 5,000.
maxStaleMs is an integer from three times refreshMs to 86,400,000 and defaults to 60,000, or to
three times refreshMs when that is larger. onError is called once with each failed read. now is a monotonic clock in
milliseconds and defaults to performance.now.
interface ConsoleGuardrailsOptions<TGuardrails> {
readonly compile: (document: unknown) => TGuardrails;
readonly state: Pick<ConnectorStateStore, "read">;
readonly refreshMs?: number;
readonly maxStaleMs?: number;
readonly onError?: (error: unknown) => void;
readonly now?: () => number;
} ConsoleGuardrails
active is the number and hash of the set this process last loaded: null when no set was ever
activated, undefined before the first one. It stays the same while current() throws because
the set went stale. load() rejects when the read fails, when the record cannot be run, and when
the record is older than the set this process runs. start() reads now and again refreshMs
after each read ends.
interface ConsoleGuardrails<TGuardrails> {
readonly current: () => TGuardrails;
readonly active: {
readonly number: number;
readonly hash: string;
} | null | undefined;
load(): Promise<void>;
start(): void;
stop(): void;
} ConsoleGuardrailsUnavailable
Thrown by current() before the first successful read (not_loaded) and when the store last
agreed with the running set more than maxStaleMs ago (stale).
class ConsoleGuardrailsUnavailable extends Error {
readonly reason: "not_loaded" | "stale";
constructor(reason: "not_loaded" | "stale");
} ConsoleSharing
type ConsoleSharing = ResourceSharing<SharingResourceConfigurations> & {
readonly policies?: PolicyAdministration;
readonly customRoles?: CustomRoleAdministration;
current?(): {
readonly generation: string;
readonly digest: string;
};
refresh?(): Promise<{
readonly generation: string;
readonly digest: string;
}>;
}; The application’s Sharing instance. A change’s lost outcome is resolved through its tenants’
lookupExecution; a tenant without it leaves such an outcome unknown. tenantRoles needs
customRoles.set.
ConsoleDirectory
Optional. With it, the connector advertises directory and answers the console’s customer, people
and item lookups from your handlers; every answer is validated against the protocol schema.
interface ConsoleDirectory {
listCustomers(params: CommandParams<"directory.listCustomers">): Promise<CommandResult<"directory.listCustomers">>;
getCustomer(params: CommandParams<"directory.getCustomer">): Promise<CommandResult<"directory.getCustomer"> | undefined>;
searchPeople(params: CommandParams<"directory.searchPeople">): Promise<CommandResult<"directory.searchPeople">>;
getPeople(params: CommandParams<"directory.getPeople">): Promise<CommandResult<"directory.getPeople">>;
listResources(params: CommandParams<"directory.listResources">): Promise<CommandResult<"directory.listResources">>;
} ConsoleAuditOptions
interface ConsoleAuditOptions {
readonly outbox: OutboxDeliveryPort;
readonly toEvent: (event: OutboxDeliveryEvent) => OutboxEvent | undefined;
readonly batchSize?: number;
readonly leaseMs?: number;
readonly pollMs?: number;
} UNMAPPED_AUDIT_REASON
const UNMAPPED_AUDIT_REASON = "Not a console audit event"; DISABLED_TENANT_AUDIT_REASON
const DISABLED_TENANT_AUDIT_REASON = "Tenant not enabled for the console"; MAX_PENDING_COMMANDS
const MAX_PENDING_COMMANDS = 64; MAX_PENDING_BYTES
const MAX_PENDING_BYTES: number; MAX_QUEUED_COMMANDS
const MAX_QUEUED_COMMANDS: number; MAX_DEDUP_ENTRIES
const MAX_DEDUP_ENTRIES = 4096; ConsoleConnectorEvent
type ConsoleConnectorEvent = {
readonly type: "connected";
readonly primary: boolean;
} | {
readonly type: "disconnected";
readonly code: number;
readonly retryInMs?: number;
} | {
readonly type: "halted";
readonly code: number;
} | {
readonly type: "command";
readonly name: string;
readonly outcome: "applied" | "already_applied" | "answered" | "refused" | "failed";
readonly code?: string;
} | {
readonly type: "audit";
readonly sent: number;
readonly acknowledged: boolean;
} | {
readonly type: "frame_rejected";
readonly reason: "malformed" | "oversized" | "overloaded";
}; ConsoleConnectorEvents
interface ConsoleConnectorEvents {
on<T extends ConsoleConnectorEventType>(type: T, listener: (event: Extract<ConsoleConnectorEvent, {
type: T;
}>) => void): () => void;
} ConsoleConnectorEventType
type ConsoleConnectorEventType = ConsoleConnectorEvent["type"]; validConsoleUrl
function validConsoleUrl(value: unknown): value is string; validSigningKey
function validSigningKey(key: unknown): key is SigningPublicKey; CONNECTOR_ENVIRONMENT_VARIABLES
const CONNECTOR_ENVIRONMENT_VARIABLES: readonly [
"ROLEBOOK_CONSOLE_URL",
"ROLEBOOK_ENVIRONMENT_ID",
"ROLEBOOK_SERVICE_KEY",
"ROLEBOOK_SIGNING_KEYS"
]; ConnectorConfigurationResult
type ConnectorConfigurationResult = {
readonly enabled: false;
} | {
readonly enabled: true;
readonly url: string;
readonly environmentId: string;
readonly serviceKey: string;
readonly signingKeys: readonly SigningPublicKey[];
}; parseConnectorEnvironment
function parseConnectorEnvironment(env: Readonly<Record<string, string | undefined>>): ConnectorConfigurationResult; parseSigningKeys
function parseSigningKeys(value: string): readonly SigningPublicKey[]; ConnectorAdmission
interface ConnectorAdmission {
readonly tenantId: string;
readonly commandId: string;
readonly seq: number;
readonly payloadHash: string;
readonly resourceType: string;
readonly resourceId: string;
readonly expiresAt: number;
} ConnectorAdmissionResult
type ConnectorAdmissionResult = "admitted" | "exists" | "stale" | "jump"; ConnectorReceiptState
type ConnectorReceiptState = "pending" | "started" | "committed" | "refused" | "expired" | "unknown"; ConnectorReceipt
interface ConnectorReceipt {
readonly tenantId: string;
readonly seq: number;
readonly payloadHash: string;
readonly resourceType: string;
readonly resourceId: string;
readonly expiresAt: number;
readonly state: ConnectorReceiptState;
readonly outcome: string | undefined;
} ConnectorTransition
interface ConnectorTransition {
readonly commandId: string;
readonly payloadHash: string;
readonly from: readonly ConnectorReceiptState[];
readonly to: ConnectorReceiptState;
readonly outcome?: string;
readonly notAfterExpiry?: number;
readonly waitUntil?: number;
} ConnectorCompletion
interface ConnectorCompletion {
readonly commandId: string;
readonly payloadHash: string;
readonly sharingRevision: string;
} MAX_SEQUENCE_STEP
const MAX_SEQUENCE_STEP: number; ConnectorSqlDialect
type ConnectorSqlDialect = "sqlite" | "postgres"; ConnectorSqlExecutor
interface ConnectorSqlExecutor {
query(sql: string, values?: readonly (string | number | null)[]): Promise<{
readonly rows: readonly Readonly<Record<string, unknown>>[];
}>;
} ConnectorStateStore
interface ConnectorStateStore {
readonly environmentId: string;
highestCommittedSeq(): Promise<number>;
readReceipt(commandId: string): Promise<ConnectorReceipt | undefined>;
admitCommand(admission: ConnectorAdmission): Promise<ConnectorAdmissionResult>;
transition(change: ConnectorTransition): Promise<boolean>;
completeReceipt(input: ConnectorCompletion): Promise<void>;
hasUnresolvedBefore(seq: number): Promise<boolean>;
sweep(now: number, skewMs: number): Promise<void>;
read(key: string): Promise<string | undefined>;
write(key: string, value: string): Promise<void>;
writeOnce(key: string, value: string): Promise<string>;
compareAndSet(key: string, expected: string | undefined, value: string): Promise<boolean>;
list(prefix: string): Promise<readonly (readonly [
string,
string
])[]>;
} connectorStateMigrations
function connectorStateMigrations(options: {
readonly dialect: ConnectorSqlDialect;
readonly tablePrefix?: string;
}): readonly string[]; createMemoryConnectorStateStore
function createMemoryConnectorStateStore(options: {
readonly environmentId: string;
}): ConnectorStateStore; createSqlConnectorStateStore
function createSqlConnectorStateStore(options: {
readonly executor: ConnectorSqlExecutor;
readonly dialect: ConnectorSqlDialect;
readonly environmentId: string;
readonly tablePrefix?: string;
}): ConnectorStateStore;