Storage and identity adapters
The SharingAdapter and TenantIdentityAdapter contracts, the workspace identity factory, and the in-memory adapter.
The sharing module talks to the outside world through two interfaces: a storage adapter per resource
type (SharingAdapter) and one identity adapter (TenantIdentityAdapter). The first-party packages
implement both; this page is for choosing between them and for writing your own.
Storage adapters
| Adapter | Use |
|---|---|
createPostgresSharingAdapter | Production on PostgreSQL. |
createSqliteSharingAdapter | Production on SQLite: local-first, edge, desktop. |
createMemorySharingAdapter | Tests and fixtures only. |
A SharingAdapter owns one concrete resource table’s sharing state. Its methods:
| Method | Contract |
|---|---|
readAccess | One resource’s authoritative snapshot: the trusted resource, its version, the sharing revision, the owner, memberships (only of requestingPrincipals when given), and the incarnation ID. Fences requiredEligibleSubjects in the same read. Leaves out expired memberships. |
readAccessBatch | The same for up to 200 resources in one consistent read; rejects more. |
readInvitation | One invitation by ID. |
listPendingInvitations | Unconsumed, unrevoked invitations in (createdAt, id) order, for the given incarnation, or undefined when it is no longer live. |
listAuditEvents | One page of the incarnation’s audit events, newest first, with a raw cursor. |
readMutationIdempotency | Looks up a committed idempotency record without changing state. |
applyMutation | Applies one mutation atomically, conditional on the expected resource version and sharing revision, fencing eligible subjects, authorization facts, and (when fenced) the policy generation, with the audit event and idempotency record in the same commit. |
listCandidates | One page of candidate resource IDs for listing, with cursors; honours the narrowing hints. |
resourceDeleted, resourceMoved | Standalone lifecycle conveniences, or "unsupported". |
The details that matter for correctness:
-
Eligibility is held, not just checked.
requiredEligibleSubjectsnames subjects whose current tenant eligibility the adapter must hold for the whole read or mutation. PostgreSQL does it with aSERIALIZABLEtransaction andFOR SHARErow locks; SQLite with the write lock ofBEGIN IMMEDIATE. -
Authorization facts. A principal’s
authorizationFacts(mapped workspace roles, team memberships) travel with mutations asrequiredAuthorizationFacts. An adapter must lock and compare every one in the transaction, and fail closed (identity_ineligible) when it has no fence for them. -
Fences fail closed. A fence callback result counts as eligible only when it is literally
true. -
Expiry. Reads leave out memberships at or past
expiresAt; grants and invitation consumption replace an expired row;changeRolekeeps, sets, or clears the expiry;revokeMemberdeletes an expired row. -
Output is captured. Pages and candidates must be plain records with at most 16 own data properties; accessors, class instances, and holes are
InvalidCandidatePageError. Return frozen object literals. -
Cursors.
listCandidatesmust throwInvalidCursorErrorfor anything butundefinedor a non-empty string of at most 128 characters, and every non-exhausted page must return a usable, advancingnextCursor. -
Listing pages.
listAccessible()andlistAccess()do not calllistCandidatesandreadAccessBatchdirectly. They read each page through the optionalrunConsistentPage, which opens one snapshot, runs the candidate and hydration reads inside it, and seals every expiry the page depended on. The first-party adapters implement it, each on a specific executor. A custom adapter without it answerscapability_missingfor both listings. See what a consistent page requires. -
Eligibility evidence for pages. A page proves tenant eligibility inside its snapshot without locks, through a reader that returns
{ eligible, expiryDependencies }from the same authority as the fence.createPostgresMembershipEligibilityFence()andcreateSqliteMembershipEligibilityFence()carry their own reader, as do thelockEligibleSubjectsfences of the PostgreSQL and SQLite local identity projections. Every other fence needs a matchingreadEligibleSubjectson the adapter. That includes a fence you write yourself, a function that wraps one of the fences above, and the team fences fromcreatePostgresTeamFences()andcreateBetterAuthTeamFences(), which carry no reader; see listing with teams. Without the evidence, listings answeridentity_evidence_missing.
Run @rolebook/sharing-testkit against any adapter you write: it is the
executable form of this contract.
The in-memory adapter
createMemorySharingAdapter(options) exists for the contract kit and local fixtures. It holds no
transaction and takes no locks. Configure fenceEligibleSubjects to have it re-check eligibility at the
points the PostgreSQL adapter locks it; without it, every supplied subject counts as eligible. Even fenced,
the check is a re-read rather than a lock, so a concurrent revocation can still interleave. It is not a
production adapter.
import { createMemorySharingAdapter, type SharingClock } from "@rolebook/sharing";
import { trustedResource } from "rolebook";
const clock: SharingClock = { now: () => new Date("2026-11-01T00:00:00Z") };
const members = new Set(["user_123", "user_789"]);
const projects = createMemorySharingAdapter({
clock, // pass the same clock to createSharing()
fenceEligibleSubjects: ({ subjects }) => subjects.every((subject) => members.has(subject.id)),
});
projects.seed({
tenantId: "ws_456",
resourceId: "project_1",
resource: trustedResource({ type: "project", id: "project_1" }, [{ type: "workspace", id: "ws_456" }]),
owner: { type: "user", id: "user_123" },
memberships: [{ subject: { type: "user", id: "user_789" }, role: "viewer" }],
}); seed() starts a new incarnation and records a resource.initialized audit event; readAudit() returns
every audit event; advanceResourceVersion() simulates an application change to the resource. Other options:
fenceInvitationRecipient (required for email invitations), revalidateAuthorizationFacts (required for
mutations authorized by mapped roles or teams), groupSubjectTypes (default ["team"]), and fencePolicy
for versioned sharing. Share one clock between the adapter and createSharing(): both check expiry.
For listAccessible() and listAccess(), an adapter configured with fenceEligibleSubjects also needs
readEligibleSubjects, the same answer as synchronous evidence
({ eligible, expiryDependencies }, judged at the evaluatedAt it is given). The identity adapter must
supply identity evidence as well; the simplest way in a fixture is a synchronous capturePagePrincipal. See
listing page evidence.
Identity adapters
A TenantIdentityAdapter answers two questions, always for an explicit tenant:
import type { TenantIdentityAdapter, TenantPrincipal } from "@rolebook/sharing";
declare function isActiveMember(tenantId: string, userId: string): Promise<boolean>;
const identity: TenantIdentityAdapter = {
async resolvePrincipal({ tenantId, subject }): Promise<TenantPrincipal> {
const eligible = subject.type === "user" && (await isActiveMember(tenantId, subject.id));
return {
eligible,
subject: { type: subject.type, id: subject.id },
tenantScope: { type: "workspace", id: tenantId },
assignments: [], // workspace membership grants no private-resource access by itself
};
},
async matchesInvitationRecipient({ principal, recipient }) {
return (
principal.eligible === true &&
recipient.type === "subject" &&
recipient.subject.type === principal.subject.type &&
recipient.subject.id === principal.subject.id
);
},
}; resolvePrincipal returns a TenantPrincipal:
| Field | Meaning |
|---|---|
eligible | Whether the subject is a current member of exactly this tenant. |
subject | The canonical { type, id }, plus optional attributes Rolebook conditions read. |
tenantScope | The tenant resource reference; its ID must equal the explicit tenant ID. |
assignments | Explicit workspace-scoped Rolebook assignments. Empty is the safe default. |
authorizationFacts | Provider facts behind those assignments or attributes, revalidated by the storage adapter in every mutation. Assignments require at least one subject-scoped fact. |
attributes | Application metadata. Never passed to conditions. |
groups | The subject’s current flat group principals (teams), at most 64. |
group | true when the principal is itself a group, resolved as a grant or invitation target. |
Never derive the tenant from a session’s active organization: every lookup must use the explicit tenant ID. An identity adapter may throw; the module does not catch it, and the operation rejects.
Listing page evidence
resolvePrincipal and matchesInvitationRecipient are all that authorize(), permissions(), and commands
need. listAccessible() and listAccess() read each page at one coherent
point and also need evidence that the principal belongs to that point. An identity adapter that works for
authorize() does not qualify for listing on that basis. There are three ways to supply the evidence:
- A local projection, attested on the storage adapter. The PostgreSQL and SQLite adapters take a
pageIdentityoption naming the identity adapter object given tocreateSharing()and the local identity projection it answers from. The page then reads the projection row inside its own transaction. The option is an attestation: that identity adapter must actually resolve principals from exactly that projection, complete with assignments, groups, attributes, and authorization facts. Naming an adapter that resolves from a remote provider, or a wrapper around one, as the source of a projection it does not read is a false attestation, and Rolebook cannot detect it. The projection has to be kept synchronized as authoritative data, with a revision that advances on every change. resolvePagePrincipal, an optional method for a source outside the database. It returns the complete principal with anepoch, arevisionthat never repeats within the epoch and changes on every relevant change, and the expiry of every time-sensitive fact. Rolebook calls it before the page’s snapshot opens and after the page was read and accepts the page only when both answers are identical. Implement it only over a source that really has such a revision.capturePagePrincipal, an optional synchronous method for the in-memory adapter. It returns{ principal, expiryDependencies }from in-process state, judged at theevaluatedAtit is given, with no I/O.
With none of these, listings reject with AccessListingUnavailableError and the reason
identity_evidence_missing.
createWorkspaceIdentityAdapter
The Better Auth, Clerk, and WorkOS adapters are configurations of one shared implementation, exported so you can build your own provider adapter with the same rules:
import { createWorkspaceIdentityAdapter, type WorkspaceMemberRecord } from "@rolebook/sharing";
interface AppUser {
readonly id: string;
readonly email: string;
readonly emailVerified: boolean;
}
declare function findMember(organizationId: string, userId: string): Promise<WorkspaceMemberRecord | undefined>;
declare function findUser(userId: string): Promise<AppUser | undefined>;
const identity = createWorkspaceIdentityAdapter<AppUser>({
authorizationFactType: "app.workspace-member.v1",
getMember: ({ organizationId, userId }) => findMember(organizationId, userId),
getUser: ({ userId }) => findUser(userId),
snapshotUser: (user) => ({ id: user.id, email: user.email, emailVerified: user.emailVerified }),
verifiedEmail: (user) => (user.emailVerified ? user.email : undefined),
}); - Every membership lookup receives the explicit tenant and subject IDs, and the returned record is copied (each field read once) before it is checked.
mapWorkspaceAssignmentsexplicitly maps a provider role to workspace assignments; the default emits none. Mapped assignments must target the subject, a bounded role, and the tenant scope, or the factory throws. ATransactionalAuthorizationFactwith the member ID and role accompanies them.- With
requireUser, the user is also loaded while resolving, and the principal is ineligible unless it exists; otherwise the user is loaded only to match an email invitation.principalAttributesrequiresrequireUser. snapshotUsermust return a new object: a throw,undefined, or the input itself counts as a missing user. A throwingverifiedEmailcounts as no verified address.- Invitation matching requires
eligible === true, the canonical subject, and current membership. Email recipients compare the verified address after normalization, both bounded by 320 characters.
An adapter built with this factory, including the Better Auth, Clerk, and WorkOS adapters, has
resolvePrincipal and matchesInvitationRecipient only. It supplies no
listing page evidence on its own.
createWorkspaceMemberRemovedHandler({ provider, onMemberRemoved }) validates and freezes a provider’s
member-removal notification before your cleanup code sees it. It is cleanup only: current membership is
still checked on every sharing operation.
Identity and storage must agree
The identity adapter’s answer is a preflight. The storage adapter’s fences make it hold until commit: a membership removal either commits first and the mutation fails, or waits for the already-authorized mutation. That works only when the authoritative membership rows are in the same database as the sharing tables. A remote provider (Clerk, WorkOS) cannot be locked by your transaction: keep a database-local projection of memberships whose lifecycle you coordinate with removals, and point the fences at it. See the provider pages for details.