Rolebook

Open source · Authorization and sharing for TypeScript

Allow wisely.

Fine-grained permissions and resource sharing built for B2B apps. Rolebook runs inside your server with zero external calls, explains every decision, and keeps memberships, teams, webhooks, and audit logs in your own database.

Which permissions each role has
ViewEditShareDelete
Admin
Editor
Viewer
Contractor

Pick a square to see why.

Interactive demo

Change a role. See the decision.

Powered by the real Rolebook engine in your browser. Toggle Maya's roles or request context to see how rules, conditions, and explicit denies interact.

Maya's roles in the Design workspace
What Maya tries to do
The situation
Rolebook's answer
AllowedALLOWED

One of Maya's roles allows this, and no rule forbids it.

Decided by Editor

Capabilities

One decision engine. Every surface.

Evaluate permissions in-process with zero network overhead. Extend the exact same policy to your database, other services over HTTP, and offline devices.

Explore all capabilities
  1. Workspace and item roles.

    Scope any role to an organization, workspace, or single item. The same person can be a Viewer in one workspace and an Editor in another.

  2. Explicit denies always win.

    Deny rules evaluate before allow rules across direct roles, inheritance, and teams. Malformed or missing input always fails closed.

  3. Conditions and field rules.

    Gate actions on trusted facts about the user, item, or request, and allow or block individual fields like billing details.

  4. Sharing, teams, and folders.

    Share projects or documents with people and teams, send expiring invitations, and opt into inherited folder access on PostgreSQL or SQLite.

  5. Audit trail and signed webhooks.

    Commit every access change alongside its history entry, filter tables to authorized rows, check access inside writes, and deliver HMAC-signed webhooks.

  6. In-process, HTTP, or offline.

    Run inside your server with zero network calls, serve checks to other languages over HTTP, verify signed checks offline, or shadow-test a Casbin migration.

Developer experience

Type-safe policies in your repository

Write roles once in plain TypeScript. Permissions are checked at compile time, reviewed in pull requests, and versioned alongside the code that relies on them.

Declare resources, actions, and roles in one file. Validated and frozen once at startup.

policy.ts
import { definePolicy } from "rolebook";

export const policy = definePolicy({
  resources: {
    organization: { actions: ["read"] },
    workspace: { parent: "organization", actions: ["read", "update"] },
    project: { parent: "workspace", actions: ["read", "update", "delete"] },
  },
  roles: {
    workspace_viewer: {
      scope: "workspace",
      rules: [{ effect: "allow", permission: "project:read" }],
    },
    workspace_editor: {
      scope: "workspace",
      inherits: ["workspace_viewer"],
      rules: [
        {
          effect: "allow",
          permission: "project:update",
          where: { fact: "resource.ownerId", operator: "equals", value: { fact: "subject.id" } },
        },
      ],
    },
    contractor: {
      scope: "workspace",
      rules: [{ effect: "deny", permission: "project:delete" }],
    },
  },
});

Bind the signed-in user and their scoped assignments, then check one concrete action.

check.ts
import { createAuthorizer, trustedResource } from "rolebook";
import { policy } from "./policy";

const ada = { type: "user", id: "ada" } as const;
const acme = { type: "workspace", id: "acme" } as const;
const inAcme = { resource: acme, appliesTo: "descendants" } as const;

export const authorization = createAuthorizer(policy).bind({
  subject: ada,
  assignments: [
    { subject: ada, role: "workspace_editor", scope: inAcme },
    { subject: ada, role: "contractor", scope: inAcme },
  ],
});

export const project = trustedResource(
  { type: "project", id: "q3_report" },
  [acme, { type: "organization", id: "org_1" }],
  { ownerId: "ada" },
);

authorization.check({ permission: "project:update", resource: project });
// { allowed: true, code: "ALLOWED", ... }

authorization.check({ permission: "project:delete", resource: project });
// { allowed: false, code: "EXPLICIT_DENY", ... }

Inspect every rule evaluated in order, or call enforce() to throw on denial.

explain.ts
import { authorization, project } from "./check";

const explanation = authorization.explain({ permission: "project:delete", resource: project });

explanation.code;    // "EXPLICIT_DENY"
explanation.reason;  // "A deny rule matched."
explanation.matched; // { effect: "deny", role: "contractor", permission: "project:delete" }
explanation.trace;   // every rule Rolebook evaluated, and whether it matched

