Better Auth plugin
@rolebook/better-auth: Rolebook Sharing as a Better Auth 1.7.14 plugin, with a client plugin and React bindings.
@rolebook/better-auth serves the Sharing operations from the Better Auth session. The actor is the
signed-in user and the tenant is the session’s active organization, read from Better Auth’s
authoritative session; nothing in a request body, a client-side scope or a customSession
projection selects them. Decoding, decisions, fences and error mapping are the existing ones of
@rolebook/sharing, its SQL adapters and @rolebook/server/core.
| Entry | Use |
|---|---|
@rolebook/better-auth | Server: createBetterAuthSharing, rolebook, getRolebook, getRolebookMigrations |
@rolebook/better-auth/postgres | Server only: createPostgresBetterAuthSharing, the PostgreSQL-bound kit factory with PostgresSharingAdapter adapters |
@rolebook/better-auth/sqlite | Server only: createSqliteBetterAuthSharing, the SQLite-bound kit factory with SqliteSharingAdapter adapters |
@rolebook/better-auth/client | Browser: rolebookClient, createScopeController |
@rolebook/better-auth/react | Browser: RolebookSharingProvider, useRolebookScope, useCan |
Not on npm yet
The @rolebook/* packages are not on npm yet. The npm package named rolebook is an unrelated project, so do not install it.
It needs better-auth >=1.7.14 <1.8 with the organization plugin and server-side sessions, and the
application installs the mandatory @rolebook/sharing peer, the SQL adapter it uses, and for the
browser entries @rolebook/client, nanostores and (React) @rolebook/react with react
>=18.3 <20.
Set up on PostgreSQL
Build the kit before betterAuth(): nothing in it needs the auth object. Better Auth and Rolebook
use the very same pg pool.
storage.executor must be the very object createPgExecutor(pool) returns. Strict listing
(sharing.listAccessible) opens its read-only page only on that checked executor. With a proxy or
wrapper in its place, every page answers 503 ACCESS_LISTING_UNAVAILABLE (capability_missing).
import { createBetterAuthSharing, getRolebookMigrations, rolebook } from "@rolebook/better-auth";
import { createHmacInvitationTokens } from "@rolebook/sharing";
import { createPgExecutor } from "@rolebook/sharing-postgres";
import { betterAuth } from "better-auth";
import { organization } from "better-auth/plugins";
import pg from "pg";
import { definePolicy, trustedResource } from "rolebook";
const policy = definePolicy({
version: "1",
resources: {
workspace: { actions: ["read"] },
project: { parent: "workspace", actions: ["read", "update", "share"] },
},
roles: {
project_owner: { scope: "project", rules: [{ effect: "allow", permission: "project:*" }] },
project_editor: {
scope: "project",
rules: [
{ effect: "allow", permission: "project:read" },
{ effect: "allow", permission: "project:update" },
],
},
},
});
const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });
export const kit = await createBetterAuthSharing({
storage: { dialect: "postgres", pool, executor: createPgExecutor(pool) },
definition: {
policy,
resources: {
project: {
memberRoles: { editor: "project_editor" },
ownershipRole: "project_owner",
actions: { read: "project:read", update: "project:update", share: "project:share" },
management: { members: "project:share", invitations: "project:share", ownership: "project:share" },
},
},
},
descriptors: {
project: {
resourceType: "project",
table: ["app", "project"],
tenantColumn: "workspace_id",
idColumn: "id",
resourceVersionColumn: "version",
sharingTablePrefix: "project",
resourceFromRow: (row) =>
trustedResource({ type: "project", id: String(row.id) }, [
{ type: "workspace", id: String(row.workspace_id) },
]),
},
},
invitationTokens: createHmacInvitationTokens(process.env.ROLEBOOK_INVITATION_KEY ?? ""),
listingCursorKey: process.env.ROLEBOOK_LISTING_CURSOR_KEY ?? "",
});
export const auth = betterAuth({
database: pool, // the same pool object
emailAndPassword: { enabled: true },
plugins: [organization(), rolebook(kit)],
});
// Better Auth's own migration, then the application's tables, then Rolebook's explicit plan.
await (await auth.$context).runMigrations();
await pool.query(
"CREATE TABLE IF NOT EXISTS app.project (workspace_id text NOT NULL, id text NOT NULL, version text NOT NULL, PRIMARY KEY (workspace_id, id))",
);
await getRolebookMigrations(auth).apply(); The keys come from your secret store (generateListingCursorKey() and the invitation-token key
generator of @rolebook/sharing); the factory refuses an empty listing key.
The kit’s identity reads Better Auth’s member and user rows (and, with teams, team and
teamMember) through the Rolebook executor. Strict sharing.listAccessible pages resolve the actor
with the same function inside the page’s own read-only transaction, so a page always reflects
Better Auth’s rows as of that page. A malformed Better Auth directory fails the page closed
(503 ACCESS_LISTING_UNAVAILABLE).
Versioned policy
With storage.policyStore, the kit is registered before it is initialized: building it, registering
rolebook(kit) and serving requests read, seed and migrate nothing. Keep the same order: Better
Auth’s migration, the application’s tables, then getRolebookMigrations(auth).apply().
apply() does the following:
- It runs the idempotent policy-store and sharing steps.
- It builds the versioned Sharing instance, which seeds and activates the policy on an empty store.
- It publishes Sharing, the core and the
"<generation>:<digest>"label together.
Concurrent calls share one attempt. A failed call can be repeated, and a later call never seeds again.
Until then, and after kit.close():
- operations, and
GET /rolebook/scopefor a session with an active organization, answer503 SHARING_SCHEMA_UNAVAILABLE; kit.sharing,kit.core,kit.policyLabel()andgetRolebook(auth).forRequest()throwRolebookConfigurationErrorwith the codeMIGRATIONS_PENDING, orKIT_CLOSEDafter close.
A missing session is still 401, and no active organization is still no_active_organization.
rolebook(kit) accepts only a kit createBetterAuthSharing() built. Its init runs no SQL and
refuses, with a RolebookConfigurationError code: an adapter-backed database or a Better Auth
without its built-in Kysely database (ADAPTER_UNSUPPORTED), stateless sessions
(STATELESS_SESSIONS_UNSUPPORTED), a database object other than the kit’s (DATABASE_MISMATCH), a
missing organization plugin (ORGANIZATION_PLUGIN_REQUIRED), and a Better Auth model named like a
Rolebook table (MODEL_NAME_COLLISION). better-auth/minimal given a database object fails in Better
Auth itself (“Direct database connection requires Kysely”) before any plugin initializes; with an
adapter it is ADAPTER_UNSUPPORTED.
Set up on SQLite
Better Auth keeps its own raw bun:sqlite connection; the kit opens and owns separate Rolebook worker
connections (@rolebook/sharing-sqlite/bun-query) to the same database file, so the two never share
a transaction. Open the file by its absolute canonical path and configure Better Auth’s connection
yourself; the kit checks these settings and never changes them.
import { Database } from "bun:sqlite";
import { createBetterAuthSharing, getRolebookMigrations, rolebook } from "@rolebook/better-auth";
import type { CreateBetterAuthSharingOptions } from "@rolebook/better-auth";
import { betterAuth } from "better-auth";
import { organization } from "better-auth/plugins";
declare const sharing: Omit<CreateBetterAuthSharingOptions, "storage">; // definition, descriptors, keys
const database = new Database("/srv/app/data/app.db"); // absolute, canonical, existing file
database.exec("PRAGMA journal_mode = WAL");
database.exec("PRAGMA foreign_keys = ON");
database.exec("PRAGMA synchronous = FULL");
database.exec("PRAGMA busy_timeout = 0");
const kit = await createBetterAuthSharing({ ...sharing, storage: { dialect: "sqlite", database } });
export const auth = betterAuth({ database, plugins: [organization(), rolebook(kit)] });
await (await auth.$context).runMigrations();
database.exec(
"CREATE TABLE IF NOT EXISTS project (workspace_id TEXT NOT NULL, id TEXT NOT NULL, version TEXT NOT NULL, PRIMARY KEY (workspace_id, id))",
);
await getRolebookMigrations(auth).apply();
// Shutdown: close the kit's Rolebook connections first, then the application's database.
await kit.close();
database.close(); - The filename must be absolute and equal to its
realpath, and the connection’smaindatabase must be that file; in-memory, temporary andfile:URI databases, relative paths,./..segments and symlink aliases are refused (SQLITE_FILE_IDENTITY). - WAL,
foreign_keys = ON,synchronous = FULLandbusy_timeout = 0on Better Auth’s connection are checked when the kit is built and again byapply()(SQLITE_CONNECTION_POLICY). - With
busy_timeout = 0, a write that meets the other connection’s open write transaction fails instead of waiting on the lock. Better Auth reports its own write error. A conflicting Rolebook core-storage operation fails closed as503after the adapter’s bounded retries, with no partial Rolebook state. The public plugin endpoint first obtains an authoritative Better Auth session, and that admission may wait while a Better Auth transaction is open, so endpoint requests have no promise of an immediate HTTP503, cancellation or latency bound. Nothing retries a failed request for the caller. kit.close()closes only the kit’s worker connections (idempotent). After that, every Rolebook operation request is refused at admission with503 SHARING_SCHEMA_UNAVAILABLE, before the core runs, including on a server that has already answered requests. Teams are PostgreSQL only.
Lifecycle on your database
kit.adapters.<type> is a RolebookResourceAdapter from the root entry: the Sharing storage adapter
and initializeResource. The root entry’s types name neither SQL adapter package, so an application
with one of them installed type-checks strictly. For transaction-bound lifecycle work
(withLifecycleTransaction, initializeResourceInTransaction, deletion and moves), build the kit
with createPostgresBetterAuthSharing() from @rolebook/better-auth/postgres or
createSqliteBetterAuthSharing() from @rolebook/better-auth/sqlite. Each accepts only its own
storage.dialect and returns the same kit, typed with that backend’s own adapter. Both entries are
server only.
Endpoints
The plugin adds POST /rolebook/v1/sharing.<operation> for the seven Sharing operations and
sharing.executeIfUnchanged, the conditional form of sharing.execute, with the existing wire format, and GET /rolebook/scope. They are not Better Auth actions, so they add
nothing to auth.api or to path-inferred client methods. For each operation: Rolebook CSRF
(same-origin, or an exact trustedOrigins origin, whatever Better Auth’s own origin settings),
application/json, an authoritative session with an active organization (401 UNAUTHENTICATED
otherwise), the optional x-rolebook-actor / x-rolebook-tenant headers (a mismatch is
401 UNAUTHENTICATED, after Better Auth’s own session read and before any Rolebook core or storage
call), readiness (503 SHARING_SCHEMA_UNAVAILABLE until apply() has run, and after
kit.close()), then @rolebook/server/core. GET /rolebook/scope answers
{ status: "ready", scope: { actor, tenant, policy } }, { status: "no_active_organization" } or
401, and ignores the expected-scope headers. For a static kit, scope does not depend on the Rolebook
tables. For a versioned kit, scope with an active organization checks readiness first. It answers
503 SHARING_SCHEMA_UNAVAILABLE before apply(), after kit.close(), or when the readiness probe
fails or rejects. A request whose readiness probe is in flight when the kit closes answers the same
503, for operations and for versioned scope.
Client and React
import { createScopeController, rolebookClient } from "@rolebook/better-auth/client";
import { createAuthClient } from "better-auth/client";
import { organizationClient } from "better-auth/client/plugins";
export const authClient = createAuthClient({
plugins: [organizationClient(), rolebookClient()],
});
const scope = createScopeController({ rolebook: authClient.rolebook });
scope.subscribe(() => console.log(scope.getSnapshot().status));
scope.start(); // focus, page visible, same-origin channel, this client's session changes, any 401 authClient.rolebook.fetchScope() reads the scope through Better Auth’s configured fetch and base
URL; sharingClientFor() builds the existing @rolebook/client POST client for it, with cookies and
only the actor/tenant refusal headers.
import { RolebookSharingProvider, useCan } from "@rolebook/better-auth/react";
import { MembersList } from "@rolebook/react";
<RolebookSharingProvider
authClient={authClient}
scopeContext={mfaLevel} // optional: view identity only, never sent
actions={{ members: "share", invitations: "share" }}
fallback={<Spinner />}
signedOut={<SignIn />}
noActiveOrganization={<ChooseOrganization />}
unavailable={(code, retry) => <Retry code={code} onRetry={retry} />}
>
<MembersList resource={project} />
</RolebookSharingProvider>; Any change of the server scope or scopeContext remounts the kit view. While the scope is re-read the
previous view stays mounted but hidden and aria-busy, and a capture-phase fence cancels clicks,
submits and activation keys inside it, so none of its controls starts an operation; an operation
already in flight is not cancelled. A closed view’s reads reject before any request and its invitation
tokens are not handed over. useCan(resource, action) is a hint, no_hint until the server answers.
On the server the provider renders fallback and reads nothing.
API
Signatures are checked against the built declarations.
Exports of @rolebook/better-auth
RolebookConfigurationError
class RolebookConfigurationError extends Error {
readonly code: RolebookConfigurationCode;
constructor(code: RolebookConfigurationCode, message: string);
} RolebookConfigurationCode
type RolebookConfigurationCode = "FOREIGN_KIT" | "DATABASE_MISMATCH" | "ADAPTER_UNSUPPORTED" | "STATELESS_SESSIONS_UNSUPPORTED" | "ORGANIZATION_PLUGIN_REQUIRED" | "MODEL_NAME_COLLISION" | "TEAMS_REQUIRE_POSTGRES" | "SQLITE_FILE_IDENTITY" | "SQLITE_CONNECTION_POLICY" | "INVALID_OPTIONS" | "MIGRATIONS_PENDING" | "KIT_CLOSED"; RolebookUnauthenticatedError
class RolebookUnauthenticatedError extends Error {
readonly code: "UNAUTHENTICATED";
constructor(message?: string);
} BetterAuthSharingKit
interface BetterAuthSharingKit<TResources extends Readonly<Record<string, BetterAuthSharingResource>> = Readonly<Record<string, BetterAuthSharingResource>>> {
readonly dialect: "postgres" | "sqlite";
readonly sharing: ResourceSharing<SharingResourceConfigurations> | VersionedResourceSharing<SharingResourceConfigurations>;
readonly database: object;
readonly core: SharingCore;
readonly migrations: RolebookMigrationPlan;
readonly schema: Readonly<Record<string, DisabledModel>>;
readonly policyLabel: () => string;
readonly adapters: {
readonly [K in keyof TResources]: RolebookResourceAdapter;
};
readonly ready: () => Promise<boolean>;
readonly close: () => Promise<void>;
readonly onInternalError: (error: unknown, request: Request) => void;
} BetterAuthSharingResource
type BetterAuthSharingResource = Omit<SharingResourceConfiguration, "adapter">; BetterAuthSharingStorage
type BetterAuthSharingStorage = PostgresStorage | SqliteStorage; CreateBetterAuthSharingOptions
interface CreateBetterAuthSharingOptions<TResources extends Readonly<Record<string, BetterAuthSharingResource>> = Readonly<Record<string, BetterAuthSharingResource>>> {
readonly storage: BetterAuthSharingStorage;
readonly betterAuthTables?: BetterAuthTables;
readonly definition: {
readonly policy: RolebookPolicy;
readonly resources: TResources;
};
readonly descriptors: {
readonly [K in keyof TResources]: PostgresTableDescriptor | SqliteTableDescriptor;
};
readonly invitationTokens: InvitationTokenProtector;
readonly listingCursorKey: string | Uint8Array | readonly (string | Uint8Array)[];
readonly teams?: {
readonly enabled: true;
};
readonly mapWorkspaceAssignments?: BetterAuthIdentityAdapterOptions["mapWorkspaceAssignments"];
readonly inspection?: CreateSharingOptions["inspection"];
readonly maxBodyBytes?: number;
readonly onInternalError?: (error: unknown, request: Request) => void;
readonly sharingOptions?: Pick<CreateSharingOptions, "clock" | "ids" | "mutationRetries" | "mutationBackoffMs" | "mutationWait" | "maxInvitationTtlMs">;
} createBetterAuthSharing
function createBetterAuthSharing<TResources extends Readonly<Record<string, BetterAuthSharingResource>>>(options: CreateBetterAuthSharingOptions<TResources>): Promise<BetterAuthSharingKit<TResources>>; DisabledModel
interface DisabledModel {
readonly modelName: string;
readonly fields: Record<string, never>;
readonly disableMigration: true;
} PostgresStorage
interface PostgresStorage {
readonly dialect: "postgres";
readonly pool: object;
readonly executor: PostgresSqlExecutor;
readonly policyStore?: {
readonly tablePrefix?: string;
readonly schema?: string;
readonly seed?: "activate-if-empty" | "require-active";
readonly refreshIntervalMs?: number;
readonly maxStalenessMs?: number;
};
} RolebookMigrationPlan
interface RolebookMigrationPlan {
readonly dialect: "postgres" | "sqlite";
readonly steps: readonly RolebookMigrationStep[];
compile(): string;
apply(): Promise<void>;
rollback(options?: {
readonly dropAudit?: boolean;
}): readonly RolebookRollbackStep[];
} RolebookMigrationStep
interface RolebookMigrationStep {
readonly name: string;
readonly sql: string;
} RolebookRollbackStep
interface RolebookRollbackStep extends RolebookMigrationStep {
readonly dataLoss?: string;
} SqliteStorage
interface SqliteStorage {
readonly dialect: "sqlite";
readonly database: BunSqliteRawDatabase;
readonly maxConnections?: number;
} getRolebook
function getRolebook(auth: RolebookAuthLike): {
forRequest(headers: Headers): Promise<RolebookRequestScope>;
}; getRolebookMigrations
function getRolebookMigrations(auth: RolebookAuthLike): RolebookMigrationPlan; RolebookAuthLike
interface RolebookAuthLike {
readonly options: {
readonly plugins?: readonly unknown[];
};
readonly api: object;
} RolebookRequestScope
interface RolebookRequestScope {
readonly actor: string;
readonly tenant: string;
can(resource: ResourceKey, action: string): Promise<boolean>;
forTenant(): TenantSharing<SharingResourceConfigurations>;
} RolebookPlugin
type RolebookPlugin = ReturnType<typeof rolebook>; rolebook
function rolebook(kit: BetterAuthSharingKit): {
id: "rolebook";
schema: Readonly<Record<string, import("./factory.js").DisabledModel>>;
endpoints: RolebookEndpoints;
options: {
kit: BetterAuthSharingKit<Readonly<Record<string, import("./factory.js").BetterAuthSharingResource>>>;
};
rateLimit: {
window: number;
max: number;
pathMatcher: (path: string) => boolean;
}[];
init(ctx: import("better-auth").AuthContext): void;
}; RolebookInitializeResourceInput
interface RolebookInitializeResourceInput {
readonly tenantId: string;
readonly resourceId: string;
readonly owner: OwnerRef;
readonly actor: ResourceRef;
readonly occurredAt: Date;
} RolebookInitializeResourceResult
type RolebookInitializeResourceResult = "applied" | "already_initialized" | "identity_ineligible" | "owner_mismatch" | "group_owner" | "not_found"; RolebookResourceAdapter
interface RolebookResourceAdapter extends SharingAdapter {
initializeResource(input: RolebookInitializeResourceInput): Promise<RolebookInitializeResourceResult>;
} BetterAuthTables
interface BetterAuthTables {
readonly schema?: string;
readonly user?: string;
readonly member?: string;
readonly team?: string;
readonly teamMember?: string;
readonly fields?: {
readonly memberId?: string;
readonly memberOrganizationId?: string;
readonly memberUserId?: string;
readonly memberRole?: string;
readonly userId?: string;
readonly userEmail?: string;
readonly userEmailVerified?: string;
readonly userName?: string;
};
} Exports of @rolebook/better-auth/postgres
createPostgresBetterAuthSharing
function createPostgresBetterAuthSharing<TResources extends Readonly<Record<string, BetterAuthSharingResource>>>(options: CreatePostgresBetterAuthSharingOptions<TResources>): Promise<PostgresBetterAuthSharingKit<TResources>>; CreatePostgresBetterAuthSharingOptions
type CreatePostgresBetterAuthSharingOptions<TResources extends Readonly<Record<string, BetterAuthSharingResource>> = Readonly<Record<string, BetterAuthSharingResource>>> = Omit<CreateBetterAuthSharingOptions<TResources>, "storage" | "descriptors"> & {
readonly storage: PostgresStorage;
readonly descriptors: {
readonly [K in keyof TResources]: PostgresResourceDescriptor;
};
}; PostgresBetterAuthSharingKit
type PostgresBetterAuthSharingKit<TResources extends Readonly<Record<string, BetterAuthSharingResource>> = Readonly<Record<string, BetterAuthSharingResource>>> = Omit<BetterAuthSharingKit<TResources>, "dialect" | "adapters"> & {
readonly dialect: "postgres";
readonly adapters: {
readonly [K in keyof TResources]: PostgresSharingAdapter;
};
}; Exports of @rolebook/better-auth/sqlite
createSqliteBetterAuthSharing
function createSqliteBetterAuthSharing<TResources extends Readonly<Record<string, BetterAuthSharingResource>>>(options: CreateSqliteBetterAuthSharingOptions<TResources>): Promise<SqliteBetterAuthSharingKit<TResources>>; CreateSqliteBetterAuthSharingOptions
type CreateSqliteBetterAuthSharingOptions<TResources extends Readonly<Record<string, BetterAuthSharingResource>> = Readonly<Record<string, BetterAuthSharingResource>>> = Omit<CreateBetterAuthSharingOptions<TResources>, "storage" | "descriptors" | "teams"> & {
readonly storage: SqliteStorage;
readonly descriptors: {
readonly [K in keyof TResources]: SqliteResourceDescriptor;
};
}; SqliteBetterAuthSharingKit
type SqliteBetterAuthSharingKit<TResources extends Readonly<Record<string, BetterAuthSharingResource>> = Readonly<Record<string, BetterAuthSharingResource>>> = Omit<BetterAuthSharingKit<TResources>, "dialect" | "adapters"> & {
readonly dialect: "sqlite";
readonly adapters: {
readonly [K in keyof TResources]: SqliteSharingAdapter;
};
}; Exports of @rolebook/better-auth/client
createScopeController
function createScopeController(options: ScopeControllerOptions): ScopeController; ScopeState
type ScopeState = {
readonly status: "inert";
} | {
readonly status: "verifying";
readonly previous?: ReadyScope;
readonly epoch: number;
} | ReadyScope | {
readonly status: "signed_out";
} | {
readonly status: "no_active_organization";
} | {
readonly status: "unavailable";
readonly code: string;
}; rolebookClient
function rolebookClient(): {
id: "rolebook";
$InferServerPlugin: RolebookPlugin;
getAtoms: () => {
$rolebookScopeSignal: import("nanostores").PreinitializedWritableAtom<boolean> & object;
};
atomListeners: {
signal: "$rolebookScopeSignal";
matcher: typeof changesScope;
callback: () => void;
}[];
getActions: ($fetch: unknown, _store: unknown, options: unknown) => {
rolebook: RolebookActions;
};
}; RolebookActions
interface RolebookActions {
fetchScope(signal?: AbortSignal): Promise<ScopeRead>;
sharingClientFor(server: ServerScope, sharingBase: string, onUnauthenticated: () => void): RolebookSharingClient;
register(controller: {
localChange(): void;
}): () => void;
} ScopeRead
type ScopeRead = {
readonly kind: "ready";
readonly scope: ServerScope;
readonly sharingBase: string;
} | {
readonly kind: "no_active_organization";
} | {
readonly kind: "signed_out";
} | {
readonly kind: "unavailable";
readonly code: string;
}; Exports of @rolebook/better-auth/react
RolebookSharingProvider
function RolebookSharingProvider(props: RolebookSharingProviderProps): ReactNode; RolebookSharingProviderProps
type RolebookSharingProviderProps = Omit<SharingProviderProps, "client" | "scope"> & {
readonly authClient: {
readonly rolebook: RolebookActions;
};
readonly scopeContext?: SharingScope["context"];
readonly fallback?: ReactNode;
readonly signedOut?: ReactNode;
readonly noActiveOrganization?: ReactNode;
readonly unavailable?: (code: string, retry: () => void) => ReactNode;
}; useRolebookScope
function useRolebookScope(): ScopeState; useCan
function useCan(resource: SharingResource, action: string, options?: UseCanOptions): UseCanResult;