RolebookDocs

Commands

execute() and its seven commands, tenant.governance, idempotency, conflict retries, expiring memberships, and result codes.

Every change to sharing state is a command passed to execute() on a tenant facade. The module authorizes it with Rolebook against current state, applies it in the storage adapter’s transaction with an audit event, and returns a result. It never throws for an ordinary refusal. Whenever governance applies, that direct call returns GOVERNANCE_REQUIRED and does not bypass approval effects. Those commands go through the server-side tenant.governance façade.

const result = await tenant.execute({
  kind: "grantRole",
  resource: { type: "project", id: projectId },
  subject: { type: "user", id: "user_789" },
  role: "editor",
  idempotencyKey: "grant-user_789-project_1",
});

if (result.ok) {
  console.log(result.code, result.sharingRevision); // "APPLIED" | "ALREADY_APPLIED"
} else {
  console.log(result.code); // for example "FORBIDDEN" or "NOT_TENANT_MEMBER"
}

The commands

Every command names its resource ({ type, id }) and an idempotencyKey, an opaque string of 1 to 128 characters. Role labels are the configured member-role labels (or a custom role label on a versioned instance).

CommandFieldsActor needs
grantRolesubject, role, optional expiresAtmanagement.members
changeRolesubject, role, optional expiresAt (Date, null, or omitted)management.members
revokeMembersubjectmanagement.members
transferOwnershipto, optional formerOwnerRolemanagement.ownership, and to be the current owner
issueInvitationrecipient, role, expiresAt, optional membershipExpiresAtmanagement.invitations
acceptInvitationtokento match the invitation’s recipient
revokeInvitationinvitationIdmanagement.invitations

Beyond the management permission, grants, changes, revocations, and invitations by anyone other than the owner are bounded by the delegation ceiling: a manager can hand out, change, or take away only access it holds itself.

Grant and change a role

grantRole creates a membership for a subject (a user, or a team) who must be an eligible member of the tenant. A live membership already present is MEMBER_ALREADY_EXISTS; use changeRole to change it. changeRole replaces the role of an existing membership. Neither may target the actor itself (SELF_PROMOTION) or the current owner (OWNER_TRANSFER_REQUIRED).

Revoke a member

revokeMember deletes a membership. A successful commit is the linearization point: the next authorization and listing read the new state. Positive decisions are never cached by the module.

Transfer ownership

Only the current owner may transfer ownership, and only to an eligible individual: a group target is GROUP_CANNOT_OWN, and an actor that holds management.ownership without owning the resource is OWNER_TRANSFER_REQUIRED. With formerOwnerRole, the former owner keeps a permanent membership with that role; without it, the former owner keeps no membership. A former owner retrying its own committed transfer with the same idempotency key still gets ALREADY_APPLIED.

Invitations

issueInvitation creates an invitation to one recipient and returns its token once, on the APPLIED result: result.invitation is { id, token }. Storage keeps only a keyed digest of the secret, so a replay of the same command reports ALREADY_APPLIED without a token.

const issued = await tenant.execute({
  kind: "issueInvitation",
  resource: { type: "project", id: projectId },
  recipient: { type: "subject", subject: { type: "user", id: "user_789" } },
  role: "viewer",
  expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
  idempotencyKey: "invite-user_789-project_1",
});
if (issued.ok && issued.invitation) {
  const link = `https://app.example.com/invitations/${encodeURIComponent(issued.invitation.token)}`;
}
  • A recipient is { type: "subject", subject } (bound to an immutable subject ID) or { type: "email", email } (at most 320 characters, matched against the accepting user’s verified address). Email recipients need a recipient fence in the storage adapter; some identity adapters refuse them. A malformed recipient is INVITATION_RECIPIENT_INVALID.
  • expiresAt must be after the clock’s current time and at most maxInvitationTtlMs (30 days by default) ahead; otherwise INVITATION_EXPIRED.
  • Inviting yourself is SELF_PROMOTION.
  • The recipient need not be a workspace member yet. Resource invitations never create or replace an identity provider’s organization invitation: complete the provider’s own workspace invitation first, then accept the resource invitation as the signed-in member.

acceptInvitation takes the token. The accepting actor must be an eligible tenant member that matches the recipient (INVITATION_RECIPIENT_MISMATCH otherwise). Expiry is checked after the identity lookup and again inside storage (INVITATION_EXPIRED). A wrong token, a consumed or revoked invitation, a missing resource, and an invitation whose creator no longer qualifies all answer the same INVITATION_UNAVAILABLE. Accepting an invitation you created is SELF_PROMOTION.

