RolebookDocs

Define and create

The policy roles sharing needs, defineSharing, createSharing options, and secret keys.

The policy

Sharing reads its roles and permissions from an ordinary Rolebook policy. For each shareable resource type, declare at the resource’s own scope:

  • an ownership role that the owner holds (usually type:*);
  • one or more member roles for ordinary members;
  • the resource actions members use (read, update);
  • three management actions: managing members, managing invitations, and transferring ownership.
import { definePolicy } from "rolebook";

export const policy = definePolicy({
  resources: {
    workspace: { actions: ["read"] },
    project: {
      parent: "workspace",
      actions: ["read", "update", "delete", "manage_members", "manage_invitations", "transfer_ownership"],
    },
  },
  roles: {
    project_owner: { scope: "project", rules: [{ effect: "allow", permission: "project:*" }] },
    project_manager: {
      scope: "project",
      inherits: ["project_editor"],
      rules: [
        { effect: "allow", permission: "project:manage_members" },
        { effect: "allow", permission: "project:manage_invitations" },
      ],
    },
    project_editor: {
      scope: "project",
      rules: [
        { effect: "allow", permission: "project:read" },
        { effect: "allow", permission: "project:update" },
      ],
    },
    project_viewer: { scope: "project", rules: [{ effect: "allow", permission: "project:read" }] },
  },
});

defineSharing

defineSharing() maps storage labels to policy values and validates the mapping against the policy:

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

const projectSharing = defineSharing({
  policy,
  resources: {
    project: {
      // Label stored in membership rows -> policy role.
      memberRoles: { viewer: "project_viewer", editor: "project_editor", manager: "project_manager" },
      ownershipRole: "project_owner",
      // Action label used by authorize(), listAccessible(), and listAccess() -> permission.
      actions: { read: "project:read", update: "project:update", delete: "project:delete" },
      management: {
        members: "project:manage_members",
        invitations: "project:manage_invitations",
        ownership: "project:transfer_ownership",
        // Optional: who may call describeAccess(), auditHistory(), and explain(). Defaults to members.
        inspect: "project:manage_members",
      },
      adapter: projectAdapter,
    },
  },
});

It throws an Error when:

  • a resource type is not declared by the policy, or is not a lowercase label (^[a-z][a-z0-9_]{0,127}$);
  • the ownership role does not exist at that resource’s scope, or is also listed as a member role;
  • a member role does not exist at that scope, or a member-role or action label is not a lowercase label;
  • there is no member role, no action, or no resource type at all;
  • an action or management permission is not a concrete, declared permission of that resource type.

defineSharing() canonicalizes the policy the way definePolicy() does and freezes the whole catalog, so a later change to your objects cannot reach a sharing decision. The member-role labels are what membership rows store and what commands name (role: "editor"), so choose them as a stable storage vocabulary.

Several resource types

One sharing instance can serve several resource types, each with its own roles, actions, and storage adapter. Use a separate adapter for every concrete table, even when two types share ID formats: the resource type selects the adapter and its valid labels.

import { definePolicy } from "rolebook";
import { defineSharing, type SharingAdapter } from "@rolebook/sharing";

declare const projectAdapter: SharingAdapter;
declare const folderAdapter: SharingAdapter;

const managed = ["manage_members", "manage_invitations", "transfer_ownership"] as const;

const multiTypePolicy = definePolicy({
  resources: {
    project: { actions: ["view", ...managed] },
    folder: { actions: ["browse", ...managed] },
  },
  roles: {
    project_owner: { scope: "project", rules: [{ effect: "allow", permission: "project:*" }] },
    project_editor: { scope: "project", rules: [{ effect: "allow", permission: "project:view" }] },
    folder_owner: { scope: "folder", rules: [{ effect: "allow", permission: "folder:*" }] },
    folder_contributor: { scope: "folder", rules: [{ effect: "allow", permission: "folder:browse" }] },
  },
});

const multiTypeDefinition = defineSharing({
  policy: multiTypePolicy,
  resources: {
    project: {
      memberRoles: { editor: "project_editor" },
      ownershipRole: "project_owner",
      actions: { view: "project:view" },
      management: {
        members: "project:manage_members",
        invitations: "project:manage_invitations",
        ownership: "project:transfer_ownership",
      },
      adapter: projectAdapter,
    },
    folder: {
      memberRoles: { contributor: "folder_contributor" },
      ownershipRole: "folder_owner",
      actions: { browse: "folder:browse" },
      management: {
        members: "folder:manage_members",
        invitations: "folder:manage_invitations",
        ownership: "folder:transfer_ownership",
      },
      adapter: folderAdapter,
    },
  },
});

createSharing

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

const projects = createSharing({
  definition,
  identity,
  invitationTokens: createHmacInvitationTokens(process.env.SHARING_INVITATION_KEY!),
  listingCursorKey: process.env.SHARING_LISTING_CURSOR_KEY!,
});

