RolebookDocs

Add resource sharing

An end-to-end guide to sharing one resource type with owners, members, and invitations.

This guide makes one resource type, project, shareable on PostgreSQL with Better Auth as the identity provider. Each step links to the reference for the details. For SQLite, swap step 2 and 3 for the SQLite adapter; for Clerk or WorkOS, swap step 4.

Not on npm yet

These packages are not on npm yet: rolebook, @rolebook/sharing, @rolebook/sharing-postgres and @rolebook/sharing-better-auth. The npm package named rolebook is an unrelated project, so do not install it.

1. Roles for the resource

Add an owner role, member roles, and three management actions at the project’s own scope. See the policy shape.

policy.ts
import { definePolicy } from "rolebook";

export const policy = definePolicy({
  resources: {
    workspace: { actions: ["read"] },
    project: {
      parent: "workspace",
      actions: ["read", "update", "manage_members", "manage_invitations", "transfer_ownership"],
    },
  },
  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" },
      ],
    },
    project_viewer: { scope: "project", rules: [{ effect: "allow", permission: "project:read" }] },
  },
});

2. Tables

Describe the application table and run the generated migrations on every deploy. See PostgreSQL migrations.

projects.ts
import { trustedResource } from "rolebook";
import {
  applyPostgresMigrations,
  createResourceSharingMigrations,
  type ParameterizedSqlExecutor,
  type PostgresResourceDescriptor,
} from "@rolebook/sharing-postgres";

// createPgExecutor(pool): see "An executor" in the PostgreSQL guide. Listing needs this checked executor.
declare const executor: ParameterizedSqlExecutor;

export const projectTable = {
  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) }]),
} as const satisfies PostgresResourceDescriptor;

await applyPostgresMigrations(executor, createResourceSharingMigrations(projectTable));

3. The storage adapter

Fence eligibility against Better Auth’s member table, and email recipients against its member and user tables. See fences.

adapter.ts
import {
  createPostgresEmailInvitationRecipientFence,
  createPostgresMembershipEligibilityFence,
  createPostgresSharingAdapter,
} from "@rolebook/sharing-postgres";

export const projectAdapter = createPostgresSharingAdapter({
  executor,
  resource: projectTable,
  lockEligibleSubjects: createPostgresMembershipEligibilityFence({
    table: ["auth", "member"],
    tenantColumn: "organizationId",
    subjectIdColumn: "userId",
  }),
  lockInvitationRecipient: createPostgresEmailInvitationRecipientFence({
    membershipTable: ["auth", "member"],
    membershipTenantColumn: "organizationId",
    membershipSubjectIdColumn: "userId",
    userTable: ["auth", "user"],
    userIdColumn: "id",
    userEmailColumn: "email",
    userEmailVerifiedColumn: "emailVerified",
  }),
});

4. Identity

See Better Auth for a directory reader over its tables.

identity.ts
import { createBetterAuthIdentityAdapter, type BetterAuthDirectoryReader } from "@rolebook/sharing-better-auth";

declare const directory: BetterAuthDirectoryReader;

export const identity = createBetterAuthIdentityAdapter({ directory });

5. The sharing instance

Generate the two keys once with generateInvitationTokenKey() and generateListingCursorKey() and store them as secrets. See secret keys.

sharing.ts
import { createHmacInvitationTokens, createSharing, defineSharing } from "@rolebook/sharing";

export const sharing = createSharing({
  definition: defineSharing({
    policy,
    resources: {
      project: {
        memberRoles: { editor: "project_editor", viewer: "project_viewer" },
        ownershipRole: "project_owner",
        actions: { read: "project:read", update: "project:update" },
        management: {
          members: "project:manage_members",
          invitations: "project:manage_invitations",
          ownership: "project:transfer_ownership",
        },
        adapter: projectAdapter,
      },
    },
  }),
  identity,
  invitationTokens: createHmacInvitationTokens(process.env.SHARING_INVITATION_KEY!),
  listingCursorKey: process.env.SHARING_LISTING_CURSOR_KEY!,
});

6. Create projects with an owner

