Rolebook

Integrations and tools

Fits the stack you already have

Keep sharing in your own PostgreSQL or SQLite database, connect Better Auth, Clerk, or WorkOS, drop in React sharing UI, deliver signed webhooks, decide writes in the same transaction, serve checks over HTTP or offline, and use the CLI or agent skills.

How it works

01 · Integrations and tools

PostgreSQL and SQLite storage

What it does
Storage adapters keep members, invitations and history in your own database, next to the items they protect.
Why it matters
Your access data stays with your data, inside your own backups and your own region.
How it works
Both adapters work with the database client you already use. They create their own tables per kind of item and run each change in one transaction.
  • PostgreSQL: works with pg, Postgres.js, Kysely, Drizzle or your own client. Migrations run one step at a time, with lock timeouts and retries.
  • SQLite: bun:sqlite, better-sqlite3, node:sqlite or a local libSQL database, in WAL mode, for local-first, edge and desktop apps.
  • Both pass the same adapter security contract as the in-memory test adapter.

Read the docs: PostgreSQL and SQLite storage

02 · Integrations and tools

Writes decided in the same transaction

What it does
Your own update to an item runs only if the person may make it, inside the database transaction that decides it.
Why it matters
A check made before a write can be out of date when the write lands. Deciding inside the transaction means access removed a moment earlier can't slip through.
How it works
The protected-write adapter reads the rules, the person's roles from a table in your database, and the item's sharing state inside the transaction, runs your SQL, and commits it with a receipt and an outbox event. A retry with the same key returns the saved receipt. Managed update, delete and move write the SQL themselves; a managed update checks field rules on the item before and after the change.
  • PostgreSQL in a SERIALIZABLE transaction. SQLite through the Bun and local libSQL executors, and through the Bun worker executor that named queries use.
  • A delivery worker hands committed outbox events to a sink you write, at least once, one bounded pass per call.
  • Your SQL stays trusted code: the raw callback is decided for the whole item and action, not field by field.
  • It is a TypeScript API in your server. The Python, Go and Rust clients do not extend this transaction.
protected-write.ts
const scoped = protectedWrites.forScope({
  tenantId: "acme",
  actor: { type: "user", id: "ada" },
});

const outcome = await scoped.withAuthorizedTransaction(
  {
    resource: { type: "document", id: "q3_report" },
    incarnationId,
    action: "update",
    idempotencyKey: "rename-q3_report",
    payload: { title: "Q3 report, final" },
    postVersion: nextVersion,
  },
  async (guard) => {
    // Runs only if Ada may update it, in the same transaction as that decision.
    await guard.executor.query(
      "UPDATE document SET title = $1, version = $2 WHERE tenant_id = $3 AND id = $4 AND version = $5",
      ["Q3 report, final", nextVersion, "acme", "q3_report", guard.resourceVersion],
    );
    return { version: nextVersion };
  },
);
// outcome.status: "committed", or "replayed" for a retry with the same key
// outcome.receipt: saved with the change, next to an outbox event

Read the docs: Writes decided in the same transaction

03 · Integrations and tools

Better Auth, Clerk and WorkOS

What it does
Identity adapters read users, organizations, and memberships from your sign-in provider. If you use Better Auth, a drop-in plugin wires up the server endpoints, client, and React hooks too.
Why it matters
You keep one source of truth for who belongs where, while Rolebook handles what each person can do with each item.
How it works
The identity adapters look up users and organizations explicitly (never trusting an active-workspace cookie) and never turn workspace membership into access to private items unless you map roles explicitly. @rolebook/better-auth mounts session-bound Sharing endpoints directly on Better Auth with PostgreSQL or SQLite.
  • Better Auth: use @rolebook/better-auth for the all-in-one server, client, and React plugin, or @rolebook/sharing-better-auth for the standalone identity adapter. @rolebook/teams also reads Better Auth organization teams.
  • Clerk: @rolebook/sharing-clerk reads users, organizations, memberships, and roles.
  • WorkOS: @rolebook/sharing-workos reads users, organizations, active memberships, roles, and Directory Sync groups.
  • For paged lists (listAccessible / listAccess), keep a local identity projection table in the same database so Rolebook can read identity and items in one consistent snapshot.

Read the docs: Better Auth, Clerk and WorkOS

04 · Integrations and tools

React sharing components

What it does
Ready-to-use, accessible React components for member lists, invitations, ownership transfer, and audit logs, plus a framework-free headless state layer.
Why it matters
You can build sharing screens quickly without re-implementing duplicate-submit guards, confirmation dialogs, or keyboard accessibility.
How it works
@rolebook/react wraps @rolebook/client with SharingProvider, hooks, and UI components (MembersList, InviteMember, OwnershipTransfer, AuditLog, IntentPanel, ConfirmDialog). Your server still decides every read and write; the browser only shows permission hints and prevents accidental double sends across clicks and tabs.
  • @rolebook/react/core has no React import, so you can reuse the access cache and mutation runner in other UI frameworks.
  • Browser storage keeps only digests, keys, and timestamps, never emails, roles, or invitation tokens.
  • Pair with @rolebook/better-auth/react to add RolebookSharingProvider and the useCan hook wired to your Better Auth session.