const session = projects.forTenant({ tenantId: "ws_456", actor: { type: "user", id: "user_123" } });
const decision = await session.authorize({ resource: { type: "project", id: "project_1" }, action: "update" });
OptionDefaultMeaning
definitionrequiredThe defineSharing() result (it is validated again).
identityrequiredThe TenantIdentityAdapter for your provider.
invitationTokensrequiredProtects invitation secrets; use createHmacInvitationTokens(key).
clocksystem clock{ now(): Date }. Share one clock with the storage adapter in tests. Listing pages decide expiry at the storage adapter’s own instant, not this clock.
idscrypto.randomUUID(){ next(): string } for invitation and audit event IDs.
mutationRetries3Extra attempts after a revision conflict, an integer from 0 to 10.
mutationBackoffMs(retry)capped exponential backoff with full jitterPause before retry retry (1 for the first), 0 to 1,000 ms.
mutationWait(ms)a timerPerforms a positive pause; inject one for deterministic tests.
maxInvitationTtlMs30 daysThe longest invitation lifetime issueInvitation accepts.
listingCursorKeya random key per instanceSeals listing and audit cursors; a key or an ordered list of up to 8 keys to rotate.
inspectiondisabled{ audit, limiter }: enables current-state inspection. Both hooks must be functions, or construction throws a TypeError.
diagnosticsomitted{ observe?, queueLimit?, observerTimeoutMs? }: enables factory-local operational diagnostics. Omitted, no operation is instrumented. An invalid value throws TypeError("Invalid sharing diagnostics options").

createSharing() returns a ResourceSharingWithDiagnostics: { forTenant(context), inspectionEnabled, diagnostics() }. diagnostics() is a synchronous, frozen snapshot of this instance in this process; with diagnostics omitted it reports enabled: false and zero counts. Diagnostics are implemented but not yet released and not production-qualified. A TenantContext is { tenantId, actor }: the explicit tenant and the authenticated actor reference. The returned TenantSharing has authorize, execute, listAccessible, describeAccess, permissions, listAccess, auditHistory, and explain.

What listing needs from this configuration

authorize(), permissions(), and commands work with any conforming storage and identity adapter. listAccessible() and listAccess() are stricter: each page is read at one coherent point, so the adapters you pass here must be able to supply one. Check three things when you assemble the instance:

  • The storage adapter’s executor. PostgreSQL needs the checked createPgExecutor(pool) executor and text tenant and resource ID columns. SQLite needs the worker-backed createBunSqliteQueryExecutor() executor; the executors from @rolebook/sharing-sqlite/bun and /libsql do not supply the page snapshot. The executor is recognized by provenance, so a wrapped or hand-built one does not qualify. The in-memory adapter needs nothing further.
  • Eligibility evidence. The built-in membership and local-projection eligibility fences supply it. Any other fence, a custom lockEligibleSubjects (or, in memory, fenceEligibleSubjects) or the Teams fences from createPostgresTeamFences() and createBetterAuthTeamFences(), needs a matching readEligibleSubjects that reads the same authority.
  • Identity evidence for identity. Either the storage adapter’s pageIdentity option names this exact identity object together with the local projection it answers from, or the identity adapter implements resolvePagePrincipal (an external source with a non-repeating revision) or, in memory, capturePagePrincipal. The Better Auth, Clerk and WorkOS identity adapters and withTeams() implement neither page method. To list, use an identity adapter that answers exclusively from a complete local projection and name it in pageIdentity; naming the provider-backed identity itself does not qualify.

These are listing requirements; construction does not check them, and other operations have their own documented requirements. A configuration that lacks one of them rejects its listings with AccessListingUnavailableError and a reason (capability_missing or identity_evidence_missing); they never return a weaker page. What a consistent page requires has the details and an example.

Secret keys

createHmacInvitationTokens(key) digests invitation secrets with HMAC-SHA256, and listingCursorKey seals cursors with keys derived through HKDF-SHA256. Both need at least 32 bytes of secret random data, never a passphrase. Create a key once and store it as a secret:

bun -e 'import { generateInvitationTokenKey } from "@rolebook/sharing"; console.log(generateInvitationTokenKey())'

A generated key is text of the form rbk1_<32 random bytes as base64url><6-character check>, used as its UTF-8 bytes. generateListingCursorKey() produces the same form, so one secret can back both.

  • A string key must be a generated key: its check must match. A passphrase, a hand-typed key, or a generated key with a changed character or surrounding whitespace throws at construction.
  • Any other random secret goes in as bytes: Buffer.from(hexKey, "hex"), or any Uint8Array of at least 32 bytes. Byte keys are only checked for length and for at least 8 distinct byte values, which catches placeholders, not weak secrets.
  • Keys are copied at construction; clearing your buffer later changes nothing. Only strings and Uint8Array (including Buffer) are accepted.
  • Keep the invitation key stable: a new key invalidates every outstanding invitation. To rotate cursor keys, pass [newKey, oldKey]: the first seals new cursors and every listed key opens old ones.
  • Without a listingCursorKey, each instance seals with its own random key, so cursors work only within the instance that issued them. Configure a shared key for several processes, or for paging across restarts.

Upgrading an existing string key

A random key already in use as a plain string (from an older release or openssl rand) no longer passes as a string. Keep it, and every outstanding invitation and cursor, with new TextEncoder().encode(existingKey): a string has always been used as its UTF-8 bytes. Do not decode it from hex or base64, which changes the key. If the old key is a passphrase, generate a new key and re-issue outstanding invitations instead.

Versioned policies

createSharing() evaluates the policy in its definition and never reads a store. To publish policy changes at runtime and give tenants custom roles, use createVersionedSharing() instead: it has the same tenant API plus policy and custom-role administration. Its listings read the active policy inside each page’s snapshot, so create the policy store on the same executor object as the resource adapter and pass the store itself, not a wrapper; see versioned policy.