Authorization providers
Let another authorization system answer permission checks in the SQL modules, bucket and topic policies, API keys and doctor, through one versioned config key.
An authorization provider is a plain object in the authorization key of
better-supabase.config.ts. It tells better-supabase which SQL functions
answer "does this user hold this permission", which scopes exist, which
membership tables the provider reads, and which claims its access token hook
writes. better-supabase never imports the provider: the object is data, and
the provider's own package builds it, usually from the files that package
generates.
import { defineConfig } from "better-supabase/config";
import { authorizationProvider } from "your-authorization-package";
export default defineConfig({
auth: { authorization: authorizationProvider() },
blocks: { permissions: {}, organizations: {} },
});With authorization set, blocks.permissions.model defaults to
"provider", so can(), tenant_ids_with() and every module check answer
from the provider's templates.
PermDock builds one from its manifest and catalog.
The provider covers the database side. Permission checks in your server
code (a resource's permissions, an action's or MCP tool's permission, a
route guard) go to a runtime authorizer
instead, passed as authorizer to the server. An authorization package can
ship both: the provider for the config, and an authorizer for the server
that answers with the same permission keys.
A package that audits the tables it creates, or the app's tables, calls
better_supabase.audit() like the app does. Each call replaces the table's
settings, so pass the app's ignore and redact from audit_settings(table)
instead of calling it with defaults. See the
audit log.
Who owns what
better-supabase and an authorization library split the work at the token. better-supabase verifies tokens, keeps sessions and refreshes them, reads the claim names you configure, and builds each request's context. The library writes the claims its access token hook adds, ships its SQL helpers and policies, and makes every decision.
| better-supabase owns | The library owns |
|---|---|
| Token verification, the session memo and refresh | The access token hook and the claims it writes |
The claim names it reads (config.claims) | The SQL functions the provider object points at |
Building the request (AuthorizationRequest, context) | Its policies, roles, grants and their storage |
The slots below, each versioned with apiVersion: 1 | Every allow or deny decision behind those slots |
The library plugs in through these slots:
| Slot | Where |
|---|---|
authorization (AuthorizationProvider) | auth.authorization in better-supabase.config.ts |
authorizer (Authorizer) | createServer and createNext |
authorization (AuthorizationHooks) | createServer and createNext |
versions (AuthzVersionCache) | createServer and createNext |
policy (AccessBucketPolicy, AccessTopicPolicy) | a bucket or a realtime topic |
keys (ApiKeyResolverOptions) | the API key resolver |
credentials (CredentialProvider) | MCP clients and Chat SDK installations |
authorize (McpOptions) | createMcp, per tool call |
authorize (SupportAuthorize) | support sessions |
SessionSnapshot | what subject builders and a version cache read, on every adapter |
A change to one of these types fails
tests/core/authorization-library-contract.test-d.ts, so it can't land
without a new apiVersion.
Import the contract
better-supabase/contract re-exports every type in these slots, the
request types the authorizer receives (see
Authorizers) and ContractApiVersion. It is
types only, so an adapter can import it from any runtime without adding
code to its bundle:
import type {
Authorizer,
ContractApiVersion,
Provider,
TokenHook,
} from "better-supabase/contract";
const apiVersion: ContractApiVersion = 1;Provider is AuthorizationProvider and TokenHook is
AuthorizationTokenHook, under the names an adapter uses.
What reads it
| Feature | What it takes from the provider |
|---|---|
blocks.permissions.model: "provider" | can() and the modules' checks call functions, at tenantScope |
auth.entitlements.memberships: "provider" | has_entitlement and entitlement_members() call memberIds and memberIdsFor |
Bucket and topic access policies with sql | the idsWith and isPlatform templates, for any scope in scopes |
on.<type>.scope in attachments and comments | idsWith at that scope, for grants on a single record |
API keys with claim | nothing at runtime; the claim names follow the provider's functions |
better-supabase add memberships | refuses when tokenHook.ownedClaims has memberships (--force writes it) |
better-supabase gen | refuses a bucket or topic key that isn't sqlComplete: true |
| Doctor BS107, BS213, BS214, BS324, BS404, BS405, BS407 to BS409, BS411, BS419, BS420 | requires, decidingColumns, permissions, memberships, tokenHook, versions |
A block checks <block>.<action> by default, such as tags.read. When
authorization.permissions lists <resource>.<action> of the block's primary
entity (tag.read) and not the block's own key, the block checks the resource
key instead, so a provider that names permissions after resources needs no
blocks.<name>.permissions entries. An entry in blocks.<name>.permissions
always wins, and a block whose keys the provider lists under neither name still
fails the check that names the key to remap.
auth.entitlements.memberships and blocks.permissions.model both default to
"provider" when authorization is set. Set another access model to keep
the built-in roles; doctor BS414 then reports each policy and function that
calls can() or tenant_ids_with(), because those answer from roles the
provider never sees.
The config key covers SQL. Server code reads the same decisions from
runtime hooks, passed to createServer.
The contract
interface AuthorizationProvider {
apiVersion: 1;
name: string;
scopes: { name: string; idType?: string; parent?: string }[];
tenantScope: string;
functions: AuthorizationFunctions;
requires?: { function: string; args?: string; role: string }[];
permissions?: {
key: string;
sqlComplete?: boolean;
scopes?: string[];
levels?: string[];
}[];
memberships?: {
table: string;
userColumn: string;
userKey?: string;
scope: { column: string } | { value: string };
idColumn: string;
rolesTable?: string;
disabledAt?: string;
}[];
suspension?: {
user?: string | DisabledRow;
tenant?: DisabledRow;
userKey?: string;
};
roleSources?: AuthorizationRoleSource[];
platformRoles?: AuthorizationPlatformRoles;
personas?: AuthorizationPersona[] | "roles";
fixtureRoles?: AuthorizationFixtureRole[];
decidingColumns?: string[];
tokenHook?: AuthorizationTokenHook;
versions?: { function: string };
delegation?: { scopes?: Record<string, string[]> };
wildcards?: "all" | "prefix" | "none";
operations?: Record<string, AuthorizationOperation>;
/** @deprecated Ignored. `isApprover` decides. */
approvals?: { distinctApprover?: boolean };
problems?: string[];
}AuthorizationProvider and its parts are exported from
better-supabase/config. A scope name is lower case ([a-z][a-z0-9_]*),
because it goes into templates unquoted. problems lists what the provider
found wrong while building the object; doctor reports each one.
The CLI validates the object when it loads the config. Every scope name in
tenantScope and parent must be declared, parents must not form a cycle,
the tenant scope needs an idType, and idType is uuid, text, bigint
or integer. Each decidingColumns entry is schema.table.column, and
tokenHook.budget.bytes is a positive integer. An object with another
apiVersion gets one message naming both versions instead of a list of field
errors.
Nested tenancy
The built-in tenancy has one level: a row belongs to an organization, and
tenant_ids_with() returns organization ids. An app that splits each
organization into environments (or projects, or workspaces) models the extra
level as provider scopes. Each scope names its parent, and tenantScope
picks the level the modules treat as the tenant:
scopes: [
{ name: "organization", idType: "uuid" },
{ name: "environment", idType: "uuid", parent: "organization" },
],
tenantScope: "environment",
functions: {
idsWith: "authz.{scope}_ids_with({permission})",
isPlatform: "authz.is_platform({permission})",
memberIds: "authz.member_{scope}_ids()",
},With tenantScope: "environment", the modules' organization_id columns
hold environment ids, and can() asks the provider for the environments
where the caller holds a permission. The provider decides how a role on an
organization reaches its environments, so authz.environment_ids_with()
returns the environments of every organization where the caller holds the
key, plus those granted one by one. Keep tenantScope: "organization" when
the modules work per organization and only your own tables have an
environment column; your policies then call the provider's environment
function directly.
Functions
Each function is a SQL template. better-supabase fills the placeholders and puts the result into a policy or a module function:
| Template | Placeholders | Returns |
| ---------------------- | -------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| idsWith | {permission}, {scope} | a set of the {scope} ids where the caller holds the key |
| isPlatform | {permission} | boolean: the caller holds the key platform-wide |
| idsWithFor | {user}, {permission}, {scope} | as idsWith, for another user |
| isPlatformFor | {user}, {permission} | as isPlatform, for another user |
| memberIds | {scope} | the {scope} ids the caller is a member of |
| memberIdsFor | {user}, {scope} | as memberIds, for another user |
| teamIdsOf | {user} | a set of the team ids {user} belongs to |
| canAssign | {role}, {roles}, {tenant}, {scope} | boolean: the caller may give {role} in {tenant} |
| canAssignFor | {user}, {role}, {roles}, {tenant}, {scope} | as canAssign, for another user |
| roleIn | {role}, {tenant}, {scope} | whether {role} is a role of {tenant} (declared, or a custom role it owns or shares); with roles.many, membership_roles refuses every other role |
| permissionsFor | {user}, {tenant}, {scope} | text[]: the permission keys {user} holds in {tenant} |
| isApprover | {kind}, {subject}, {tenant}, {requester}, {approvers}, {scope} | boolean: the caller may approve request {subject} of kind {kind} |
| holdersOf | {permission}, {tenant}, {scope} | a set of user ids that hold {permission} on {tenant} |
| actorMayWrite | none | boolean: the caller's session may write |
| permitted | {permission}, {id}, {tenant}, {resource}, {scope} | boolean: the caller holds {permission} on instance {id} of {resource} |
| rowsWith | {permission}, {resource}, {ids} | a set of the ids (text) of {resource} rows the caller holds {permission} on |
| rowsWithFor | {user}, {permission}, {resource}, {ids} | as rowsWith, for another user |
| roleOn | {user}, {resource}, {id} | text: the role {user} holds on the {resource} row {id} (text), or null |
| portalSubjects | {action} | a set of (tenant, subject_type, subject_id) the caller reaches as a guest for {action} |
| portalParties | none | a set of (tenant, party_type, party_id) the caller acts for as a guest |
| subject | none | jsonb: the signed-in user's authorizer subject (a function name, called with no arguments) |
| subjectForTenant | {tenant}, {scope} | jsonb: that subject restricted to {tenant}; null for an unknown tenant. The caller is the user, so there is no {user}: authz.subject_for(auth.uid(), {tenant}) |
| bootstrapPermissions | {tenant}, {scope} | jsonb in the BootstrapPermissionsWire shape; a null {tenant} means every tenant the caller belongs to |
| approverFor | none | {kind}, {id}, {requester}, {tenant} | a set of user ids that may decide the request {id} of {kind} ('leave', 'expense', 'time-entry'). {requester} is the requester's user id and {tenant} the request's tenant, so a provider can answer from the manager chain without looking the request up. Leave, expenses and time entries read it when the block sets no decider; a template that names none of the four placeholders is not read |
| managedUsers | {tenant} (optional) | the user ids the caller manages in {tenant}. Leave, expenses and time entries count them as the caller's reports when they read or list requests |
| canApprove | {tool}, {tenant}, {scope} | ignored. Kept so an API 1 provider still loads; isApprover decides |
| canIn | {permission}, {tenant}, {scope} | boolean: the caller holds {permission} in {tenant}; the @bsb access tag puts it into its policies |
rowsWith answers a config.recordTypes.<type>.permissions.<action> entry with
rows (Actions granted per row).
{resource} is that entry's rows, unquoted, so it can be part of a
function name (app.rows_{resource}({permission})), and {ids} is a text[]
of the ids being checked, which a provider may use to limit its work. The
calendar block's accessFunctions and the drive block's roleFunctions take
{ rows } entries too, so those blocks check per-row grants without a
hand-written function; the calendar feeds use rowsWithFor to check the
link's creator.
roleOn is for a provider whose roles are not permission keys, such as a role
table or a relation graph. It names the role itself, so the drive block's
roleFunctions.node: { rows } without roles asks it once per node, and with
grants: "roles" the block keeps no grant rows at all
(Roles without grant rows). Return
one of the drive's roles; any other value counts as no role. The conformance
kit checks that the template names {user}, {resource} and {id}.
{roles} is the same role as a text[] (array[role]::text[]), for a
function that checks a set of roles at once. A memberships entry's
rolesTable names the table of a member's roles when a member can hold
several, one row per scope id, user and role; better-supabase's own is
better_supabase.membership_roles
(roles.many). Doctor
(BS411) warns when roles.many is on and no entry sets it.
idsWith and isPlatform are required. A template that leaves out a For
variant makes the module function answer for the caller only: called for
another user, it raises SQLSTATE 0A000. Without canAssign, only the
service role assigns roles: the permissions module's can_assign answers false
for every member, owners included.
Some modules call the optional templates under the provider model:
invitations calls idsWithFor, isPlatformFor and canAssignFor to check
the inviter again when an invitation is accepted; inbox, comments, sso,
notifications, connectors and workflow-sdk call idsWithFor; and
usage reads memberships through memberIds; approvals checks that a
delegate is a member through memberIdsFor. Doctor (BS411) warns for each
installed module whose template the provider doesn't set.
teamIdsOf is for a provider that keeps its own teams. team_ids_of() in
the teams block returns its set instead of reading team_members, and
saved-views and collections share with those teams even without the
teams block. Doctor (BS417) warns when the provider declares a team
scope and leaves it unset.
managedUsers takes {tenant} when the provider keeps a manager chain per
tenant: authz.managed_user_ids({tenant}) returns only the reports the caller
manages in that tenant, so a manager in one organization never reaches
reports in another. A template without {tenant} returns the users the caller
manages in every tenant.
canIn is the one capability the @bsb access table tag may use beyond what every
provider answers (Tags that render SQL). Write it for a
policy: {tenant} is usually a column, so answer from a set ({tenant} in (select ...))
instead of calling a function per row. A provider without canIn keeps working: the tag
renders {tenant} in (select better_supabase.tenant_ids_with({permission})), which your
idsWith template already answers, and actorMayWrite (or the built-in check) guards the
write policies.
permissionsFor fills better_supabase.member_permissions and
permission_claims, so the access token hook can carry permission keys. The
claims cover the tenants memberIdsFor returns; without memberIdsFor they
stay empty. Without permissionsFor, both functions return nothing, as
before.
functions: {
idsWith: "authz.{scope}_ids_with({permission})",
isPlatform: "authz.is_platform({permission})",
memberIds: "authz.member_{scope}_ids()",
canAssign: "authz.can_assign({role}, {tenant}::text)",
},
requires: [
{ function: "authz.organization_ids_with", args: "text", role: "authenticated" },
{ function: "authz.is_platform", args: "text", role: "authenticated" },
{ function: "authz.member_organization_ids", role: "authenticated" },
{ function: "authz.can_assign", args: "text, text", role: "authenticated" },
],requires lists every function the templates call, with {scope} filled,
and the role that must be able to execute it. Doctor (BS411) checks the
database has each one, and the conformance block checks the list is complete.
A function name with {resource}, such as authz.rows_{resource}, matches
any resource name ([a-z_][a-z0-9_]*), so requires lists each function as
the database names it (authz.rows_file_node) or once with the placeholder.
idType is the Postgres type of a scope's ids: uuid, text, bigint or
integer.
Permissions
permissions lists the keys the provider knows. sqlComplete: true says its
SQL functions answer the key completely: a grant has no row condition beyond
the scope. Bucket and topic policies and the SQL modules check by role and
scope only, so gen, add and doctor (BS214, BS411) refuse a key that
isn't marked. Leave row-conditioned keys to the provider's table policies.
The permissions claim carries the marked keys only:
better_supabase.member_permissions and permission_claims drop every key
without sqlComplete: true, because a key in the token is a grant in the
whole tenant. permissionsAuthorizer decides from that claim, so doctor
BS419 warns when app code uses it while some keys aren't marked: those keys
deny there unless its load option reads my_permissions. Check them with
your library's own authorizer instead.
wildcards says which wildcard grants the generated
better_supabase.permission_matches honours: all (the default) lets *
grant every key and prefix.* every key under the prefix, prefix drops the
bare *, and none matches the exact key only. Set none when your grants
never hold a wildcard, so a stray * row cannot widen access (ADR 0372). The
webhooks fan-out reads the same setting, so an endpoint's declared
permissions match an event's read permission only by the wildcards you allow
(ADR 0400).
Token hook
tokenHook describes the custom access token hook the provider generates:
| Field | Used for |
|---|---|
function | BS404 checks its grants, BS405 its shape |
tenantClaim | BS409 compares it with auth.tenant.claim |
activeOrganizationFrom | "claim", a profile column or "resolver" (the request, the default). BS409 compares it with blocks.permissions.activeTenant, where switch_organization writes |
ownedClaims | BS407 reports another hook that writes them; add memberships stops on them |
truncatedClaim | the marker the hook sets when it leaves claims out to fit the budget |
registeredClaims | BS407 accepts these claims from the functions named, such as features |
budget | BS405 measures the claims it lists against bytes for doctor --as |
markers | comment lines in the provider's files, so doctor recognises its hook and grants migration |
grantsCommand | the command BS404 suggests |
A hook that writes permissions itself lists it in ownedClaims. The hook
template better-supabase generates then leaves the claim out, and BS407
reports any other hook that still calls better_supabase.permission_claims,
so only one writer fills it. A provider that leaves the claim to
better-supabase lists it in registeredClaims with that function instead:
tokenHook: {
function: "authz.access_token_hook",
ownedClaims: ["memberships", "permissions"],
truncatedClaim: "claims_truncated",
budget: { bytes: 3072, claims: ["memberships", "permissions"] },
},truncatedClaim names the one boolean claim the hook sets when it trimmed
the claims in budget to fit. Without it, the marker is <claim>_truncated
(permissions_truncated for the permissions claim). better-supabase passes it
to permissionsOf and permissionsAuthorizer, which then answer "can't
say" instead of "not granted", so the caller asks the database. Read the
same names from better-supabase/claims instead of writing them out:
import {
MEMBERSHIPS_CLAIM,
PERMISSIONS_CLAIM,
isTruncated,
} from "better-supabase/claims";
export function complete(claims: Record<string, unknown>): boolean {
return (
!isTruncated(claims, PERMISSIONS_CLAIM, { marker: "claims_truncated" }) &&
claims[MEMBERSHIPS_CLAIM] !== undefined
);
}Approvals
isApprover is the one eligibility check for every request that waits for
someone else: AI tool calls in the ai-chat block
({kind} 'ai-tool', {subject} the tool's name) and support sessions
({kind} 'support-session', {subject} the request id). {tenant} is
required. {requester} is optional: the uuid of the user who asked (the
approval's requested_by, the support admin, the chat's owner). A provider
that resolves out-of-office covers inside isApprover reads it so a cover
never lets the requester's own delegator approve. {approvers} is optional:
a jsonb value with the approvers the request waits on now. The approvals
block passes its current step's approvers (users, permission, role,
team, manager, whichever the policy names) with the step's required
count, or the step's escalateTo once the step is escalated, for example
{"users": ["<uuid>"], "manager": true, "required": 1}. A provider reads it to
let a cover approve only where the absent user is a named approver. AI tool
calls and support sessions pass null. Under the provider model,
decide_ai_tool_approval lets the service role and any caller isApprover
allows decide the call. isApprover always refuses the requester, so
a request needs a second approver. Without
isApprover, the chat's owner decides a tool call.
holdersOf is the audience for notifications.send({ permission }): the
user ids that hold that key on the tenant. A provider sets it from its
manifest when the tenant scope lists permitted_<scope>_users, for example
permdock.permitted_organization_users({permission}, {tenant}). Grant
execute on that function to the role that owns send_notification, and
never to authenticated. Without the template, a notification that names
permission fails with NOTIFICATION_PERMISSION_AUDIENCE_UNAVAILABLE.
actorMayWrite replaces the built-in read of the act claim. A provider
sets it to permdock.permdock_actor_may_write() when the manifest lists
that helper. Write functions and write policies call the template and not
the built-in as well. Doctor BS413 warns when support sessions are installed
under the provider model and this template is missing.
functions: {
// ...
isApprover: "authz.is_approver({kind}, {subject}, {tenant}::text, {requester})",
},Out-of-office covers
The approvals block's delegate(id, userId) hands one approver's place on
one step of one request to someone else. A standing cover ("Ana approves for
Ben until Friday") is a different thing, and it belongs to the provider when
the provider has one: its isApprover answers true for the cover as well as
for Ben, so every module that waits for an approval (the approvals block, AI
tool calls, support sessions) sees it without a configuration of its own.
Configure covers in one place only. An app without such a provider calls
delegate per request instead.
PermDock keeps covers in its approval_delegations table and resolves them
in permdock_is_approver, one hop deep, never for the requester's own
delegator. Its better-supabase adapter
passes {requester} for that check, and with requestApprovers: true also
{approvers}, so a cover reaches the users and managers a block policy
names.
Delegated tokens
delegation.scopes maps an OAuth scope to the permission keys a delegated
token (an OAuth client or an agent) may use. The access functions narrow
every check to those keys, and blocks.permissions.scopes is merged over it.
delegation.interactiveOnly lists the keys no delegated token or API key
gets, whatever its scopes; a provider leaves them out of its scopes too. See
Access.
delegation: {
scopes: { "invoices:read": ["invoices.read"], "invoices:write": ["invoices.read", "invoices.update"] },
},Share links as guests
The share-links block resolves a
token in security definer functions. A provider can instead turn the row
resolve_share_link returns into a link principal and exchange it for a
short-lived anonymous session, so a guest page reads the subject under the
provider's row-level security. PermDock's subjectFromShareLink does this:
it builds a link capability from the row, caps its lifetime at the row's
expiresAt, and denies when the row is missing, revoked or expired.
Guests and portals
portalSubjects and portalParties let a provider's external users (a
client, a contractor) into comments, attachments, invoices and bookings
without making them members. {action} is 'read', 'comment' or
'upload', and every column is read as text:
functions: {
portalSubjects: "authz.guest_records({action})",
portalParties: "authz.guest_parties()",
},access wraps them in better_supabase.portal_subjects(action) and
portal_parties(), which policies read through ctx.scope.guest and
ctx.scope.guestParty. With the guests block
installed, its own grants are added to the provider's sets. Without either,
the checks render false (ADR 0070).
Operations
operations maps an operation name to the permission it needs, so one table
names the permission for every workflow-editor node, MCP tool, AI tool and
inbox command. A module looks up <prefix><name> and falls back to its own
key, after the blocks.<module>.permissions rename:
| Prefix | Operations |
|---|---|
workflow.node. | workflow-editor nodes |
mcp.tool. | MCP tools |
ai.tool. | AI tools |
inbox.command. | inbox commands |
operations: {
"mcp.tool.search_invoices": { permission: "invoices.read" },
"ai.tool.refund": {
permission: "invoices.refund",
meta: { risk: "high", effects: ["write", "external"] },
},
},An MCP tool's operation, an agent's toolOperations and a
workflow-editor step's operation name an entry in place of the prefixed
one. Under the access module, better_supabase.operation_permission(op)
answers the key of any operation in SQL: the installed modules' operations
(<module>.<action>, such as audit.view) after renames, with this table
over them, and null for a name nobody declared.
Each permission must be in permissions when the provider lists them; the
conformance block checks it. meta.risk and meta.effects describe the
operation for approval prompts and tool listings.
Block tables
An adapter whose SQL reads the memberships or tenant tables asks for their
names instead of assuming better_supabase.memberships. blockTables(config)
from better-supabase/sql resolves them from the loaded config, with the
table and column renames and the block instances applied:
import { resolveConfig } from "better-supabase/config";
import { blockTables } from "better-supabase/sql";
import config from "../better-supabase.config";
const tables = blockTables(resolveConfig(config, process.cwd()));
const members = tables.memberships;
if (members) {
console.log(`select ${members.columns.user} from ${members.table}`);
}| Field | Table | Columns |
|---|---|---|
memberships | a member's tenant and role | tenant, user, role, disabledAt |
membershipRoles | one row per role, only with roles.many | tenant, user, role |
organizations | the tenants | id, name, slug, disabledAt, deletedAt |
byBlock | every installed block's tables, by block |
A field is absent when its block isn't installed, and a column is null
when the table has no such column. table is schema.name, with the
configured schema and table name.
Codemod renames
better-supabase/api/naming.json lists every rename the library has made, so
an adapter's own codemod or a check in its CI reads the same list. Each entry
in renames has from, to, a kind (such as env) and the release it
happened since:
import naming from "better-supabase/api/naming.json" with { type: "json" };
for (const rename of naming.renames) {
console.log(
`${rename.kind} ${rename.from} is now ${rename.to} (${rename.since})`,
);
}The file also has words (the vocabulary: tenant, record type, member and
the rest), allowlist (the names a check lets through) and env, the prefix
and the platform variables it ignores.
Bucket and topic policies
An access policy calls the access contract (tenant_ids_with,
is_platform) by default. Give it the provider's templates in sql, and it
calls those instead, for any scope they take. sql: "provider" uses the
provider's idsWith and isPlatform: better-supabase gen writes them into
the generated bucket meta, and better-supabase upgrade passes them to each
topic's sql(). A copy of the templates also works, so the bucket module
doesn't import the config; doctor (BS214) warns when the copy differs from the
provider.
import { defineBucket } from "better-supabase/storage";
export const documents = defineBucket({
id: "documents",
path: "{organizationId}/{documentId}/{name}",
policy: {
access: { read: "documents.browse", write: "documents.write" },
scope: "organization",
sql: "provider",
},
});A topic with sql: "provider" throws when its sql() runs without
templates. Pass them yourself outside upgrade:
topic.sql({ functions: config.authorization.functions });The scope id is compared as text, so a path or topic segment must be the id's
lowercase form. segment picks another path segment than {organizationId}.
Runtime hooks
The config key is plain data for SQL. AuthorizationHooks is the runtime
half: functions that decide the same things in server code, so one provider
can own automations, support sessions, delivery, identity links, chat
actions, approvals and delegated tokens end to end. Build it with defineAuthorizationHooks
from better-supabase/server and pass it to createServer:
import { createServer, defineAuthorizationHooks } from "better-supabase/server";
import { betterSupabase } from "./supabase";
const authorization = defineAuthorizationHooks({
apiVersion: 1,
name: "your-provider",
support: { authorize: async (input) => policy.supportStart(input) },
delivery: { subscribers: policy.subscribers, audience: policy.audience },
approverOf: (approver, request) => policy.mayApprove(approver, request),
});
export const bsb = createServer(betterSupabase, { authorization });Every hook is optional. A slot passed to a block directly wins over the hook.
| Hook | Decides | Owner page |
|---|---|---|
automation.mayPublish | whether the publisher may publish a version whose nodes need the stored permissions | Workflow builder |
automation.runAs | the claims each step of a published version runs with; null fails the step | Workflow builder |
support.authorize | a support session start: true still needs a second approver, { approvedBy } names one | Support sessions |
delivery.subscribers | which webhook endpoints, outbox consumers and realtime members may read an event | Outgoing webhooks |
delivery.audience | which notification recipients may read a notification | Notifications |
identities.principalByIdentity | the user or contact a verified email address or chat user links to | Identities |
chat.onAction | a button a linked chat user pressed, such as an approval | Chat SDK |
approverOf | whether a user may approve a request; the server side of isApprover | Approvals |
tickets.subject | the context an opaque run ticket stands for, for jobs and workflow steps | Jobs |
delegation.permissions | the permission keys a delegated token's scopes grant, as the cap forContext runs with | Access |
Without delivery.subscribers or delivery.audience, delivery still fails
closed on records: webhooks, notifications and reminders fall back to
subjectReaders, which keeps a subscriber only when
can_subject_for(user, type, id, 'read') is true for an event about a
registered subject, and realtime fan-out refuses such an event without a
policy.
Each hook fails closed. A throw or rejection refuses, null from runAs,
principalByIdentity or tickets.subject refuses, and no hook falls back to
the service role. better-supabase refuses a requester as their own approver
before it calls approverOf.
createServer throws when the hooks target another apiVersion, with a
message naming both versions.
Test the hooks
testAuthorizationHooks from better-supabase/testing runs the hooks a
provider sets against cases every provider must refuse: subscriber and
audience policies return a subset of their input, an unlinked identity is
null, a requester never approves their own request, a forged ticket is
null, an unknown publisher may not publish and gets no claims, an
unlinked chat author is refused, an admin with no claims cannot start a
support session, an admin is never named as their own support approver,
and a delegated token with no scopes maps to no permissions.
import { testAuthorizationHooks } from "better-supabase/testing";
import { it } from "vitest";
it("fails closed", () => testAuthorizationHooks(authorizationHooks()));Version cache
A provider that caches decisions per user can key them on an authorization
version: a number the database bumps whenever a user's roles or grants
change. An access token hook copies it into the token as authz_ver, and
session.authzVersion (on AuthSession and SessionSnapshot) reads it, or
null without the claim. issuedAt reads iat the same way.
The provider's library owns the cache. better-supabase types it
structurally as AuthzVersionCache, which only needs evict(userId).
Create it once at module scope, never per request or per cache scope, and
hand it to the server:
import "server-only";
import { createNext } from "better-supabase/next";
import { betterSupabase } from "./index";
import { versions } from "./authz";
export const bsb = createNext(betterSupabase, { versions });Every authorizer call then gets { versions, memo } as its runtime
(AuthorizerRuntime): versions is the shared cache, typed as the cache
you passed (see Typed versions),
and memo is a
RequestMemo for reads that several checks in one scope share. Create a
memo with requestMemo() from better-supabase/server; nothing request-specific lives in module state.
bsb.evictSession(userId) calls versions.evict(userId) next to
expiring the user's cache entries.
To evict on other instances too, have the database broadcast each change on
a private Realtime channel, and subscribe from the module that creates the
cache. The sessions module's authzVersions option does the database part:
it adds better_supabase.user_authz_versions, a bump_authz_version()
trigger for your role tables (bump_authz_versions(uuid[]) for a batch),
better_supabase.authz_version(uid) for your access token hook, and a
broadcast on AUTHZ_TOPIC for servers and on authz:<uid> for the user:
blocks: { sessions: { options: { authzVersions: true } } },create trigger user_roles_authz_version
after insert or update or delete on app.user_roles
for each row execute function better_supabase.bump_authz_version();import { subscribeAuthzVersions } from "better-supabase/server";
export const versions = createVersionCache();
subscribeAuthzVersions({
client: serviceClient,
versions,
onError: (error) => console.warn(error),
});With your own trigger, pass topic, event and userIdKey to match what
it sends (defaults AUTHZ_TOPIC, "changed" and "user_id").
Without a library cache
An app whose provider ships no cache can use createVersionCache from
better-supabase/server. It keeps the highest version seen per user (a slow
bootstrap never lowers a version a broadcast raised) and forgets an entry after
maxStaleMs, which bounds the staleness when an eviction message is lost. Pass
a store with get, set and delete (Redis, Vercel Runtime Cache) so
instances share what one learned. The in-process map holds at most
maxEntries users (default 10,000) and drops the least recently used one
first, so a long-lived server never grows with every user it has seen; the
shared store still has the dropped version.
The store keeps the time each version was read next to it: set(userId, version, at) receives that time in epoch milliseconds, and get returns
{ version, at } or undefined. The cache counts maxStaleMs from at, so a
store whose keys never expire still never serves a version older than that. A
value without a numeric version and at counts as a miss. A provider library
whose store has the same shape can share one store object with the cache.
import type { VersionStore } from "better-supabase/server";
import { createVersionCache } from "better-supabase/server";
const redisVersionStore: VersionStore = {
async get(userId) {
const raw = await redis.get(`authz:v:${userId}`);
return raw ? JSON.parse(raw) : undefined;
},
async set(userId, version, at) {
await redis.set(`authz:v:${userId}`, JSON.stringify({ version, at }));
},
async delete(userId) {
await redis.del(`authz:v:${userId}`);
},
};
export const versions = createVersionCache({
maxStaleMs: 60_000,
maxEntries: 5000,
store: redisVersionStore,
});Seed the subject from the bootstrap
An authorizer that loads a subject per user (roles and grants) can skip that query when the page's bootstrap already read it. Name a no-argument function that returns the subject as jsonb in the sessions option, either form of the entry:
blocks: {
sessions: {
options: {
bootstrap: { home: { readSet: "home", subject: "app.authz_subject" } },
},
},
},bsb.bootstrap returns it as subject. accessFor(source, { bootstrap })
passes { userId, version, subject } as runtime.seed (AuthzSubjectSeed) to
every check. Use the seed only when seed.userId is the caller and
seed.version equals the version you would read; otherwise load the subject as
before. The field is optional, so authorizers written for API v1 keep working.
With subjectForTenant set, a bootstrap call that names a tenant
(args.tenant) returns the subject restricted to it, so the payload never
carries the user's other tenants. Write it as
authz.subject_for(auth.uid(), {tenant}). The caller is the user, so there
is no {user}. The template must fail closed: null for an unknown tenant,
a tenant the user has no membership in and a null tenant. A call without a
tenant still gets subject.
Permissions in the bootstrap
A provider that sets functions.bootstrapPermissions gets the caller's
permissions returned by every sessions bootstrap wrapper, in the query that
checks the session, as Bootstrap.permissions. The wrapper calls only your
template ({tenant} is the page's tenant, or null for every tenant the
caller belongs to); it never names a provider function. Set permissions: false on a bootstrap entry to leave them out.
The value is versioned (apiVersion: 1) and has two forms:
{
"apiVersion": 1,
"tenants": { "<tenant id>": ["file.read", "file.write"] },
"platform": []
}{
"apiVersion": 1,
"form": "compact",
"keys": ["file.read", "file.write", "invoice.read"],
"tenants": { "<tenant id>": "Bw" },
"platform": "AQ"
}In the compact form keys lists every key once and each tenant (and
platform) is a bitset over that list in base64 or base64url: bit i is bit
i % 8 of byte i / 8, least significant first, and means keys[i] is held.
Postgres writes it with encode(bytes, 'base64'). compactBootstrapPermissions
and expandBootstrapPermissions from better-supabase/server convert between
the forms. With 150 tenants and 300 keys, the full form is 737,192 bytes and
the compact form 21,314 (97 percent less).
Reading fails closed: another apiVersion, a malformed list, a bitset with a
bit past the key list or a damaged encoding gives permissions: null, and the
page falls back to its authorizer. A provider returns an empty list for a
tenant it does not know. The page still asks the authorizer for the decision;
the permissions are data it can render from, never an allow.
Memberships without memberIds
A provider that lists memberships for the tenant scope and leaves
functions.memberIds and memberIdsFor out gets both derived from the rows:
the ids of the memberships whose user column equals auth.uid() (or {user})
and whose disabledAt is null. A template the provider sets always wins.
suspension.userKey becomes blocks.permissions.disabled.userKey unless the
config sets it.
Role personas
personas: "roles" with fixtureRoles (name, setup, permissions) writes
one access matrix file per role the provider's fixture seeds, as if each were
listed in personas. resolvePersonas(provider) returns the list.
Level keys
A permission may list levels (own, team, all). A level key is
<permission>@<level>, such as file.read@team, and a key without a level
means the whole tenant. permissionLevelKey and splitPermissionLevel from
better-supabase/config build and read them. The token hook sets
teamIdsTruncatedClaim (default team_ids_truncated) when team_ids is not
the user's whole list; teams have their own slice, so a truncated
permissions claim says nothing about them.
Versions the provider keeps
A provider whose library already stores a version per user names its
function in versions, so the app doesn't get a second table:
versions: { function: "authz.user_version" },The function takes the user id and returns a bigint, 0 before the first
change. It can be closed to client roles. The provider then broadcasts
{ user_id, version } as changed on authz:<uid> (and AUTHZ_TOPIC for
servers, if it wants server eviction), ships the realtime.messages policy
that lets each user receive their own topic, and has its token hook write
authz_ver from the same function.
With versions set, authzVersions: true renders no table, trigger,
broadcast or receive policy. It still adds
better_supabase.caller_authz_version(), which the bootstrap wrappers and
api.caller_authz_version() read, and which calls the provider's function
for auth.uid(). Doctor BS420 reports a user_authz_versions table left
from before and an app hook that still reads better_supabase.authz_version.
A provider that caches its own entries in bsb.cached() scopes returns
their tags from sessionTags(userId) in its authorization hooks. Cached
entries then carry those tags, and evictSession, sign-out and
bsb.refreshSessionCache() clear them with the session tags:
export const authorization: AuthorizationHooks = {
apiVersion: 1,
name: "my-provider",
sessionTags: (userId) => [`my-provider:${userId}`],
};The subscriber joins with the service-role client, so the channel needs no
realtime.messages policy and no user can listen. Each message evicts one
user; a malformed message goes to onError. A second call with the same
versions returns the first subscription; its ready promise settles once
the channel joined, and close() leaves it. Start it from that module, not from instrumentation.ts, so the
cache and its subscription live and die together.
The subscriber keeps a Realtime channel open for as long as the process
runs, so it only evicts reliably in a long-lived process, such as a Node
server or a container. Serverless instances (Vercel Functions, AWS Lambda,
Cloudflare Workers) freeze between requests and miss the broadcasts sent
in the meantime. There, don't call subscribeAuthzVersions. Give the
provider's cache a short maximum age instead, so each instance reads a
user's version again once it is older than that, and keep calling
bsb.evictSession(userId) where the change happens, which evicts the
user on that instance right away:
export const versions = createVersionCache({ maxStaleMs: 30_000 });maxStaleMs is the provider cache's option, not a better-supabase one; check
your library for its name. It bounds how long another instance can decide
with an old version.
Devices follow the same versions. The browser and native SessionProvider
listen on authz:<uid> by default and refresh the token when the version is
ahead of the token's authz_ver, and the native one reconnects PowerSync
afterwards. A library that broadcasts on its own topic passes topic and
event, or an AuthzVersionSource as source when it delivers versions
another way; the token hook must still write authz_ver, because the
providers compare against it
(Authorization refresh on native).
Provider fields by release
Every field below is optional and additive. A config value you set always wins over the provider's.
| Field | What it fills | Release |
|---|---|---|
functions.subject | the subject the sessions bootstrap returns and seeds, when an entry sets no subject | 0.58 |
roleSources[].role.through tenant and where | blocks.memberships.options.roleThrough | 0.58 |
memberships[].disabledAt | the memberships disabledAt column | 0.58 |
platformRoles | blocks.invitations.options.platformRoles | 0.58 |
personas | one access matrix file per persona (providerPersonaTests) | 0.58 |
wildcards | the wildcard grants permission_matches honours (all, prefix, none) | 0.58 |
memberships[].userKey, suspension.userKey | the user key of the membership table and of blocks.permissions.disabled | 0.58 |
functions.subjectForTenant | the bootstrap subject restricted to the page's tenant | 0.58 |
functions.bootstrapPermissions | the caller's permissions in the bootstrap, full or compact (apiVersion: 1) | 0.58 |
functions.approverFor, functions.managedUsers | the user sets for approver covers and manager chains | 0.58 |
{tenant} in functions.managedUsers | the manager chain of one tenant, so a manager never reaches reports in another tenant | 0.58 |
personas: 'roles', fixtureRoles | one access matrix file per fixture role | 0.58 |
permissions[].levels | the levels of a permission (<permission>@<level> keys) | 0.58 |
tokenHook.teamIdsTruncatedClaim | the claim that marks a partial team_ids | 0.58 |
tokenHook.truncatedClaim | the claim that marks a partial permissions list | 0.58 |
versions | the function that returns the caller's authorization version | 0.58 |
delegation | OAuth scopes mapped to permission keys | 0.58 |
operations | named operations and the permission key each one needs | 0.58 |
AuthorizationProvider<Key> | typed permission keys in blocks.*.permissions, subjects.*.permissions and the role lists | 0.58 |
functions.approverFor with {kind}, {id}, {requester} or {tenant}, functions.managedUsers | leave, expenses and time entries decide and list through them | 0.82 |
actionKeys | the permission keys of block actions, record types, buckets and topics, so the config does not repeat them | 0.82 |
doctor.command | a command doctor runs in the project root, whose JSON findings join the report as BS705 and the baseline | 0.82 |
doctor.timeoutMs | the milliseconds the command may run before it is stopped and reported, 60000 by default | 0.83 |
operations[name].approval | the approval floor of an operation named <subjectType>:<action> | 0.82 |
functions.canApprove, approvals.distinctApprover | ignored. An API 1 provider that still sets them loads | 0.58 |
suspension.user as a column name | userKey matches that column when the provider's user is the one in use | 0.58 |
functions.canIn | the permission check the @bsb access tag renders into its policies; the tag falls back to tenant_ids_with | 0.58 |
seed.tenant (AuthzSubjectSeed) | the tenant a seeded subject belongs to, so accessOf and testAuthorizer keep it out of other tenants | 0.58 |
tables | share: "tenant" or "row" per table, with the permissions its reads check, for shared cache entries | 0.85 |
context.enforcement on the authorizer's request | rls or definer, so the adapter can skip its live version read for a write RLS checks again (Enforcement) | 0.85 |
sharedFunctions | the functions a share: "tenant" fill may call, with the tables each reads and the permissions they check | 0.85 |
permissionFilters | helpers that return the ids a literal permission key grants, which a sharedFunctions function may call | 0.86 |
Doctor reports a config value equal to the provider's (BS427).
tables says which tables every caller with the same permissions in a tenant
reads alike. share: "tenant" lets bsb.kept and bsb.remote with
share: "tenant" keep one entry for those callers; share: "row" (or no
entry) keeps one per user. The hooks' shareKey names the caller's grant, and
permissionsShareKey() reads it from the permissions claim. Doctor BS428
fails a tenant table whose select policies filter by the caller.
sharedFunctions does the same for a database function: a page that loads in
one RPC can keep one entry per grant when the function reads only tables the
provider shares per tenant. Name the function by schema.name (public when
the schema is left out) and list the tables it reads and the permissions
those reads check:
sharedFunctions: {
"api.customer_payload": {
tables: ["customers", "customer_contacts"],
permissions: ["crm.read"],
},
},The entry then lists it in functions instead of tables:
bsb.kept(fn, { name, functions: ["customer_payload"], share: "tenant" }).
Inside the fill $rpc passes only the listed functions. Doctor
BS430 fails a function that is security definer,
isn't language sql, is volatile, reads the caller (auth.uid(),
current_setting('request.jwt.claims'), current_user), reads a table its
entry doesn't list, or calls a function it doesn't admit, and lists every
reason. A payload function that also returns the caller's own rows doesn't
qualify; split it into a tenant function you share and a per-user read you
keep with share: "user". Run
better-supabase config functions --shareable 'public.*_payload' to see which
of your functions pass before you list them.
permissionFilters
A payload function often narrows its rows with a provider helper, such as
app_auth.allowed_org_ids('crm.read'), which returns the ids the caller holds
a permission on. The helper reads the caller, so BS430 refuses the call unless
the provider lists the helper in permissionFilters, by schema.name, with
the position of the argument that holds the permission key:
permissionFilters: {
"app_auth.allowed_org_ids": { keyArgument: 0 },
},BS430 then admits a call whose key is a string literal that the entry's
permissions lists. Two callers with the same share key hold the same grants
for those keys in the tenant, so the helper returns them the same ids, and the
function returns them the same rows. A key built at run time, or one the entry
leaves out, fails the check, because the share key would not cover it. List a
helper here only when its result depends on nothing but the caller's grants
for that key in the current tenant: no user id, no row-level grant, no time.
ADR 1228
has the argument.
import type { AuthorizationProvider } from "better-supabase/config";
import { permissionsShareKey } from "better-supabase/blocks/permissions";
import { defineAuthorizationHooks } from "better-supabase/server";
export const tables: AuthorizationProvider["tables"] = {
"public.customers": { share: "tenant", permissions: ["customer.read"] },
"public.notes": { share: "row", permissions: ["customer.read"] },
};
export const authorization = defineAuthorizationHooks({
apiVersion: 1,
name: "my-provider",
shareKey: permissionsShareKey(),
});Test a provider
testAuthorizationProvider from better-supabase/testing checks API v1,
plain JSON, valid scopes (known names, no parent cycle, a tenant scope with an
idType), the placeholders of each template (an unknown function name fails,
each template uses its {permission}, {user}, {tenant} and {role}, and
idsWith and idsWithFor use {scope} when there is more than one scope),
that templates are safe to
inline (a tokenizer reads strings, quoted identifiers and comments whole, then
refuses a function call without a schema, a dollar-quote tag such as $$ or
$tag$, a ;, a comment, an unterminated string and a stray {), that
requires lists every function the templates call, the permission list, and
the shapes of
memberships, suspension, roleSources, decidingColumns and
tokenHook: ownedClaims is not empty, a registeredClaims entry is not also
owned, budget.claims are owned or registered, and budget.bytes is a
positive integer. It also checks that the hook names one truncated marker
(an identifier, apart from the claims it marks, the same in truncatedClaim
and budget.truncatedClaim, and present when the budget counts a
permissions claim the hook writes), and that a hook writing permissions
has at least one sqlComplete key. With versions, it checks that the
function is a lower-case schema.function and that the token hook, if any,
owns or registers authz_ver. Pass { postgres } (from createPostgres()
in better-supabase/postgres) against a database with the provider's SQL
applied, and it also checks that the function takes a uuid and returns
bigint, that a signed-in user can't read another user's version, and that a
realtime.messages policy mentions authz:. See
conformance blocks.
import { createPostgres } from "better-supabase/postgres";
import { testAuthorizationProvider } from "better-supabase/testing";
import { afterAll, it } from "vitest";
const postgres = createPostgres({ connectionString: process.env.DATABASE_URL });
afterAll(() => postgres.end());
it("conforms", () => testAuthorizationProvider(authorizationProvider()));
it("conforms in the database", () =>
testAuthorizationProvider(authorizationProvider(), { postgres }));A provider for a new contract version sets another apiVersion; this release
refuses anything but 1 with a message naming both versions.
Last updated on
Authorizers
The runtime authorization decision point that resources, actions, route guards and MCP tools ask for their permission, in the AuthZEN request model, failing closed.
Document formats
Render the API model to a standard better-supabase does not ship, such as a Postman collection or a GraphQL schema, with defineDocumentFormat and testDocumentFormat.