Better Auth
@rolebook/sharing-better-auth: Better Auth organizations as the source of users and workspace membership.
@rolebook/sharing-better-auth resolves sharing principals from Better Auth’s organization plugin: users,
organizations, organization members, and member roles. It needs better-auth >=1.7.7 <2.
import { createBetterAuthIdentityAdapter, type BetterAuthDirectoryReader } from "@rolebook/sharing-better-auth";
import type { ParameterizedSqlExecutor } from "@rolebook/sharing-postgres";
declare const executor: ParameterizedSqlExecutor; // the same database Better Auth uses
// Read Better Auth's tables directly; adjust table and column names to your Better Auth schema.
const directory: BetterAuthDirectoryReader = {
async getOrganizationMember({ organizationId, userId }) {
const { rows } = await executor.query<{ id: string; organizationId: string; userId: string; role: string }>(
'SELECT id, "organizationId", "userId", role FROM auth.member WHERE "organizationId" = $1 AND "userId" = $2',
[organizationId, userId],
);
return rows.length === 1 ? rows[0] : undefined;
},
async getUser({ userId }) {
const { rows } = await executor.query<{ id: string; email: string; emailVerified: boolean }>(
'SELECT id, email, "emailVerified" FROM auth."user" WHERE id = $1',
[userId],
);
return rows[0];
},
};
export const identity = createBetterAuthIdentityAdapter({ directory }); The reader must query membership with both the organization and user IDs, from an authoritative path: your Better Auth database or its server API.
Behaviour
- Resolution always loads the user (the factory’s
requireUser): a principal is ineligible unless the user exists with the requested ID. The user’semail,emailVerified, and the member’sworkspaceRoleare exposed onprincipal.attributesfor your application, never to Rolebook conditions, because the member-role fence does not protect profile changes. - Membership IDs and roles must be non-empty strings of at most 128 characters; malformed records fail closed.
- Better Auth stores several roles as one comma-separated string (
"admin,member"). The mapper, the authorization fact, andattributes.workspaceRolereceive that string unchanged: match onrole.split(","), not on equality or a substring (includes("admin")also matchessuperadmin). - Email-bound invitations match only a current member whose Better Auth email is verified.
Mapping workspace roles
import { createBetterAuthIdentityAdapter, type BetterAuthDirectoryReader } from "@rolebook/sharing-better-auth";
declare const directory: BetterAuthDirectoryReader;
export const identity = createBetterAuthIdentityAdapter({
directory,
mapWorkspaceAssignments: ({ tenantId, subject, member }) =>
member.role.split(",").includes("admin")
? [
{
subject,
role: "workspace_admin",
scope: { resource: { type: "workspace", id: tenantId }, appliesTo: "descendants" },
},
]
: [],
}); With a mapper, each principal carries a BETTER_AUTH_WORKSPACE_MEMBER_AUTHORIZATION_FACT with the member ID
and role. Configure the storage adapter’s workspace-role fact fence
with that factType and Better Auth’s real id and role columns; without it, mapped management mutations
fail closed.
Fences
Better Auth can share your application database, so its member and user rows can be locked by the
sharing transaction: configure createPostgresMembershipEligibilityFence() (or the SQLite equivalent)
against Better Auth’s member table, and createPostgresEmailInvitationRecipientFence() against member
and user for email invitations. A Better Auth deployment reached only through a remote API cannot be
fenced: issue subject-bound invitations there. For teams, see @rolebook/teams/better-auth.
Listing accessible resources
This adapter answers authorize(), permissions(), and commands. It does not implement
resolvePagePrincipal, so on its own it supplies no identity evidence for
listAccessible() and listAccess(): those calls reject with
AccessListingUnavailableError and the reason identity_evidence_missing. That holds even when Better Auth
shares your database, because the adapter reads through your directory reader and not inside the page’s
snapshot. The membership eligibility fence above does carry the eligibility evidence a page needs; identity
evidence is a separate requirement.
To list, the sharing instance needs an identity adapter that resolves principals from a complete local
identity projection in the same database as the sharing tables: eligibility, assignments, groups, and
attributes. Name that adapter object and the projection in the storage adapter’s pageIdentity option. The
option is an attestation that the adapter passed to createSharing() answers from exactly that projection,
so it must be an adapter that really reads the projection. Do not name this Better Auth adapter as the
source of a projection it does not read. Keep the projection synchronized from Better Auth as authoritative
data, and advance the row’s revision on every change. A sharing instance has one identity adapter, so its
checks and commands then use the projection as well.
The alternative is an identity adapter of your own that implements resolvePagePrincipal over a source
with a revision that never repeats and changes on every relevant change. See
identity for listing.
What every identity adapter guarantees
All three provider adapters are configurations of createWorkspaceIdentityAdapter(),
so they enforce the same rules:
- Every membership lookup receives the explicit organization (tenant) ID and user ID. There is no session or active-organization input.
- Organization membership is eligibility only. No Rolebook assignment is emitted unless you supply
mapWorkspaceAssignments, and then each mapped assignment must target the canonical subject, a role of at most 128 characters, the configured workspace resource type with the explicit tenant ID, andappliesTo"self"or"descendants"; anything else throws. - Records are copied (each field read once) before they are validated, so a cache-backed record cannot answer two checks differently.
- The Rolebook subject is the canonical
{ type, id }only (default type"user", workspace resource type"workspace"). Profile data never reaches conditions. - Invitation matching requires an eligible principal in canonical form and rechecks current membership.
- Provider organization invitations are never created or replaced: resource invitations are separate.
- The member-removed handler validates and freezes the event for cleanup code. It is not an authorization fence: every sharing operation checks current membership.
API
import { ... } from "@rolebook/sharing-better-auth". Signatures are checked against the built declarations.
Exports
createBetterAuthIdentityAdapter
function createBetterAuthIdentityAdapter(
options: BetterAuthIdentityAdapterOptions,
): TenantIdentityAdapter; Builds the TenantIdentityAdapter. Always loads the user while resolving.
BetterAuthIdentityAdapterOptions
interface BetterAuthIdentityAdapterOptions {
readonly directory: BetterAuthDirectoryReader;
readonly subjectType?: string;
readonly workspaceResourceType?: string;
readonly mapWorkspaceAssignments?: (input: {
readonly tenantId: string;
readonly subject: ResourceRef;
readonly member: BetterAuthMemberRecord;
}) => readonly RoleAssignment[];
readonly normalizeEmail?: (email: string) => string;
} directory (required), subjectType, workspaceResourceType, mapWorkspaceAssignments, normalizeEmail.
BetterAuthDirectoryReader
interface BetterAuthDirectoryReader {
getOrganizationMember(input: {
readonly organizationId: string;
readonly userId: string;
}): Promise<BetterAuthMemberRecord | undefined>;
getUser(input: { readonly userId: string }): Promise<BetterAuthUserRecord | undefined>;
} Exact membership and user lookups you implement.
BetterAuthMemberRecord
type BetterAuthMemberRecord = Pick<
BetterAuthOrganizationMember,
"id" | "organizationId" | "userId" | "role"
>; The authority-bearing fields of a Better Auth organization member.
BetterAuthUserRecord
type BetterAuthUserRecord = Pick<BetterAuthUser, "id" | "email"> &
Partial<Pick<BetterAuthUser, "emailVerified" | "name">>; The user fields the adapter reads.
BETTER_AUTH_WORKSPACE_MEMBER_AUTHORIZATION_FACT
const BETTER_AUTH_WORKSPACE_MEMBER_AUTHORIZATION_FACT =
"rolebook.better-auth.workspace-member.v1"; The fact type for the workspace-role fact fence.
createBetterAuthMemberRemovedHandler
function createBetterAuthMemberRemovedHandler(input: {
readonly onMemberRemoved: (event: {
readonly organizationId: string;
readonly userId: string;
}) => void | Promise<void>;
}): (event: {
readonly organization: {
readonly id: string;
};
readonly member: {
readonly userId: string;
};
}) => Promise<void>; Adapts Better Auth’s member-removed hook event ({ organization, member }) to a validated, frozen
{ organizationId, userId } for cleanup.