RolebookDocs

WorkOS

@rolebook/sharing-workos: WorkOS User Management as the source of users and membership, plus Directory Sync groups.

@rolebook/sharing-workos resolves sharing principals from WorkOS User Management organization memberships and users, and lists a user’s Directory Sync groups. It needs @workos-inc/node >=11.0.0 <12.

import { WorkOS } from "@workos-inc/node";
import { createWorkOSDirectoryReader, createWorkOSIdentityAdapter } from "@rolebook/sharing-workos";

const workos = new WorkOS(process.env.WORKOS_API_KEY!);

export const identity = createWorkOSIdentityAdapter({
  directory: createWorkOSDirectoryReader(workos),
});

createWorkOSDirectoryReader() requests userManagement.listOrganizationMemberships({ organizationId, userId, statuses: ["active"], limit: 2 }) and returns a membership only when the response holds exactly one record whose organization and user IDs both match. It projects the membership’s primary role to its slug and keeps its status. Users are projected to { id, email, emailVerified }. WorkOS 404 responses become absence; other errors propagate.

Behaviour

  • Only an active membership is eligible. pending, inactive, any other status, and a role without a slug resolve as ineligible, checked again after the server-side filter.
  • Only the primary role is mapped; additional roles are ignored, so the mapper and the authorization fact see exactly one slug a fence can compare.
  • Each resolution makes two calls (membership and user): the principal is ineligible unless the user still exists with the requested ID. email and emailVerified are exposed on principal.attributes, never to conditions.
  • Email-bound invitations always fail closed. WorkOS is remote, so its email state cannot be locked in the sharing transaction. Issue subject-bound invitations, which compare WorkOS’s immutable user ID.
  • With a role mapper, principals carry WORKOS_ORGANIZATION_MEMBER_AUTHORIZATION_FACT. As with Clerk, fence it and the membership against a database-local projection you keep in step with WorkOS.

Directory Sync groups

listUserDirectoryGroups() returns a frozen, deduplicated list of at most MAX_DIRECTORY_GROUPS (100) { id, name } groups for one Directory Sync user within one organization:

import { WorkOS } from "@workos-inc/node";
import { createWorkOSDirectoryGroupReader, listUserDirectoryGroups } from "@rolebook/sharing-workos";

const workos = new WorkOS(process.env.WORKOS_API_KEY!);

const groups = await listUserDirectoryGroups({
  directory: createWorkOSDirectoryGroupReader(workos),
  organizationId: "org_123",
  userId: "directory_user_123", // a Directory Sync user ID, not a User Management user ID
});
  • The caller must bind the directory user to the principal it already resolved, from a mapping it stored (for example while processing Directory Sync events). Never accept a directory user ID from a client.
  • Every group must carry the explicit organization ID. A group from another organization or directory, a malformed record, conflicting names for one ID, or more than 100 groups rejects the whole call. A 404 on the first page reads as no groups.
  • Directory Sync is eventually consistent. Access derived from groups lags revocation until WorkOS processes the identity provider’s change. Do not rely on directory groups alone where revocation must be immediate.
  • Directory groups are not wired into @rolebook/teams. To use them as teams, mirror the groups that carry access into application tables from Directory Sync events and point createSqlTeamDirectory() and the team fences at them. Mind the bounds: teams allow 64 per subject, this listing 100.

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 WorkOS 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 WorkOS adapter as the source of a projection it does not read. Keep the projection synchronized from WorkOS 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, and appliesTo "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-workos". Signatures are checked against the built declarations.

Identity

createWorkOSIdentityAdapter

function createWorkOSIdentityAdapter(
  options: WorkOSIdentityAdapterOptions,
): TenantIdentityAdapter;

Builds the TenantIdentityAdapter. Always loads the user while resolving.

WorkOSIdentityAdapterOptions

interface WorkOSIdentityAdapterOptions {
  readonly directory: WorkOSDirectoryReader;
  readonly subjectType?: string;
  readonly workspaceResourceType?: string;
  readonly mapWorkspaceAssignments?: (input: {
    readonly tenantId: string;
    readonly subject: ResourceRef;
    readonly member: WorkspaceMemberRecord;
  }) => readonly RoleAssignment[];
}