Insert the application row and initialize its owner in the same SERIALIZABLE transaction. See lifecycle.

create-project.ts
import { withSerializableTransaction } from "@rolebook/sharing-postgres";

export async function createProject(workspaceId: string, userId: string, projectId: string, title: string) {
  const user = { type: "user", id: userId };
  return withSerializableTransaction(executor, async (transaction) => {
    await transaction.query(
      "INSERT INTO app.project (workspace_id, id, title, version) VALUES ($1, $2, $3, 1)",
      [workspaceId, projectId, title],
    );
    return projectAdapter.initializeResourceInTransaction(transaction, {
      tenantId: workspaceId,
      resourceId: projectId,
      owner: user,
      actor: user,
      occurredAt: new Date(),
    });
  });
}

7. Share and check

use.ts
const tenant = sharing.forTenant({ tenantId: "ws_456", actor: { type: "user", id: "user_123" } });

await tenant.execute({
  kind: "grantRole",
  resource: { type: "project", id: "project_1" },
  subject: { type: "user", id: "user_789" },
  role: "viewer",
  idempotencyKey: "share-project_1-user_789",
});

const viewer = sharing.forTenant({ tenantId: "ws_456", actor: { type: "user", id: "user_789" } });
const canRead = await viewer.authorize({ resource: { type: "project", id: "project_1" }, action: "read" });

Commands return result codes rather than throwing; see commands. Expose the same operations to a browser with the HTTP API.

8. List what a user can open

listAccessible() pages through the projects a user may perform one action on, and listAccess() through the projects they may do anything on, with every action’s decision. Each page is read at one coherent point, which asks more of the configuration than authorize() does:

  • Storage. The adapter from step 3 qualifies when executor comes from createPgExecutor(pool) and the workspace_id and id columns are text.
  • Eligibility. createPostgresMembershipEligibilityFence supplies the evidence a page needs. A fence you write yourself needs a matching readEligibleSubjects.
  • Identity. The identity adapter from step 4 must supply evidence that its answer belongs to the page. Either it implements resolvePagePrincipal, which requires a source with a non-repeating revision, or you keep the identity facts in a projection table in the same database and name it in the adapter’s pageIdentity option. Identity for listing shows the projection setup. The Better Auth adapter from step 4 does neither, and neither do the Clerk and WorkOS adapters: wired exactly as shown, both listings reject with identity_evidence_missing. To list, replace it with an identity adapter that answers exclusively from a projection table complete for every fact it returns (kept in sync from the provider), and name that identity object and projection in pageIdentity. pageIdentity is your attestation, and it is valid only when that identity resolves exclusively from the complete projection. Rolebook checks that the object is the same, not where its data comes from, so naming the provider-backed adapter beside a copy would make listings run without being sound.
list.ts
import { AccessListingUnavailableError } from "@rolebook/sharing";

try {
  const page = await viewer.listAccessible({ type: "project", action: "read", limit: 20 });
  const everything = await viewer.listAccess({ type: "project", limit: 20 });
  console.log(page.resources.length, everything.resources.length, page.nextCursor);
} catch (error) {
  if (!(error instanceof AccessListingUnavailableError)) throw error;
  // No page was returned. `reason` says why: "identity_evidence_missing" means the step above is not done.
  console.warn(`listing unavailable: ${error.reason}`);
}

A listing that cannot read a consistent page rejects with AccessListingUnavailableError; it never returns a partial list, and the error does not mean the user has no access. Continue with nextCursor until exhausted: a page can be empty and not exhausted. See listing.

9. Operate it

  • Run the adapter contract in your test suite.
  • Schedule one pruning job.
  • Size the connection pool for listing: each page attempt holds one connection under a 2-second deadline, a call makes up to three attempts, and at most 32 attempts are open at once per adapter; see bounds. Alert on ACCESS_LISTING_UNAVAILABLE with the reasons capability_missing, identity_evidence_missing, or policy_evidence_missing, which indicate configuration, not load.
  • Drain the audit table if you deliver audit events elsewhere.
  • Roll out per resource type, comparing with your existing checks first: see migrating to sharing.