RolebookDocs

PostgreSQL adapter

@rolebook/sharing-postgres: an ORM-neutral PostgreSQL storage adapter for sharing.

@rolebook/sharing-postgres stores sharing state in your PostgreSQL database, next to the resources it protects. It does not import a driver or an ORM: it takes a small parameterized executor that you build over pg, Postgres.js, Kysely, Drizzle, or your own database boundary.

  • One adapter per concrete resource table. Sharing rows are separate tables (owner, member, invitation, audit, idempotency, lifecycle, revision floor) with composite foreign keys to the application row’s (tenant, id) key, never a polymorphic (resource_type, resource_id) pair.
  • Sharing mutations run at SERIALIZABLE isolation, locks the application row and the required workspace member rows (FOR SHARE), compares exact resource versions and sharing revisions, and writes the idempotency record and audit event before committing. Serialization failures and deadlocks retry.
  • Migrations are generated per resource, idempotent, and validate the existing schema before changing it.
  • PostgreSQL 13 or later is required (gen_random_uuid()).
  • Named authorized queries serve registered, filtered and sorted queries over a resource table on the checked createPgExecutor(pool) executor.

1. An executor

The executor runs parameterized SQL and opens SERIALIZABLE transactions. The custom executor below is a Sharing adapter example. For protected application updates, use the checked createPgExecutor(pool) factory for both the resource adapter and policy store; a structural custom executor is not accepted by that wrapper. With node-postgres:

executor.ts
import pg from "pg";
import {
  asSerializablePostgresTransaction,
  type ParameterizedSqlExecutor,
  type SqlResult,
  type SqlRow,
  type SqlValue,
} from "@rolebook/sharing-postgres";

const pool = new pg.Pool({ connectionString: process.env.DATABASE_URL });

async function run<TRow extends SqlRow>(
  client: pg.Pool | pg.PoolClient,
  sql: string,
  values: readonly SqlValue[],
): Promise<SqlResult<TRow>> {
  const result = await client.query(sql, [...values]);
  return { rows: result.rows as TRow[], rowCount: result.rowCount ?? 0 };
}

export const executor: ParameterizedSqlExecutor = {
  query: (sql, values = []) => run(pool, sql, values),
  async transaction(options, operation) {
    if (options.isolationLevel !== "serializable") throw new Error("SERIALIZABLE only");
    const client = await pool.connect();
    try {
      await client.query("BEGIN TRANSACTION ISOLATION LEVEL SERIALIZABLE");
      const transaction = asSerializablePostgresTransaction({
        query: (sql, values = []) => run(client, sql, values),
        transaction: async () => {
          throw new Error("Nested transactions are not supported");
        },
      });
      const result = await operation(transaction);
      await client.query("COMMIT");
      return result;
    } catch (error) {
      await client.query("ROLLBACK").catch(() => undefined);
      throw error;
    } finally {
      client.release();
    }
  },
};

Two requirements: a call with no values must be sent as a simple query, because migration steps are multi-statement SQL (node-postgres does this; with Postgres.js use unsafe()), and the transaction must really be SERIALIZABLE. asSerializablePostgresTransaction() is an explicit assertion that it is: the adapter cannot inspect a driver’s isolation level at runtime.

2. A resource descriptor

The descriptor names the application table and how to build a trusted snapshot from its row:

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