Read the docs: React sharing components

05 · Integrations and tools

Signed access-change webhooks

What it does
Send signed HTTP notifications to your own services or other tools whenever access to an item changes.
Why it matters
Billing, search indexes, and external integrations stay in sync with access changes without polling your database.
How it works
@rolebook/server/webhooks drains committed audit rows from PostgreSQL or SQLite and delivers six access-change events (member grants, role changes, removals, ownership transfers, and issued or accepted invitations) at least once, in commit order per item, with exponential backoff and dead-letter handling. Receivers verify requests with @rolebook/http/webhooks.
  • Every request is signed with HMAC-SHA-256 (rolebook-webhook-signature) and carries a stable rolebook-webhook-id for deduplication.
  • Delivery reads only committed audit rows, so rolled-back changes are never sent.
  • Configure endpoints in code or with ROLEBOOK_WEBHOOK_* environment variables.

Read the docs: Signed access-change webhooks

06 · Integrations and tools

The HTTP API

What it does
Serve Rolebook Sharing over HTTP from your own server, and call it from the browser with a typed client.
Why it matters
Front ends and other services get the same answers as your server code, through one documented contract.
How it works
@rolebook/http defines seven operations, a conditional form of execute, and an OpenAPI 3.1 document. @rolebook/server mounts them in any fetch server, Hono or Next.js, takes the person and organization from your trusted session, and checks the request origin. @rolebook/client is a typed fetch client, and the repository carries Python, Go and Rust clients.
  • Six operations for everyday use: authorize, permissions, describe access, list accessible items, audit history and execute a change.
  • The seventh, sharing.explain, is the opt-in inspection described under Sharing. Your server serves it only when inspection is switched on.
  • @rolebook/client and the Python SDK call all seven. The Go and Rust SDKs call the first six and have no explain method.
route.ts
// app/api/sharing/[...rolebook]/route.ts
import { createSharingRouteHandlers } from "@rolebook/server/next";

export const { POST, OPTIONS } = createSharingRouteHandlers({
  basePath: "/api/sharing",
  sharing,
  getContext, // tenant and actor from your trusted session, never from the request body
});

Read the docs: The HTTP API

07 · Integrations and tools

A decision service for your other services

What it does
An HTTP handler that answers single checks or batches of up to 100 checks (including optional field checks) for services written in any language.
Why it matters
Non-TypeScript services get the exact same decisions without re-implementing your rules. Callers name who and what; they can never inject their own roles or facts.
How it works
@rolebook/decision-service authenticates each caller through your verifier, checks its scope grant, loads facts from your authority provider, and runs the Rolebook engine. Every response is either a decision with the policy version used, or a typed no-decision (never an allow or a fake denial).
  • Two routes per scope (single check and batch). Completed decisions return HTTP 200; batches preserve request order.
  • If facts are unavailable, malformed, or too old, the service answers no-decision rather than falling back to stale or empty roles.
  • Mounts inside your own server, which handles TLS and rate limiting. Fixed concurrency and timeout budgets (64 KiB max body, 2 s single check, 5 s batch) are built in.
  • Scoped to permission checks only; sharing mutations, lists, and protected writes stay in @rolebook/sharing.

Read the docs: A decision service for your other services

08 · Integrations and tools

Signed checks for devices without a connection

What it does
An issuer signs a bundle containing everything one check needs. A device or edge worker verifies the signature and runs the same engine offline.
Why it matters
Kiosks, field devices, and edge processes keep enforcing your policy during a network outage without trusting client-modified facts.
How it works
@rolebook/offline issues and verifies Ed25519-signed bundles under a root-signed trust lease. The verifier checks audience, expiry, fact freshness, and anti-rollback state before running the Rolebook engine. Anything it cannot verify returns a no-decision.
  • One bundle covers one exact check until it expires; it is not a general offline policy engine or a write token.
  • Two modes: UI hints for hiding controls, and enforcement on qualified hosts with tamper-resistant clocks and storage. Both run full signature and freshness checks.
  • You supply the clock, state store, Ed25519 functions, and keys. Offline revocation is bounded by lease updates, bundle expiry (at most 24 hours), and key lifetime (at most 7 days).
  • Runs on Node.js 24+ and Bun.

Read the docs: Signed checks for devices without a connection

09 · Integrations and tools

One strict parser at every boundary

What it does
Both the decision service and offline verifier parse JSON through @rolebook/scalars-p1, rejecting duplicate keys, invalid UTF-8, out-of-range numbers, and oversized payloads.
Why it matters
Parsing disagreements between services are a classic way to bypass authorization. One strict parser guarantees every boundary reads the same bytes the same way.
How it works
@rolebook/scalars-p1 reads raw bytes under explicit size and depth limits and returns either a clean value or a typed error without throwing. Exact identifiers and decimals should be sent as strings. Conformance fixtures ship as JSON so other implementations can verify parity.

Read the docs: One strict parser at every boundary