directory (required), subjectType, workspaceResourceType, mapWorkspaceAssignments.

createWorkOSDirectoryReader

function createWorkOSDirectoryReader(client: WorkOSDirectoryClient): WorkOSDirectoryReader;

A reader over the WorkOS SDK’s userManagement.

WorkOSDirectoryClient

type WorkOSDirectoryClient = Pick<WorkOS, "userManagement">;

WorkOSDirectoryReader

interface WorkOSDirectoryReader {
  getOrganizationMembership(input: {
    readonly organizationId: string;
    readonly userId: string;
  }): Promise<WorkOSOrganizationMembershipRecord | undefined>;
  getUser(input: { readonly userId: string }): Promise<WorkOSUserRecord | undefined>;
}

Exact membership and user lookups.

WorkOSOrganizationMembershipRecord

interface WorkOSOrganizationMembershipRecord {
  readonly id: string;
  readonly organizationId: string;
  readonly userId: string;
  readonly role: string;
  readonly status: WorkOSOrganizationMembershipStatus;
}

A membership projected to its primary role slug and status.

WorkOSOrganizationMembershipStatus

type WorkOSOrganizationMembershipStatus = "active" | "inactive" | "pending";

Only active is eligible.

WorkOSUserRecord

interface WorkOSUserRecord {
  readonly id: string;
  readonly email: string;
  readonly emailVerified: boolean;
}

WORKOS_ORGANIZATION_MEMBER_AUTHORIZATION_FACT

const WORKOS_ORGANIZATION_MEMBER_AUTHORIZATION_FACT =
  "rolebook.workos.organization-member.v1";

The fact type for the workspace-role fact fence.

createWorkOSMemberRemovedHandler

function createWorkOSMemberRemovedHandler(input: {
  readonly onMemberRemoved: (event: WorkOSMemberRemovedEvent) => void | Promise<void>;
}): (event: WorkOSMemberRemovedEvent) => Promise<void>;

Validates and freezes a translated organization_membership.deleted event for cleanup.

WorkOSMemberRemovedEvent

interface WorkOSMemberRemovedEvent {
  readonly organizationId: string;
  readonly userId: string;
}

Directory Sync

listUserDirectoryGroups

function listUserDirectoryGroups(input: {
  readonly directory: WorkOSDirectoryGroupReader;
  readonly organizationId: string;
  readonly userId: string;
}): Promise<readonly DirectoryGroup[]>;

One Directory Sync user’s groups within one organization, validated and bounded.

createWorkOSDirectoryGroupReader

function createWorkOSDirectoryGroupReader(
  client: WorkOSDirectorySyncClient,
): WorkOSDirectoryGroupReader;

A reader over the SDK’s directorySync.listGroups, following cursors explicitly.

WorkOSDirectorySyncClient

type WorkOSDirectorySyncClient = Pick<WorkOS, "directorySync">;

WorkOSDirectoryGroupReader

interface WorkOSDirectoryGroupReader {
  listDirectoryGroups(input: {
    readonly organizationId: string;
    readonly userId: string;
  }): Promise<readonly WorkOSDirectoryGroupRecord[]>;
}

WorkOSDirectoryGroupRecord

interface WorkOSDirectoryGroupRecord {
  readonly id: string;
  readonly directoryId: string;
  readonly organizationId: string | null;
  readonly name: string;
}

DirectoryGroup

interface DirectoryGroup {
  readonly id: string;
  readonly name: string;
}

MAX_DIRECTORY_GROUPS

const MAX_DIRECTORY_GROUPS = 100;

The most groups one listing returns.

MAX_DIRECTORY_GROUP_NAME_LENGTH

const MAX_DIRECTORY_GROUP_NAME_LENGTH = 256;

The longest group name accepted.

WORKOS_MAX_PAGE_SIZE

const WORKOS_MAX_PAGE_SIZE = 100;

WorkOS’s page maximum, used as the page size.