Clerk
@rolebook/sharing-clerk: Clerk organizations as the source of users and organization membership.
@rolebook/sharing-clerk resolves sharing principals from Clerk organization memberships and users. It needs
@clerk/backend >=3.17.0 <4.
import { createClerkClient } from "@clerk/backend";
import { createClerkBackendDirectoryReader, createClerkIdentityAdapter } from "@rolebook/sharing-clerk";
const clerkClient = createClerkClient({ secretKey: process.env.CLERK_SECRET_KEY! });
export const identity = createClerkIdentityAdapter({
directory: createClerkBackendDirectoryReader(clerkClient),
}); createClerkBackendDirectoryReader() requests getOrganizationMembershipList({ organizationId, userId: [userId], limit: 2 }) and returns a membership only when the response holds exactly one record whose organization ID
and user ID both match; missing, mismatched, nullable-user, or duplicate results fail closed. For users it
projects only the primary email address ID and the addresses’ verification status.
Behaviour
- Resolving a principal makes one call, the exact membership lookup.
getUseris called only to match an email-bound invitation. SetrequireUser: truewhen your reader is not authoritative for memberships (a cache or a webhook-fed projection that can briefly keep a deleted user’s membership): each resolution then also fetches the user and is ineligible unless it still exists. - The Rolebook subject carries no Clerk role, email, or metadata. The role reaches only your mapper and its authorization fact.
- Email-bound invitations match only the user’s primary email address, and only when that address’s
verification status is
verified. A verified secondary address never matches. - Clerk Organizations have no teams; keep team tables of your own and use
@rolebook/teams/sql.
Remote identity and fences
Clerk is a remote system: a Clerk API check or a webhook-fed projection is not by itself an atomic fence for
a sharing mutation. For database-backed sharing, keep a database-local projection of Clerk memberships whose
lifecycle you coordinate with removals (for example from verified organizationMembership.deleted webhooks
through createClerkMemberRemovedHandler()), and point the eligibility fence, and with a role mapper the
workspace-role fact fence (CLERK_ORGANIZATION_MEMBER_AUTHORIZATION_FACT), at it. If you cannot establish
that, keep Clerk roles out of sharing-management policy. Email-bound acceptance needs a database-local
recipient fence over the membership, the primary address ID, the address, and its verification; without one,
issue subject-bound invitations, which compare Clerk’s immutable user ID.
Mapped roles used by a decision are snapshots at the current Clerk lookup: a decision concurrent with a Clerk role change can linearize at that lookup, and one invoked after the change completes performs a new lookup. This is not a cross-system transaction.
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. A Clerk lookup cannot be read at
the same point as a database page.
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 Clerk adapter as the source of a
projection it does not read. Keep the projection synchronized from Clerk 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-clerk". Signatures are checked against the built declarations.
Exports
createClerkIdentityAdapter
function createClerkIdentityAdapter(
options: ClerkIdentityAdapterOptions,
): TenantIdentityAdapter; Builds the TenantIdentityAdapter.
ClerkIdentityAdapterOptions
interface ClerkIdentityAdapterOptions {
readonly directory: ClerkDirectoryReader;
readonly subjectType?: string;
readonly workspaceResourceType?: string;
readonly mapWorkspaceAssignments?: (input: {
readonly tenantId: string;
readonly subject: ResourceRef;
readonly member: ClerkOrganizationMembershipRecord;
}) => readonly RoleAssignment[];
readonly normalizeEmail?: (email: string) => string;
readonly requireUser?: boolean;
} directory (required), subjectType, workspaceResourceType, mapWorkspaceAssignments, normalizeEmail, requireUser.
createClerkBackendDirectoryReader
function createClerkBackendDirectoryReader(
client: ClerkBackendDirectoryClient,
): ClerkDirectoryReader; A reader over a @clerk/backend v3 client that validates both identifiers on every returned record.
ClerkBackendDirectoryClient
type ClerkBackendDirectoryClient = Pick<ClerkClient, "organizations" | "users">; The client subset the reader uses.
ClerkDirectoryReader
interface ClerkDirectoryReader {
getOrganizationMembership(input: {
readonly organizationId: string;
readonly userId: string;
}): Promise<ClerkOrganizationMembershipRecord | undefined>;
getUser(input: { readonly userId: string }): Promise<ClerkUserRecord | undefined>;
} Exact membership and user lookups.
ClerkOrganizationMembershipRecord
interface ClerkOrganizationMembershipRecord {
readonly id: string;
readonly organizationId: string;
readonly userId: string;
readonly role: string;
} The authority-bearing fields of a Clerk organization membership.
ClerkUserRecord
interface ClerkUserRecord {
readonly id: string;
readonly primaryEmailAddressId: string | null;
readonly emailAddresses: readonly ClerkEmailAddressRecord[];
} The user fields the adapter reads: the primary address ID and the addresses.
ClerkEmailAddressRecord
interface ClerkEmailAddressRecord {
readonly id: string;
readonly emailAddress: string;
readonly verification: {
readonly status: string;
} | null;
} CLERK_ORGANIZATION_MEMBER_AUTHORIZATION_FACT
const CLERK_ORGANIZATION_MEMBER_AUTHORIZATION_FACT =
"rolebook.clerk.organization-member.v1"; The fact type for the workspace-role fact fence.
createClerkMemberRemovedHandler
function createClerkMemberRemovedHandler(input: {
readonly onMemberRemoved: (event: ClerkMemberRemovedEvent) => void | Promise<void>;
}): (event: ClerkMemberRemovedEvent) => Promise<void>; Validates and freezes a translated organizationMembership.deleted event for cleanup.
ClerkMemberRemovedEvent
interface ClerkMemberRemovedEvent {
readonly organizationId: string;
readonly userId: string;
}