10 · Integrations and tools

Route checks in Hono, Express and Fastify

What it does
Protect a route with one line: the action and the item it needs.
Why it matters
Checks sit next to the routes they protect, and every denial becomes the right status code.
How it works
The middleware builds the request's assignments with your loader, checks the action, and answers 401 when there is no session and 403 when the answer is no. Hono, Express 5 and Fastify 5 share one trusted-binding contract and the same tests.
  • Hono: rolebook/middleware/hono, with an error handler that turns a thrown denial into a 403.
  • Express 5: rolebook/middleware/express, on the framework's own error pipeline.
  • Fastify 5: rolebook/middleware/fastify, on the framework's own error pipeline.
server.ts
import { Hono } from "hono";
import { createRolebookMiddleware, type RolebookEnv } from "rolebook/middleware/hono";
import { loadBinding, loadProject } from "./app";
import { policy } from "./policy";

export const app = new Hono<RolebookEnv<typeof policy>>();
const rolebook = createRolebookMiddleware({ policy, getBinding: loadBinding });
app.onError(rolebook.onError);

app.patch(
  "/projects/:id",
  rolebook.requirePermission(async (c) => ({
    permission: "project:update",
    resource: await loadProject(c.req.param("id")),
  })),
  (c) => c.json({ updated: true }),
);

Read the docs: Route checks in Hono, Express and Fastify

11 · Integrations and tools

CLI and local MCP server

What it does
One command-line tool (@rolebook/cli) to scaffold policies, check your setup, diff policies, explain or change access on your own server, and run a local MCP server for AI agents.
Why it matters
Developers and support engineers can inspect access or compare staging and production policies straight from the terminal, without extra dashboards.
How it works
Run rolebook init, doctor, explain, access, policy diff, or mcp. Every write previews the change first and applies only when you confirm the exact revision. The local MCP server runs over stdio using the credentials you provide, with your own Rolebook permissions still enforced.
terminal
npx --no rolebook init
npx --no rolebook doctor
npx --no rolebook explain --resource project:q3-report --action delete --subject user:ada
npx --no rolebook access describe --resource project:q3-report
npx --no rolebook access grant --resource project:brand-assets --subject team:design --role editor --until 2027-03-31
npx --no rolebook policy diff staging.json production.json

Read the docs: CLI and local MCP server

12 · Integrations and tools

Agent skills

What it does
Skills that teach a coding agent to add Rolebook to your app the right way.
Why it matters
An agent that knows Rolebook's rules sets it up correctly and explains a no from your own code.
How it works
Each skill is a set of instructions for the agent, with code snippets that are type-checked against the Rolebook packages.
  • rolebook-setup

    Adds Rolebook to a Next.js or Hono app.

  • rolebook-add-sharing

    Makes one kind of item shareable.

  • rolebook-add-screens

    Adds a share dialog, history and permission-aware buttons.

  • rolebook-write-roles

    Writes and tests roles and rules.

  • rolebook-debug-denial

    Finds out why someone got a no.

  • rolebook-launch-review

    Reviews an app for access mistakes before launch.

  • rolebook-mount-api

    Mounts the sharing HTTP API and calls it from the browser.

  • rolebook-custom-roles

    Publishes policy versions and custom roles per customer.

  • rolebook-operate-sharing

    Runs sharing migrations, pruning and secrets in production.

  • rolebook-write-adapter

    Writes a storage adapter and proves it with the contract suite.

Read the docs: Agent skills

13 · Integrations and tools

Move from Casbin or a role table

What it does
Plan a move to Rolebook from a Casbin role model or from your own role table, and compare the old and the new answers before you switch.
Why it matters
You see exactly what would be imported, and every request where the two systems disagree, while your app keeps enforcing what it enforces today.
How it works
@rolebook/migrate checks a Casbin source against one exact, documented subset and refuses anything outside it with a precise reason instead of approximating. It plans a policy and its assignments, compares plans so an import can be applied again safely and rolled back, and compares decisions in shadow. Every function is pure: nothing reads a file, writes to a store or switches enforcement.
  • The accepted Casbin model is role-based access with exact matching on subject, object and action. Domains, deny or priority effects and custom matchers are refused, each with its own code.
  • Roles are declared by you, never inferred from the policy lines.
  • Applying a plan to your database is your app's code. The repository has a tested SQLite recipe for applying a plan atomically and rolling assignments back.

Read the docs: Move from Casbin or a role table

14 · Integrations and tools

Runnable recipes

What it does
Two complete programs to start from: an access list with per-document roles, and HTTP routes that check access before they answer.
Why it matters
You begin with code that runs and shows each decision, instead of assembling the pieces from reference pages.
How it works
The ACL recipe shows that membership is not a role, that a block wins, and that removing one grant leaves a team's grant in place. The HTTP recipe guards Hono routes and answers a denial, a missing document and another tenant's document with the same 404. Both run with Bun from a checkout of the repository and are not part of the npm package.

Read the docs: Runnable recipes

Next: Security model

Ship enterprise-ready access control from day one.

Allow wisely.