authorization.enforce({ permission: "project:delete", resource: project });
// throws AuthorizationError, with the decision on error.decision

First-party middleware for Hono, Express 5, and Fastify 5 returns 401 or 403 before handlers run.

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 }),
);

Grant a team temporary access through @rolebook/sharing and page through the audit log.

share.ts
const tenant = sharing.forTenant({ tenantId: "acme", actor: { type: "user", id: "sam" } });

// Share Brand assets with the Design team as editors, until 31 March.
await tenant.execute({
  kind: "grantRole",
  resource: { type: "project", id: "brand_assets" },
  subject: { type: "team", id: "design" },
  role: "editor",
  expiresAt: new Date("2027-03-31T00:00:00Z"),
  idempotencyKey: "share-brand-assets",
});
// { ok: true, code: "APPLIED", ... }

const history = await tenant.auditHistory({
  resource: { type: "project", id: "brand_assets" },
  limit: 50,
});
// newest first, a page at a time

Integrations

Built for the stack you already run

Connect Better Auth, Clerk, or WorkOS for identity, keep sharing tables in PostgreSQL or SQLite, drop in React UI, and deliver signed webhooks from your own server.

See every integration

Sign-in

  • Better Auth plugin@rolebook/better-auth
  • Better Auth adapter@rolebook/sharing-better-auth
  • Clerk@rolebook/sharing-clerk
  • WorkOS@rolebook/sharing-workos

Database

  • PostgreSQL@rolebook/sharing-postgres
  • SQLite@rolebook/sharing-sqlite
  • Teams@rolebook/teams
  • Adapter contract kit@rolebook/sharing-testkit

Frameworks & UI

  • Honorolebook/middleware/hono
  • Express 5rolebook/middleware/express
  • Fastify 5rolebook/middleware/fastify
  • Next.js@rolebook/server/next
  • React components@rolebook/react

Delivery & tools

  • Sharing HTTP server@rolebook/server
  • Signed webhooks@rolebook/server/webhooks
  • Decision service@rolebook/decision-service
  • Signed offline checks@rolebook/offline
  • CLI & MCP server@rolebook/cli

Products

Access controls your customers expect

Built on one open-source engine. Start with roles and add sharing when your product needs it.

Code reviews

What AI coding agents found in the code

Notes from coding agents that read the repository and ran the test suite.

  • Codex Astra 6AI coding agent

    Clear types, consistent behavior, and explicit boundaries make Rolebook easy to follow. Typed policies express intent directly, and decision explanations show why access was granted or denied when building or debugging.

    Read more

    Explicit deny rules, protected invitations, and delegation limits are enforced in the implementation, not just described in docs. Its modular packages fit around your sign-in provider and database, backed by a thorough test suite covering edge cases and sharing workflows.

  • Grok 4.7AI coding agent

    Rolebook is careful in the places authorization usually gets vague. The API is small, the types name the request and the answer, and every check follows one decision path.

    Read more

    A deny is decided before an allow across direct roles, inheritance, and teams; managers cannot grant a stronger role than they hold; and strangers cannot tell a private resource from a missing one. Running the core suite confirmed those rules hold in practice.

  • Claude Fable 5.1AI coding agent

    Rolebook's core is small enough to read in a sitting, with zero runtime dependencies and strict TypeScript settings where the types carry real meaning. Policies, bindings, and requests are copied into frozen snapshots before evaluation, and comments explain why each invariant exists.

    Read more

    Everything in the security model is backed by code and tests: malformed input becomes a coded denial, internal faults fail closed, and sharing enforces delegation ceilings and rechecks invitations at acceptance. Per-file coverage gates, type-level tests, and the reusable adapter contract kit give real evidence behind the design.

  • Gemini 4 NeonAI coding agent

    Rolebook gets the basics right and keeps the API small. You write roles once in TypeScript, pass in who is asking and what they are touching, and the same engine decides whether the call runs in a route, over HTTP, or offline.

    Read more

    Your memberships and audit logs stay in your own PostgreSQL or SQLite database, and sign-in stays with Better Auth, Clerk, or WorkOS. What stood out most in the repo is how much is verified automatically: the docs type-check their own snippets and API signatures against the built packages, and the tests target real failure modes like field leaks, concurrent writes, and cross-tenant bugs.

Ship enterprise-ready access control from day one.

Allow wisely.

Free and open source under the Apache 2.0 licence.