export const projectTable = {
  resourceType: "project",
  table: ["app", "project"],
  tenantColumn: "workspace_id",
  idColumn: "id",
  tenantSqlType: "uuid",
  resourceSqlType: "uuid",
  resourceVersionColumn: "version",
  // Globally unique per concrete application table.
  sharingTablePrefix: "project",
  resourceColumns: ["visibility", "archived_at"],
  resourceFromRow: (row) =>
    trustedResource(
      { type: "project", id: String(row.id) },
      [{ type: "workspace", id: String(row.workspace_id) }],
      { visibility: String(row.visibility), archived: row.archived_at !== null },
    ),
} as const satisfies PostgresResourceDescriptor;
FieldMeaning
resourceTypeThe sharing resource type this table holds.
tableThe application table, "name" or ["schema", "name"].
tenantColumn, idColumnThe columns of its (tenant, id) key.
tenantSqlType, resourceSqlType"text" (default) or "uuid"; must match the real columns exactly.
resourceVersionColumnA version that changes whenever a field authorization reads changes.
sharingRevisionColumnOptional name of the generated sharing revision column (default rolebook_sharing_revision).
resourceFromRow(row)Builds the TrustedResource from the locked row, ancestry included.
resourceVersion(row)Optional: derive the version string from the row.
resourceColumnsOptional: the extra columns your callbacks read, instead of SELECT *. Unquoted, case-sensitive names.
sharingTablePrefixRequired, globally unique prefix for this table’s sharing tables.

With resourceColumns, application-table reads select only the key, version, and revision columns plus the listed ones; an unlisted column arrives as undefined.

UUID IDs

A uuid column accepts PostgreSQL’s input forms (case variants, braces, missing hyphens) on the adapter’s direct methods and returns the canonical lowercase hyphenated form. The sharing module compares resource IDs exactly as given, so always pass it the canonical form.

3. Fences and the adapter

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

const lockEligibleSubjects = createPostgresMembershipEligibilityFence({
  table: ["auth", "member"], // your real organization-member table, for example Better Auth's
  tenantColumn: "organization_id",
  subjectIdColumn: "user_id",
});

const lockInvitationRecipient = createPostgresEmailInvitationRecipientFence({
  membershipTable: ["auth", "member"],
  membershipTenantColumn: "organization_id",
  membershipSubjectIdColumn: "user_id",
  userTable: ["auth", "user"],
  userIdColumn: "id",
  userEmailColumn: "email",
  userEmailVerifiedColumn: "email_verified",
});

export const projectAdapter = createPostgresSharingAdapter({
  executor,
  resource: projectTable,
  lockEligibleSubjects,
  lockInvitationRecipient,
});

Then pass projectAdapter as the adapter of the project type in defineSharing(). See fences for what each fence locks, mapped workspace roles, teams, and the policy fence.

OptionMeaning
executorThe executor above.
resourceThe resource descriptor.
lockEligibleSubjectsRequired. Locks and checks tenant eligibility in the mutation transaction.
lockInvitationRecipientRequired for email invitations; without it they fail closed.
revalidateAuthorizationFactsRequired when mapped workspace roles or teams authorize mutations.
groupSubjectTypesGroup subject types that may never own (default ["team"]).
fencePolicyThe policy fence, for versioned sharing.
clockInject a clock for deterministic tests (otherwise the database clock decides expiry).
serializableRetryattempts (default 3, including the first), backoffMs, wait.

4. Migrations and resources

Generate the migration steps for the descriptor and apply them on every deploy:

import { applyPostgresMigrations, createResourceSharingMigrations } from "@rolebook/sharing-postgres";

await applyPostgresMigrations(executor, createResourceSharingMigrations(projectTable));

When the application creates a project, create its owner in the same transaction with initializeResourceInTransaction(). See migrations and lifecycle.

Clocks

Without a clock, every expiry comparison uses the database’s clock_timestamp() at the statement that compares, so time spent waiting for locks cannot extend an invitation or a membership. In deterministic tests pass the same clock to the adapter and to createSharing().

Protected application updates

For an application-owned resource/action SQL update, the protected update wrapper authorizes, seals authority and commits the callback result, durable receipt and outbox event together. Unlike ordinary Sharing mutations, it never automatically retries the transaction or callback. This embedded PostgreSQL API requires complete local authority and preserves incarnation, ancestry, owner and sharing state while advancing the declared resource version. It is not a field-mediated or HTTP transaction API.