@rolebook/teams API
Every export of @rolebook/teams and its /sql, /better-auth, and /sqlite entry points.
Four entry points: @rolebook/teams, @rolebook/teams/sql (needs @rolebook/sharing-postgres for its
types and fences), @rolebook/teams/better-auth, and
@rolebook/teams/sqlite (needs @rolebook/sharing-sqlite). The package root
does not load the SQLite module. Signatures are checked against the built declarations. See the
teams guide.
Identity
withTeams
function withTeams(
identity: TenantIdentityAdapter,
options: TeamIdentityOptions,
): TenantIdentityAdapter; Wraps any TenantIdentityAdapter so eligible individuals carry their current teams (after the base
adapter’s own groups, capped at 64), one TEAM_MEMBERSHIP_AUTHORIZATION_FACT per team, and one
TEAM_SET_AUTHORIZATION_FACT with the whole set. Teams are looked up only for a principal the base adapter
found eligible. A base principal with assignments but no subject-scoped authorization fact is returned as
ineligible. A subject of the team type resolves as a group principal when teamExists says so. A team
invitation matches a current tenant member who is a current member of that team. Throws TypeError for an
invalid option, and when teamSetFactType equals authorizationFactType.
withTeamLineage
function withTeamLineage(identity: TenantIdentityAdapter, source: TeamLineageSource): TenantIdentityAdapter; Nested-team wrapper. Effective groups replace the flat team list for source.teamType. More than 64
merged groups throws HierarchyUnavailableError principal_cap. More than 256 raw assignments
throws budget_exhausted. A failed
resolution throws HierarchyUnavailableError; it is not an ordinary eligibility denial. Invitation
acceptance uses the groups and the lineage fact already on the principal. Wrapping the same team type
with withTeams() throws TypeError. A remote identity host does not qualify as source: the storage
adapter recomputes the same resolution inside the write transaction.
TeamLineageSource
interface TeamLineageSource {
readonly profileId: string;
readonly teamType: string;
readonly identityStability: "registry_incarnation" | "ids_never_reused";
readonly workspaceResourceType?: string;
teamExists(input: {
readonly tenantId: string;
readonly team: ResourceRef;
}): Promise<boolean>;
readGraphToken(input: {
readonly tenantId: string;
}): Promise<string>;
resolve(input: {
readonly tenantId: string;
readonly subject: ResourceRef;
}): Promise<GroupLineageResolution>;
} identityStability is an explicit declaration. teamIdsGloballyUnique is a different flag and does
not set this. registry_incarnation means the directory stores an incarnation that changes when a
team id is created again. ids_never_reused means this deployment does not reuse team ids; the
directory then has no incarnation column. readGraphToken returns the lifecycle generation from the
same snapshot as resolve, or "absent" when the graph row is absent. workspaceResourceType
defaults to "workspace".
resolveTeamLineage
function resolveTeamLineage(input: Parameters<typeof resolveGroupLineage>[0]): Promise<GroupLineageResolution>; Resolves one subject’s direct groups through a reader bound to one snapshot. ok: true carries
direct (direct memberships) and groups (direct memberships plus ancestors). ok: false carries
cause (graph_quarantined, graph_corrupt, principal_cap, registry_unavailable,
lineage_invalid, budget, or profile_unbound). The function does not grant a permission and does
not write.
TeamIdentityOptions
interface TeamIdentityOptions {
readonly teams: TeamRegistry;
readonly teamType?: string;
readonly workspaceResourceType?: string;
readonly authorizationFactType?: string;
readonly teamSetFactType?: string;
} teams (a TeamRegistry), teamType (default "team"), workspaceResourceType (default
"workspace"), authorizationFactType, and teamSetFactType.
Directories
TeamDirectory
interface TeamDirectory {
teamsOf(input: {
readonly tenantId: string;
readonly subject: ResourceRef;
}): Promise<readonly TeamRef[]>;
} Answers which teams a subject belongs to in exactly one tenant. Implementations return a bounded,
deduplicated, frozen list; throw TeamDirectoryError for a malformed record, more than 64 teams, or a
subject type they do not answer for; and answer [] for a team subject.
TeamRegistry
interface TeamRegistry extends TeamDirectory {
teamExists(input: { readonly tenantId: string; readonly team: ResourceRef }): Promise<boolean>;
} A directory that can also confirm a team exists in a tenant, under exactly the ID teamsOf() reports.
TeamMemberDirectory
interface TeamMemberDirectory {
membersOf(input: {
readonly tenantId: string;
readonly group: ResourceRef;
readonly limit: number;
readonly cursor?: string;
}): Promise<TeamMembersPage>;
} Pages the individual subjects that are direct members of exactly one team in exactly one tenant, for impact
counting: ordered by subject ID as exact strings in the database’s binary order, limit an integer from 1 to
100 (otherwise TeamDirectoryError INVALID_LIMIT). Teams are flat: no team is returned and nothing is
expanded. A team that does not exist in the tenant, or exists only in another tenant, gives an empty exhausted
page. A malformed row fails the whole call with TEAM_RECORD_INVALID, as does a cursor that is not a valid
opaque ID. A full traversal contains a subject exactly when teamsOf() for that subject reports the team.
Identities are canonical text: the column’s PostgreSQL text form (::text) under the binary "C" collation,
deduplicated before the limit, for text, varchar, citext, uuid and integer columns. The group ID
matches only the canonical spelling teamsOf() reports, so an alias such as 007 for 7 or an upper-case UUID
gets an empty exhausted page, and only canonical member IDs are listed. Pages are live, not a timeless inverse
of teamsOf() under churn. It enumerates direct directory membership, not effective eligibility or access,
and its count is not an exact effective-impact count.
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.
It is a separate interface, so TeamDirectory and TeamRegistry implementations stay valid without it. It is
a trusted server-side directory API, like teamsOf(), and performs no authorization: the caller must
authorize the request. nextCursor is the last returned subject ID, not sealed and not bound to the tenant
or team, so never accept it from an untrusted client. It is not a “who can access this resource” query.
TeamMembersPage
interface TeamMembersPage {
readonly members: readonly ResourceRef[];
readonly nextCursor?: string;
readonly exhausted: boolean;
} TeamRef
type TeamRef = GroupPrincipalRef; A team principal: a GroupPrincipalRef, so ownership paths reject it at compile time.
resolveTeams
function resolveTeams(
directory: TeamDirectory,
input: {
readonly tenantId: string;
readonly subject: ResourceRef;
},
teamType?: string,
): Promise<readonly TeamRef[]>; Calls a directory and validates its answer whatever the implementation: a dense array of at most 64
distinct references of the team type, none equal to the subject. Throws TeamDirectoryError otherwise.
teamRefsFromIds
function teamRefsFromIds(ids: readonly unknown[], teamType?: string): readonly TeamRef[]; Validates raw team IDs into frozen, deduplicated TeamRefs, throwing TeamDirectoryError for a bad ID or more than 64.
TeamDirectoryError
class TeamDirectoryError extends Error {
readonly code: TeamDirectoryErrorCode;
constructor(code: TeamDirectoryErrorCode, message: string);
} A team lookup that cannot be answered completely. It propagates out of sharing operations; treat it as an application fault.
TeamDirectoryErrorCode
type TeamDirectoryErrorCode =
| "TEAM_RECORD_INVALID"
| "TOO_MANY_TEAMS"
| "UNSUPPORTED_SUBJECT_TYPE"
| "INVALID_LIMIT"; INVALID_LIMIT is thrown only by membersOf().
Principal sets
principalSet
function principalSet(input: {
readonly subject: ResourceRef;
readonly teams: readonly ResourceRef[];
}): PrincipalSet; The principal set for one request: principals for Rolebook’s bind() and requestingPrincipals
(subject first) for sharing reads. Throws for a malformed subject, a team equal to the subject, a repeated
team, or more than 64 teams.
PrincipalSet
interface PrincipalSet {
readonly subject: ResourceRef;
readonly principals: readonly TeamRef[];
readonly requestingPrincipals: readonly ResourceRef[];
} encodeTeamSet
function encodeTeamSet(teamIds: readonly string[]): string; The canonical team-set encoding a fence compares: a JSON array of the distinct IDs in ascending UTF-16 code-unit order ("[]" for none).
Constants
TEAM_SUBJECT_TYPE
const TEAM_SUBJECT_TYPE = "team"; The default team subject type.
TEAM_MEMBERSHIP_AUTHORIZATION_FACT
const TEAM_MEMBERSHIP_AUTHORIZATION_FACT = "rolebook.teams.team-member.v1"; The fact type for one team membership that may have authorized a mutation.
TEAM_SET_AUTHORIZATION_FACT
const TEAM_SET_AUTHORIZATION_FACT = "rolebook.teams.team-set.v1"; The fact type for a subject’s complete team set; its values are teamType and teamIds.
MAX_TEAMS_PER_SUBJECT
const MAX_TEAMS_PER_SUBJECT: typeof MAX_GROUP_PRINCIPALS; 64: Rolebook’s principal cap.
@rolebook/teams/sql
import { ... } from "@rolebook/teams/sql": application-owned team tables, read through the @rolebook/sharing-postgres executor.
createSqlTeamDirectory
function createSqlTeamDirectory(
options: SqlTeamDirectoryOptions,
): TeamRegistry & TeamMemberDirectory; A TeamRegistry and TeamMemberDirectory over application-owned team tables (default
DEFAULT_SQL_TEAM_TABLES). Every lookup names the explicit tenant and subject. membersOf() joins a
membership to its team on the membership tenant when the table has one, matches the team ID exactly, and
orders subject IDs under the binary "C" collation; every value is a bound parameter. Throws TypeError when member.tenantColumn is missing without
teamIdsGloballyUnique: true, or when subjectType equals teamType.
SqlTeamDirectoryOptions
interface SqlTeamDirectoryOptions {
readonly executor: ParameterizedSqlExecutor;
readonly tables?: SqlTeamTables;
} SqlTeamTables
interface SqlTeamTables {
readonly team: {
readonly table: QualifiedIdentifier;
readonly idColumn: string;
readonly tenantColumn: string;
};
readonly member: {
readonly table: QualifiedIdentifier;
readonly teamIdColumn: string;
readonly subjectIdColumn: string;
readonly tenantColumn?: string;
};
readonly teamIdsGloballyUnique?: boolean;
readonly subjectType?: string;
readonly teamType?: string;
} Where teams and memberships live: tables, ID, tenant, and subject columns, teamIdsGloballyUnique, subjectType (default "user"), teamType.
DEFAULT_SQL_TEAM_TABLES
const DEFAULT_SQL_TEAM_TABLES: SqlTeamTables; team(tenant_id, id) and team_member(tenant_id, team_id, user_id).
createPostgresTeamFences
function createPostgresTeamFences(options: PostgresTeamFenceOptions): PostgresTeamFences; Team-aware lockEligibleSubjects and revalidateAuthorizationFacts for
createPostgresSharingAdapter(), composed with your own fences. See fences.
PostgresTeamFenceOptions
interface PostgresTeamFenceOptions {
readonly tables?: SqlTeamTables;
readonly eligibility: PostgresEligibilityFence;
readonly authorizationFacts?: PostgresAuthorizationFactFence;
readonly warn?: (message: string) => void;
readonly factType?: string;
readonly teamSetFactType?: string;
} eligibility (required), authorizationFacts, tables, warn (default console.warn), factType, teamSetFactType.
PostgresTeamFences
interface PostgresTeamFences {
readonly lockEligibleSubjects: PostgresEligibilityFence;
readonly revalidateAuthorizationFacts: PostgresAuthorizationFactFence;
} Spread into createPostgresSharingAdapter() options.
createPostgresTeamLineageDirectory
function createPostgresTeamLineageDirectory(tables: SqlTeamTables, options: {
readonly identityStability: "registry_incarnation" | "ids_never_reused";
readonly incarnationColumn?: string;
}): Readonly<{
readDirectTeams(input: {
readonly executor: ParameterizedSqlExecutor;
readonly tenantId: string;
readonly subject: ResourceRef;
readonly lock?: "share" | "none";
}): Promise<readonly import("@rolebook/sharing").GroupPrincipalRef[]>;
readEndpoint(input: {
readonly executor: ParameterizedSqlExecutor;
readonly tenantId: string;
readonly group: ResourceRef;
readonly lock?: "share" | "none";
}): Promise<{
present: false;
incarnation?: never;
} | {
present: true;
incarnation: null;
} | {
present: true;
incarnation: string;
}>;
}>; Transactional directory for a nested-team profile. Pass it as groupGraph.directory on
createPostgresSharingAdapter(). readDirectTeams returns the configured individual type’s direct
teams, and returns [] for the configured team type. An unsupported third type throws
HierarchyUnavailableError lineage_invalid. More than 64 distinct teams throws principal_cap.
A malformed registry team id throws registry_unavailable. A driver error propagates unchanged.
lock: "share" takes the membership-table share lock
used inside a write. lock: "none" is the read-only snapshot and takes no row lock.
registry_incarnation requires incarnationColumn. ids_never_reused rejects an incarnation column.
teamIdsGloballyUnique does not imply ids_never_reused.
readEndpoint answers whether that team id exists in the tenant. Under registry_incarnation the
incarnation is the column text; a missing or empty incarnation is { present: false }.
@rolebook/teams/better-auth
import { ... } from "@rolebook/teams/better-auth": the same directory and fences over Better Auth’s team and teamMember tables.
createBetterAuthTeamDirectory
function createBetterAuthTeamDirectory(
options: {
readonly executor: ParameterizedSqlExecutor;
} & BetterAuthTeamTableOptions,
): TeamRegistry & TeamMemberDirectory; A team directory over Better Auth’s tables. Never consults the active organization or team. It implements
membersOf(): team carries the organization and teamMember.teamId references the team’s globally unique
ID, so one team’s members are an exact, organization-scoped, ordered page.
createBetterAuthTeamFences
function createBetterAuthTeamFences(
options: Omit<PostgresTeamFenceOptions, "tables"> & BetterAuthTeamTableOptions,
): PostgresTeamFences; createPostgresTeamFences() over Better Auth’s tables.
betterAuthTeamTables
function betterAuthTeamTables(options?: BetterAuthTeamTableOptions): SqlTeamTables; The SqlTeamTables for Better Auth’s team and teamMember tables, with teamIdsGloballyUnique: true.
BetterAuthTeamTableOptions
interface BetterAuthTeamTableOptions {
readonly schema?: string;
readonly teamTable?: string;
readonly teamMemberTable?: string;
readonly fields?: {
readonly teamId?: string;
readonly teamOrganizationId?: string;
readonly memberTeamId?: string;
readonly memberUserId?: string;
};
readonly subjectType?: string;
readonly teamType?: string;
} Optional schema, teamTable, teamMemberTable, fields, subjectType, and teamType.
@rolebook/teams/sqlite
import { ... } from "@rolebook/teams/sqlite". This entry loads @rolebook/sharing-sqlite and is not
imported by the package root. SQLite has no roles; keep a single writer for the database before
activating a graph. The directory reads direct memberships inside the caller’s transaction.
BEGIN IMMEDIATE is the write exclusion, so these methods take no lock argument.
SqliteTeamTables
interface SqliteTeamTables {
readonly teamTable: string;
readonly memberTable: string;
readonly teamIdColumn?: string;
readonly memberTeamIdColumn?: string;
readonly tenantColumn?: string;
readonly memberTenantColumn?: string;
readonly subjectIdColumn?: string;
readonly subjectType?: string;
readonly teamType?: string;
readonly identityStability: "registry_incarnation" | "ids_never_reused";
readonly incarnationColumn?: string;
} teamIdColumn defaults to id. memberTeamIdColumn defaults to team_id, which is the membership
column, not the team table’s id column. tenantColumn and memberTenantColumn default to
tenant_id. subjectIdColumn defaults to user_id. subjectType defaults to "user" and must
differ from teamType (default "team"). registry_incarnation requires incarnationColumn.
createSqliteTeamLineageDirectory
function createSqliteTeamLineageDirectory(tables: SqliteTeamTables): Readonly<{
readDirectTeams(input: {
readonly executor: ParameterizedSqliteExecutor;
readonly tenantId: string;
readonly subject: ResourceRef;
}): Promise<readonly TeamRef[]>;
readEndpoint(input: {
readonly executor: ParameterizedSqliteExecutor;
readonly tenantId: string;
readonly group: ResourceRef;
}): Promise<{
present: false;
incarnation?: never;
} | {
present: true;
incarnation: null;
} | {
present: true;
incarnation: string;
}>;
}>; readDirectTeams returns the configured individual type’s direct teams. It returns [] for the
configured team type. An unsupported third type throws HierarchyUnavailableError
lineage_invalid. More than 64 distinct teams throws principal_cap.
A malformed registry team id throws registry_unavailable. A driver error propagates unchanged.
readEndpoint confirms the team row in the named tenant. Pass the
directory as groupGraph.directory on createSqliteSharingAdapter(), with the same
identityStability and teamType. There is no SQLite membersOf(); direct membership pages stay on
the PostgreSQL directories.