Accepting as an existing member consumes the invitation and returns APPLIED, but never replaces the member’s role: change roles with changeRole. An invitation addressed to a team is accepted by a current team member on the team’s behalf, and the membership is the team’s.

revokeInvitation revokes a pending invitation by ID.

Governance

tenant.governance is the server-side façade. It has six methods: request(command), approve(requestId), reject(requestId), cancel(requestId), apply(requestId), and resolve(requestId). Each returns precisely { status }. status is PENDING, APPROVED, REJECTED, APPLIED, VOID, REFUSED, UNAVAILABLE, or UNKNOWN_REQUEST.

Before calling request, import createGovernanceRequestId from @rolebook/sharing and call it with the requester’s authenticated tenant context. Put the returned ID in command.requestId and keep it for retries and later calls; the response contains only the status.

A transfer uses one of two authorized modes. Recipient acceptance is not required.

  • A non-owner request requires a counted direct-owner sponsor.
  • An owner request records payload-bound, non-counting owner consent and needs an independent eligible quorum.

Direct execute() returns GOVERNANCE_REQUIRED whenever governance applies. That result does not bypass approval effects.

Idempotency

Every command carries an idempotencyKey. The adapter stores it with a fingerprint: a keyed digest of the actor, the tenant, and the command (the invitation secret is never part of it). Retrying the same command with the same key answers ALREADY_APPLIED with the sharing revision of the original commit. Reusing a key for a different command, or from a different actor, is CONFLICT once the command is otherwise authorized, returned after the first attempt without retries.

On createSharing(), a retry is authorized against current state before it replays, with two exceptions that keep retries safe for commands that remove the actor’s own access: a former owner retrying its transferOwnership, and a member retrying the revokeMember that un-shared its own team. A retried grant whose target has since left the tenant, or whose short expiry has since passed, still answers its original success. On createVersionedSharing(), the actor’s own committed key replays before validation and authorization, with the policyVersion of the original commit.

A replay holds only while the idempotency record is kept. Records are pruned by pruneSettledRecords() (30 days by default); after that a retry runs as a new command, re-authorized against current state. Choose a retention longer than every client’s retry window.

Looking up an outcome

A caller that lost the answer of an execute (its process stopped, or it gave up waiting) can read what Sharing recorded without running the command again:

declare const command: Parameters<typeof tenant.execute>[0];

const found = await tenant.lookupExecution?.(command);
if (found?.status === "committed") {
  // found.result is what a replay answers: ALREADY_APPLIED and the commit's revision.
}

lookupExecution takes the same command, executes nothing, and answers committed, not_found, different_command, or refused. Only committed proves an outcome: not_found is also the answer after the record was pruned, after the resource was deleted or moved to another tenant, and while the command may still be running. See SharingExecutionLookupResult.

Conflict retries

A mutation is conditional on the resource version and sharing revision it was authorized against. When either changed (a concurrent revocation, ownership transfer, deletion, move, or authorization-fact change), the adapter reports a conflict, and execute() re-resolves the principal, re-reads the resource, and re-authorizes, up to mutationRetries more times (3 by default, at most 10), before returning CONFLICT.

It pauses before each retry, never before the first attempt or after the last. The default pause is a whole number of milliseconds drawn uniformly from 0 to min(50, 5 x 2^(retry - 1)): at most 5, 10, 20, 40, then 50 ms, so writers that conflicted do not retry in lockstep. mutationBackoffMs(retry) replaces the schedule and must return a finite delay from 0 to 1,000 ms, or the command rejects with a RangeError. mutationWait(ms) replaces the timer.

import { createSharing } from "@rolebook/sharing";

const immediate = createSharing({
  definition,
  identity,
  invitationTokens,
  mutationBackoffMs: () => 0, // retry conflicts immediately
});

Applying only at a revision you read

A caller that showed someone the access it is about to change can make the command conditional on what was shown. With expectedSharingRevision, the command applies only while the resource’s sharing revision is still that value: the write commits under the revision the command was authorized at, and a conflicted attempt re-reads, sees the moved revision, and answers SHARING_REVISION_CHANGED instead of retrying into a state nobody reviewed. The command’s own earlier commit still replays as ALREADY_APPLIED, so a retry after a lost answer is safe. The precondition is not part of the idempotency fingerprint.

const read = await tenant.describeAccess({ resource: { type: "project", id: projectId } });
if (read.ok) {
  const result = await tenant.execute({
    kind: "revokeMember",
    resource: { type: "project", id: projectId },
    subject: { type: "user", id: "user_789" },
    idempotencyKey: "revoke-user_789-reviewed",
    expectedSharingRevision: read.access.sharingRevision,
  });
  if (!result.ok && result.code === "SHARING_REVISION_CHANGED") {
    // Access changed since it was read: read it again before asking once more.
  }
}

