Teams
@rolebook/teams: flat, bounded team principals for sharing, with directories, an identity wrapper, and fences.
Share a resource with a team and every current member inherits that access; remove someone from the team
and their team-derived access ends on their next request, while a direct grant to them still applies.
@rolebook/teams supplies the pieces: team directories for Better Auth’s organization teams and for
application-owned tables, the withTeams() identity wrapper, PostgreSQL fences, and an optional
nested-lineage directory on /sql and
/sqlite. Flat withTeams() remains the default.
const owner = { type: "user", id: "owner_1" };
const alice = { type: "user", id: "alice" };
// Share "Brand Assets" with the Design team as editors.
await sharing.forTenant({ tenantId, actor: owner }).execute({
kind: "grantRole",
resource: { type: "project", id: "brand_assets" },
subject: { type: "team", id: "design" },
role: "editor",
idempotencyKey: "share-brand-assets",
});
const decision = await sharing
.forTenant({ tenantId, actor: alice })
.authorize({ resource: { type: "project", id: "brand_assets" }, action: "update" });
decision.decision?.matched?.via; // { type: "team", id: "design" }: "editor through Design team" Rules
- Flat. Teams contain individuals, never other teams. Rolebook compares principals with assignment subjects and never expands them. Nested lineage is a separate wrapper for one team type.
- Bounded. At most
MAX_TEAMS_PER_SUBJECT(64) teams per subject per tenant, Rolebook’sMAX_PRINCIPALS. More, or a malformed team record, throwsTeamDirectoryError: dropping a team silently could drop a deny. - Tenant-scoped. Every lookup takes an explicit tenant and subject; nothing comes from an active organization, active team, or session.
- Exact IDs. A team matches only by the ID
teamsOf()reports (for the SQL directories, the database’s canonical text of the row’s ID). Another spelling auuid,integer, or case-insensitive column would coerce to the same team is refused as a target. - Never actors, never owners. A team resolves only as a grant or invitation target.
TeamRefis branded so ownership paths reject it at compile time, the sharing module rejects it at runtime (GROUP_CANNOT_OWN), and the adapters reject it again (group_owner). - No self-promotion. An actor cannot grant, change, or invite a team it belongs to. It may un-share from its own team unless the team’s role carries a deny. The owner may always remove such a deny.
- Denies on teams are the owner’s. Only the owner may grant, change, or invite a team to a role that carries a deny. Everything else follows the delegation ceiling.
- Fenced. Every team carries a
TEAM_MEMBERSHIP_AUTHORIZATION_FACT, sent when that team holds a membership on the mutated resource or receives the invitation being accepted, and every principal carries oneTEAM_SET_AUTHORIZATION_FACTwith its complete team set, even an empty one. The fence rechecks membership under lock and reads the team set again in the write transaction; a changed set restarts the mutation, so a team joined after preflight, and any deny it carries, is accounted for.
Wiring it up with Better Auth
Enable teams in Better Auth’s organization plugin (organization({ teams: { enabled: true } })). The
directory reads the plugin’s team and teamMember tables through the same executor you give the
PostgreSQL adapter:
import { createSharing, defineSharing, type InvitationTokenProtector } from "@rolebook/sharing";
import { createBetterAuthIdentityAdapter, type BetterAuthDirectoryReader } from "@rolebook/sharing-better-auth";
import {
createPostgresMembershipEligibilityFence,
createPostgresSharingAdapter,
type ParameterizedSqlExecutor,
type PostgresResourceDescriptor,
} from "@rolebook/sharing-postgres";
import { withTeams } from "@rolebook/teams";
import { createBetterAuthTeamDirectory, createBetterAuthTeamFences } from "@rolebook/teams/better-auth";
import type { RolebookPolicy } from "rolebook";
declare const executor: ParameterizedSqlExecutor;
declare const projectTable: PostgresResourceDescriptor;
declare const directory: BetterAuthDirectoryReader;
declare const invitationTokens: InvitationTokenProtector;
declare const policy: RolebookPolicy;
const teams = createBetterAuthTeamDirectory({ executor, schema: "auth" });
const fences = createBetterAuthTeamFences({
schema: "auth",
eligibility: createPostgresMembershipEligibilityFence({
table: ["auth", "member"],
tenantColumn: "organizationId",
subjectIdColumn: "userId",
}),
// authorizationFacts: createPostgresWorkspaceRoleAuthorizationFactFence({ ... }) when roles are mapped
});
const projectAdapter = createPostgresSharingAdapter({ executor, resource: projectTable, ...fences });
const sharing = createSharing({
definition: defineSharing({
policy,
resources: {
project: {
memberRoles: { editor: "project_editor" },
ownershipRole: "project_owner",
actions: { update: "project:update" },
management: {
members: "project:manage_members",
invitations: "project:manage_invitations",
ownership: "project:transfer_ownership",
},
adapter: projectAdapter,
},
},
}),
identity: withTeams(createBetterAuthIdentityAdapter({ directory }), { teams }),
invitationTokens,
}); Better Auth’s team table is keyed by its primary key alone, so a team ID names one team across every
organization; betterAuthTeamTables() declares teamIdsGloballyUnique: true. Defaults match Better
Auth’s names: team(id, organizationId) and teamMember(teamId, userId). Pass teamTable,
teamMemberTable, and fields if you renamed them, and add an index on teamMember("userId") if your
schema lacks one.
Application-owned tables
Clerk Organizations have no teams, and other providers may not either. Keep your own tables and use the
SQL directory from @rolebook/teams/sql:
CREATE TABLE team (
tenant_id text NOT NULL,
id text PRIMARY KEY,
UNIQUE (tenant_id, id)
);
CREATE TABLE team_member (
tenant_id text NOT NULL,
team_id text NOT NULL,
user_id text NOT NULL,
PRIMARY KEY (team_id, user_id),
FOREIGN KEY (tenant_id, team_id) REFERENCES team (tenant_id, id) ON DELETE CASCADE
);
CREATE INDEX team_member_user_idx ON team_member (tenant_id, user_id); import type { ParameterizedSqlExecutor, PostgresEligibilityFence } from "@rolebook/sharing-postgres";
import { createPostgresTeamFences, createSqlTeamDirectory, type SqlTeamTables } from "@rolebook/teams/sql";
declare const executor: ParameterizedSqlExecutor;
declare const lockEligibleSubjects: PostgresEligibilityFence;
const tables: SqlTeamTables = {
team: { table: ["app", "team"], idColumn: "id", tenantColumn: "tenant_id" },
member: {
table: ["app", "team_member"],
teamIdColumn: "team_id",
subjectIdColumn: "user_id",
tenantColumn: "tenant_id",
},
};
const teams = createSqlTeamDirectory({ executor, tables });
const fences = createPostgresTeamFences({ tables, eligibility: lockEligibleSubjects }); member.tenantColumn ties each membership row to its team’s tenant. Leave it out only when the team ID
is unique across every tenant, and say so with teamIdsGloballyUnique: true; otherwise both builders
throw a TypeError. Individuals default to subject type "user"; a directory asked about any other type
throws UNSUPPORTED_SUBJECT_TYPE rather than answering no teams.
Fences are required
Once identity is wrapped with withTeams(), the storage adapter must have team fences:
createPostgresTeamFences() (or createBetterAuthTeamFences()) on PostgreSQL, or equivalent fences you
write for SQLite and the memory adapter. Every mutation
by a team-wrapped principal carries its team-set fact, so without a fact fence every such mutation fails
closed with NOT_TENANT_MEMBER.
The fences lock team rows FOR SHARE when a team is granted, recheck each team-membership fact by
joining the membership to its team in the tenant, refuse membership facts without their subject’s
team-set fact, re-read the team set and return "conflict" when it changed, pass other facts to your
existing fact fence (rejecting them without one, with a one-time warn), and refuse any team offered as
an owner. Cost: one locked membership row per team that holds a membership on the mutated resource, plus
one read of the actor’s team set.
Nested lineage
withTeamLineage() is a separate wrapper. It replaces the flat team list for one team type with the
effective groups of a nested graph: a direct member of Design also receives Product when Design is
linked under Product. Do not wrap that same team type with withTeams(). Direct membership stays in
the membership table. membersOf() still pages those direct members and does not walk parents.
On an enrolled PostgreSQL or SQLite tenant, the local identity projection carries eligibility,
assignments, base facts, and groups of other types. Current membership of the configured team type
comes from the transaction-local team directory and the graph in that snapshot, so the projection
does not repeat the direct-team list. A same-team group carried from an earlier resolution, and a
group-tagged fact for a team absent from this snapshot, does not add a member. A group the
transaction explicitly retains stays. withTeamLineage() is standalone composition: it replaces
that team type on the principal it returns and keeps the base principal’s other groups. The SQL
adapter qualifies the decision in the transaction.
subjectType defaults to "user" and has to differ from teamType (default "team").
readDirectTeams returns the configured individual type’s direct teams. It returns [] for the
configured team type. An unsupported third type throws HierarchyUnavailableError
lineage_invalid.
identityStability is declared at the directory and again on the adapter’s groupGraph option, as
the same value. registry_incarnation stores an incarnation column and requires incarnationColumn.
ids_never_reused means this deployment does not reuse team ids and rejects an incarnation column.
teamIdsGloballyUnique does not select either value.
PostgreSQL reads take lock: "share" inside a write (the membership table share lock) and
lock: "none" on a read-only snapshot. SQLite reads run in the caller’s BEGIN IMMEDIATE
transaction and take no lock argument. Graph commands use that same choice of transaction.
Build them with
createPostgresGroupGraphControl()
and createSqliteGroupGraphControl().
The lower PostgreSQL facade still accepts serializableRetry, and the lower SQLite facade still
accepts busyRetry, when the caller already holds that facade’s options.
Strict SQLite listing pages still use the worker executor
createBunSqliteQueryExecutor(); a graph command does not make another executor eligible for them.
readDirectTeams returns at most 64 distinct teams. One more throws HierarchyUnavailableError
principal_cap. A malformed registry team id is registry_unavailable. A database driver error
propagates unchanged. withTeamLineage throws principal_cap when merged groups exceed 64, and
budget_exhausted when the base principal carries more than 256 raw assignments. Flat team APIs
still throw TeamDirectoryError. A graph command
returns a Core denial as status: "denied" and leaves decision intact. A structural problem, such
as a self-link, is status: "refused". A resolution that cannot be completed throws
HierarchyUnavailableError with a reason such as graph_quarantined, lineage_invalid, or
principal_cap. principal_cap refuses the resolution and does not quarantine the graph. The command facade has no
confirm method and no caller-selected authorizer.
createPostgresGroupGraphControl()
binds the compiled commands, the bootstrap provider, the policy store, the versioned sharing
instance that reads that store, and the local identity projection. Optional groupGraph.integrity
is that returned provider. When it is set, a
read or mutation that finds structural corruption confirms the finding after the detecting
transaction settles, and a failed confirmation makes no quarantine claim.
import type { PostgresEligibilityFence, PostgresResourceDescriptor } from "@rolebook/sharing-postgres";
import { createPostgresSharingAdapter, type ParameterizedSqlExecutor } from "@rolebook/sharing-postgres";
import type { SqliteEligibilityFence, SqliteResourceDescriptor } from "@rolebook/sharing-sqlite";
import { createSqliteSharingAdapter, type ParameterizedSqliteExecutor } from "@rolebook/sharing-sqlite";
import { createPostgresTeamLineageDirectory, type SqlTeamTables } from "@rolebook/teams/sql";
import { createSqliteTeamLineageDirectory, type SqliteTeamTables } from "@rolebook/teams/sqlite";
declare const pg: ParameterizedSqlExecutor;
declare const sqlite: ParameterizedSqliteExecutor;
declare const lockEligibleSubjects: PostgresEligibilityFence;
declare const sqliteEligibility: SqliteEligibilityFence;
declare const projectTable: PostgresResourceDescriptor;
declare const sqliteProject: SqliteResourceDescriptor;
const postgresTables: SqlTeamTables = {
team: { table: ["app", "team"], idColumn: "id", tenantColumn: "tenant_id" },
member: {
table: ["app", "team_member"],
teamIdColumn: "team_id",
subjectIdColumn: "user_id",
tenantColumn: "tenant_id",
},
subjectType: "user",
teamType: "team",
};
const postgresDirectory = createPostgresTeamLineageDirectory(postgresTables, {
identityStability: "registry_incarnation",
incarnationColumn: "incarnation",
});
const postgresAdapter = createPostgresSharingAdapter({
executor: pg,
resource: projectTable,
lockEligibleSubjects,
groupGraph: {
teamType: "team",
identityStability: "registry_incarnation",
directory: postgresDirectory,
},
});
const sqliteTables: SqliteTeamTables = {
teamTable: "team",
memberTable: "team_member",
subjectIdColumn: "user_id",
subjectType: "service_account",
teamType: "team",
identityStability: "ids_never_reused",
};
const sqliteDirectory = createSqliteTeamLineageDirectory(sqliteTables);
const sqliteAdapter = createSqliteSharingAdapter({
executor: sqlite,
resource: sqliteProject,
lockEligibleSubjects: sqliteEligibility,
groupGraph: {
teamType: "team",
identityStability: "ids_never_reused",
directory: sqliteDirectory,
},
});
const direct = await postgresDirectory.readDirectTeams({
executor: pg,
tenantId: "ws_456",
subject: { type: "user", id: "alice" },
lock: "none",
});
const teamSubject = await sqliteDirectory.readDirectTeams({
executor: sqlite,
tenantId: "ws_456",
subject: { type: "team", id: "design" },
});
direct.length;
teamSubject.length;
postgresAdapter;
sqliteAdapter; import { HierarchyUnavailableError, type PolicyStore, type TenantIdentityAdapter } from "@rolebook/sharing";
import {
createPostgresGroupGraphControl,
createPostgresLocalIdentityProjection,
type ParameterizedSqlExecutor,
} from "@rolebook/sharing-postgres";
import { resolveTeamLineage, withTeamLineage, type TeamLineageSource } from "@rolebook/teams";
import type { RolebookPolicy } from "rolebook";
declare const identity: TenantIdentityAdapter;
declare const source: TeamLineageSource;
declare const executor: ParameterizedSqlExecutor;
declare const policy: RolebookPolicy;
declare const policyStore: PolicyStore;
declare const sharing: object;
declare const projection: ReturnType<typeof createPostgresLocalIdentityProjection>;
const nested = withTeamLineage(identity, source);
declare const lineageInput: Parameters<typeof resolveTeamLineage>[0];
const resolution = await resolveTeamLineage(lineageInput);
if (resolution.ok) {
resolution.direct;
resolution.groups;
} else {
resolution.cause;
}
const graph = createPostgresGroupGraphControl({
executor,
profile: { schema: "public", prefix: "rolebook_control" },
teamType: "team",
identityStability: "registry_incarnation",
actor: { type: "user", id: "ada" },
policy,
bootstrapType: "tenant_admin",
actions: {
activate: "tenant_admin:graph_activate",
link: "tenant_admin:graph_link",
unlink: "tenant_admin:graph_unlink",
repairUnlink: "tenant_admin:graph_repair_unlink",
heightRepair: "tenant_admin:graph_height_repair",
release: "tenant_admin:graph_release",
},
controlBindingId: "control-binding",
normalBindingId: "graph-binding",
policyStore,
sharing,
identity: projection,
bootstrap: {
policyStore: { schema: "public", tablePrefix: "rolebook" },
descriptor: {
resourceType: "tenant_admin",
schema: "public",
table: "tenant_admin",
tenantColumn: "workspace_id",
idColumn: "id",
versionColumn: "version",
incarnationColumn: "incarnation",
},
},
registry() {
return {
async readEndpoint(group) {
return group.id === "missing"
? { present: false as const }
: { present: true as const, incarnation: "1" };
},
};
},
});
try {
const outcome = await graph.facade.link(
"ws_456",
{ type: "team", id: "design" },
{ type: "team", id: "product" },
);
if (outcome.status === "denied") outcome.decision.allowed;
if (outcome.status === "refused") outcome.refusal;
if (outcome.status === "applied") outcome.effect;
} catch (error) {
if (error instanceof HierarchyUnavailableError) error.reason;
}
nested;
graph.tables.names.groupGraph; hierarchyControlTables() names the PostgreSQL
control tables for a schema and prefix.
hierarchyControlTables() names the SQLite tables
in main. Resource migrations install that same profile. SQLite construction is
createSqliteGroupGraphControl(), with a
table prefix instead of a schema. Activation stores the control configuration as sha256: plus 64
hexadecimal characters. Reordering graph-independent provider paths does not change that digest. A
different action map is profile_mismatch.
Directory failures throw
TeamDirectoryError (more than 64 teams, a malformed record, an unsupported subject type) propagates out
of the operations that resolve the principal through this adapter, such as authorize() and execute(),
as a rejected promise, even for resources the subject owns. It is an application data fault: catch it at
your framework boundary, report it, and answer with a generic error. Listings behave differently with this
adapter; see the next section.
Listing with teams
withTeams() returns an identity adapter with resolvePrincipal and matchesInvitationRecipient. That is
all authorize() and commands need. listAccessible() and listAccess()
also need evidence that the principal, teams included, belongs to the same point as the page, and the
wrapper does not supply it. The identity adapter you pass to createSharing() supplies it in one of the
supported ways:
- A local identity projection in the same database whose row carries the subject’s teams in
groups, named in the PostgreSQL or SQLite adapter’spageIdentityoption. The identity adapter must then resolve principals from exactly that projection, so it cannot be thewithTeams()wrapper over a provider, and the projection must be kept synchronized with your team store. - Bracketed evidence: an identity adapter of your own that implements
resolvePagePrincipalover a source with a revision that never repeats and changes on every relevant change. - A synchronous capture, with the in-memory adapter: an identity adapter of your own that implements
capturePagePrincipaland returns the complete principal, with its teams ingroupsand every expiry dependency, from in-process state in the same synchronous turn as the adapter’s snapshot. It cannot await a directory or call a provider.
Identity evidence is not enough on its own. createPostgresTeamFences() and createBetterAuthTeamFences()
return an eligibility fence with no readEligibleSubjects twin, so a listing page also needs a
readEligibleSubjects of your own that reads the same eligibility authority as the fence, inside the page.
On a supported executor, a listing rejects with AccessListingUnavailableError and the reason
identity_evidence_missing until both the identity evidence and that eligibility reader are in place. On an
executor without listing pages (PGlite, or a custom PostgreSQL executor), it rejects with
capability_missing first, before identity or eligibility is checked.
Using teams with Rolebook directly
principalSet() builds the principals for Rolebook’s bind() and the requestingPrincipals for
sharing reads:
import { createAuthorizer, type RoleAssignment, type RolebookPolicy, type TrustedResource } from "rolebook";
import { principalSet, type TeamDirectory } from "@rolebook/teams";
declare const directory: TeamDirectory;
declare const policy: RolebookPolicy;
declare const assignments: readonly RoleAssignment[];
declare const resource: TrustedResource;
const subject = { type: "user", id: "alice" };
const teams = await directory.teamsOf({ tenantId: "ws_456", subject });
const { principals } = principalSet({ subject, teams });
const explanation = createAuthorizer(policy)
.bind({ subject, principals, assignments })
.explain({ permission: "project:update", resource });
explanation.matched?.via; // the team whose assignment decided Team members
The SQL and Better Auth directories also implement
TeamMemberDirectory, a separate interface, so other directory
implementations stay valid without it. membersOf({ tenantId, group, limit, cursor }) pages the individual
subjects that are direct members of exactly one team in exactly one tenant, ordered by subject ID in binary
order, for impact counting:
import type { ParameterizedSqlExecutor } from "@rolebook/sharing-postgres";
import { createBetterAuthTeamDirectory } from "@rolebook/teams/better-auth";
declare const executor: ParameterizedSqlExecutor;
declare const tenantId: string;
declare const teamId: string;
const teams = createBetterAuthTeamDirectory({ executor, schema: "auth" });
let affected = 0;
let cursor: string | undefined;
do {
const page = await teams.membersOf({
tenantId,
group: { type: "team", id: teamId },
limit: 100,
...(cursor === undefined ? {} : { cursor }),
});
affected += page.members.length;
cursor = page.nextCursor;
} while (cursor !== undefined); Teams are flat, so no team is returned and nothing is expanded. An unknown team, or one of another tenant,
gives an empty exhausted page; a malformed row fails the whole call with TEAM_RECORD_INVALID; a limit
outside 1 to 100 throws INVALID_LIMIT. A subject is in the full traversal exactly when teamsOf() reports
the team for it.
It enumerates direct directory membership, not effective eligibility or access, so its count is not an exact
count of the people a grant to the team affects. IDs are compared and listed in their canonical PostgreSQL
text form: an alias of an existing team (007 for 7, an upper-case UUID) gets an empty page. membersOf()
is PostgreSQL only: the SQL and Better Auth directories implement it, and there is no SQLite membersOf().
That limit applies to membersOf() only: listAccess() is available on the memory, PostgreSQL, and SQLite
adapters, under its own requirements.
membersOf() does not authorize: like teamsOf(), it is a trusted server-side directory API, and the
caller must authorize the request. Its nextCursor is the last returned subject ID, not sealed and bound
to nothing, so never accept it from an untrusted client. It lists team membership only; it is not a “who can
access this resource” query.
Deleting a team
When a team is deleted, teamsOf() stops returning it and teamExists() says it is gone, so its
memberships grant nothing, its pending invitations can no longer be accepted, and it cannot be granted
again. Its stale membership rows remain until you remove them with revokeMember. Nothing prevents a
deleted team’s ID from being reused, and a new team with the same ID in the same tenant would inherit the
stale memberships: use random team IDs (Better Auth does), or revoke a team’s memberships before deleting
it.
Testing
Run sharingTeamsContract() from @rolebook/sharing-testkit
against your adapter with team-aware identity and fences.