Time-limited memberships

A membership may expire. grantRole takes an optional expiresAt; issueInvitation takes an optional membershipExpiresAt for the membership its acceptance creates (a contractor invited for a fixed period); changeRole takes expiresAt as a Date to set one, null to make the membership permanent, or nothing to keep the current expiry. Ownership never expires, and a formerOwnerRole membership is permanent.

await tenant.execute({
  kind: "grantRole",
  resource: { type: "project", id: projectId },
  subject: { type: "user", id: "contractor_9" },
  role: "editor",
  expiresAt: new Date("2027-03-31T00:00:00Z"),
  idempotencyKey: "grant-contractor_9",
});
  • An expiry that is not a valid Date (or null outside changeRole), that is not after the clock’s current time, or a membershipExpiresAt not after the invitation’s own expiresAt is MEMBERSHIP_EXPIRY_INVALID.
  • Expiry fields are part of the idempotency fingerprint, so a retry that differs only in expiry is CONFLICT.
  • A membership at or past its expiresAt grants nothing: every adapter read leaves it out, and the module skips it again when binding. The row stays until grantRole or an accepted invitation replaces it, changeRole reinstates it, or revokeMember deletes it.
  • Expiry is decided by the adapter’s clock and re-checked by the module’s clock, so a membership is gone as soon as either reaches its expiresAt. Expiry does not bump the sharing revision, so never key a decision cache on sharingRevision alone.
  • Because an expired membership is absent from every read, the delegation ceiling never sees it: revoking or changing an expired member needs no coverage of its old role.

Rolling upgrades

Do not issue expiring grants or invitations until every instance runs a version with expiry support: older code reads an expiring row as permanent. Before rolling back to such a version, revoke or make permanent every expiring membership and revoke every invitation that carries membershipExpiresAt.

Result codes

A successful result is { ok: true, code: "APPLIED" | "ALREADY_APPLIED", sharingRevision }, plus invitation on an applied issueInvitation and policyVersion on a versioned instance.

CodeMeaning
NOT_FOUND_OR_DENIEDThe resource does not exist, the command is malformed, the type is not configured, or the actor has no relationship to the resource.
FORBIDDENThe actor has a relationship to the resource but Rolebook or the delegation ceiling refuses the command.
NOT_TENANT_MEMBERThe actor or the target subject is not an eligible member of the tenant, or the tenant or actor ID is malformed.
ROLE_NOT_ALLOWEDThe role label (or formerOwnerRole) is not configured for the type, or names an unavailable custom role.
SELF_PROMOTIONThe actor targets its own membership, a team it belongs to, or its own invitation.
OWNER_TRANSFER_REQUIREDgrantRole, changeRole, or revokeMember targets the current owner, or an actor allowed management.ownership that is not the current owner sends a transferOwnership whose key holds no record (its own committed transfer replays; a key recorded for another command or actor is CONFLICT). Without management.ownership, a transfer is FORBIDDEN or NOT_FOUND_OR_DENIED.
GROUP_CANNOT_OWNOwnership would go to a group.
MEMBER_ALREADY_EXISTSgrantRole for a subject with a live membership.
INVITATION_EXPIREDThe invitation’s expiresAt is invalid when issued, or it has expired when accepted.
INVITATION_RECIPIENT_INVALIDThe recipient is malformed.
INVITATION_UNAVAILABLEThe token does not open a pending invitation the actor may use.
INVITATION_RECIPIENT_MISMATCHThe accepting actor is not the invitation’s recipient.
MEMBERSHIP_EXPIRY_INVALIDAn expiry is malformed or not in the future.
CONFLICTRetries ran out, or the idempotency key was used for another command.
SHARING_REVISION_CHANGEDThe command’s expectedSharingRevision is no longer the resource’s sharing revision. Nothing was applied.
GOVERNANCE_REQUIREDDirect execute() when governance applies. The command is not applied, and the result does not bypass approval effects.
POLICY_GENERATION_CHANGEDVersioned: the active policy changed after authorization.
TENANT_ROLES_CHANGEDVersioned: the tenant’s custom roles changed after authorization.
POLICY_UNAVAILABLEVersioned: the active policy cannot be used, or the adapter is not policy-fenced.

NOT_FOUND_OR_DENIED and FORBIDDEN are split on purpose: a caller with no relationship to a resource must not learn that it exists. See denials and resource existence. Handle the two alike when you only need “not allowed”.

Identity adapters may throw (for example a team directory that cannot answer). The module does not catch it: execute(), authorize(), and listAccessible() reject. Treat that as an application fault.