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.
An Authorizer decides whether the caller holds a permission. Resources,
actions, route guards and MCP tools declare a permission, and
better-supabase builds an access request from the verified request context
and asks the authorizer. Anything but a clear grant refuses the request.
The interface is provider-neutral and versioned (apiVersion: 1):
authorization libraries ship an adapter that implements it, and
better-supabase names none of them. The schema side of authorization (the
SQL a library installs) is the separate
AuthorizationProvider.
The contract
interface Authorizer<
Ref = string,
V extends AuthzVersionCache = AuthzVersionCache,
> {
apiVersion: 1;
name: string;
// The stable key of a permission reference, for documents, SQL and messages.
key(ref: Ref): string;
// The default permission of a table operation; makes `permissions: true` work.
forOperation?(table: string, operation: string): Ref | undefined;
evaluate(
request: AuthorizationRequest<Ref>,
runtime?: AuthorizerRuntime<V>,
): AuthorizationOutcome | Promise<AuthorizationOutcome>;
// The batch form; results keep the request order.
evaluations?(
requests: readonly AuthorizationRequest<Ref>[],
runtime?: AuthorizerRuntime<V>,
): Promise<readonly AuthorizationOutcome[]>;
}runtime holds the server's versions cache and the request scope's
memo (see Share work in a request).
Ref is whatever your permissions are: plain strings, or typed objects your
library defines. The permission options of resources, actions and tools
are typed from the authorizer you pass, so a typo fails to compile when
Ref is narrower than string. key() turns a reference into the string
the API document (x-better-supabase-permission), error responses and logs
use.
defineAuthorizer from better-supabase/server builds one. It sets
apiVersion: 1, infers Ref from key(), and types the request
evaluate receives. A minimal authorizer over a table of grants:
import { defineAuthorizer } from "better-supabase/server";
export const authorizer = defineAuthorizer({
name: "grants",
key: (permission: string) => permission,
async evaluate({ subject, action, context }) {
const granted = await hasGrant(subject.id, action, context["tenant"]);
return granted ? { outcome: "granted" } : { outcome: "denied" };
},
});Pass a type argument for typed references:
defineAuthorizer<Permission>({ ... }). The types come from the same
subpath:
| Type | What it is |
|---|---|
Authorizer<Ref> | The contract above |
AnyAuthorizer | An authorizer of any Ref, for code that stores or forwards one |
AuthorizationRequest | The request evaluate receives (see below) |
AuthorizationOutcome | What evaluate returns |
AuthorizationSubject | The request's subject |
AuthorizationResource | The request's resource |
AuthorizationContext | The typed part of the request's context |
AuthorizationChange | A write's current row and next values |
AuthorizerRuntime<V> | The versions cache and memo next to each request |
PermissionRef<A> | The reference type of authorizer A, string when A is not an authorizer |
An authorization library that ships an adapter can import every one of these
types, and the provider and policy types it fills, from the types-only
better-supabase/contract entry. It has no runtime code, so the adapter adds
nothing to the bundle by importing it.
The request
Each request follows the AuthZEN Authorization API 1.0 information model: a subject, an action, a resource and a context.
| Field | What it holds |
|---|---|
subject | The caller and its verified token claims, from the verified context only (see below) |
action | The permission reference |
resource | What is acted on: type, an optional id, properties, source and, for a write, change |
context | The fields in the next table |
Every context field is optional:
| Field | What it holds |
|---|---|
tenant | The request's tenant |
aal | The token's assurance level (aal1, aal2) |
scopes | The token's scope claim, split on spaces |
intent | read or write |
operation | The kind of call: get, list, create, update, delete, action, route or tool |
enforcement | How the guarded write is enforced: rls or definer (see Enforcement) |
requestId | The server's request id, the same for every check in one request scope |
approval | The approval id the client resumes with (see Approvals) |
A route is a read for GET and HEAD and a write for every other method. An
action is a write. An MCP tool is a read when its readOnlyHint annotation is
true. The client can send requestId (the x-request-id header) and
approval, so use them for logs, audit and matching an approval you issued,
never as a grant.
The subject's type is the actor kind (user or service), or agent for
a user token that carries an act claim (a delegated token). Its id is the
actor id, and its properties hold role, email and impersonator when
they are set, plus claims: a read-only copy of the verified access-token
claims, including what your token hook wrote (memberships, roles, the tenant
claim, attrs and act). A caller without a session is
{ type: "anon", id: "anonymous" }, with no properties and no claims.
Adapters read memberships and roles from subject.properties.claims, never
from resource.properties or context, which can carry caller input.
Nothing the client sends ends up in the subject.
| Where the permission is declared | resource |
|---|---|
| A resource operation | type is the table; id and the row as properties (the body for create) |
| A resource action | the table, plus the key and the row for an item action |
| An MCP tool | { type: "mcp_tool", id: <tool name>, properties: <arguments> } |
| A route guard | { type: "route" } |
| A server or block action | { type: "action", properties: <the validated input> } |
Trust the source
resource.source says where properties came from. loaded is a row
better-supabase read through the caller's client (get, update, delete,
and a resource loader's row). input is what the caller sent: the body of a
create, an action's input and an MCP tool's arguments. Decide from loaded
properties, and treat input ones as claims the caller makes, the same way
the conformance kit does.
A write also carries change. change.current is the stored row (absent for
a create), and change.next is the values the caller sends. For an
update, properties stays the loaded row, so a rule such as "only the
owner may move a project to another team" compares change.current.teamId
with change.next.teamId and checks the owner on properties:
import { defineAuthorizer } from "better-supabase/server";
export const authorizer = defineAuthorizer({
name: "projects",
key: (permission: string) => permission,
evaluate({ subject, resource }) {
const owner =
resource.source === "loaded" &&
resource.properties?.["ownerId"] === subject.id;
const moves =
resource.change?.next["teamId"] !== undefined &&
resource.change.next["teamId"] !== resource.change.current?.["teamId"];
return owner || !moves ? { outcome: "granted" } : { outcome: "denied" };
},
});Load the resource
A route or action that acts on one row can load that row first, so the
authorizer decides on its owner or team instead of on what the client sent.
Pass resource next to permission. It runs after the session and
requireTenant checks, and gets the validated input and the request's
context (db, session, tenant). Its return value replaces the default
resource:
import * as v from "valibot";
import { bsb } from "@/lib/supabase/server";
export const renameProject = bsb.action(
{
input: v.object({ id: v.string(), name: v.string() }),
permission: "projects.update",
resource: async ({ id }, { db }) => {
const project = await db.projects
.get(id, { select: ["id", "ownerId", "teamId"] })
.orThrow();
return {
type: "project",
id: project.id,
properties: { ownerId: project.ownerId, teamId: project.teamId },
};
},
},
({ id, name }, { db }) => db.projects.update(id, { name }),
);The authorizer then grants projects.update to the owner, or to a member of
the team, by comparing resource.properties with the subject's claims. A
loader that throws refuses the caller: a DbException (such as the
not_found from .orThrow()) keeps its error, and any other throw refuses
with forbidden and code: "RESOURCE_UNAVAILABLE". Without a permission,
the loader doesn't run.
Share work in a request
Every check in one request scope gets the same context.requestId and the
same runtime.memo. Load what several checks need (a user's grants in a
tenant, say) once through runtime.memo.once(key, load) instead of keying a
module-level cache on requestId: each use cache scope gets its own memo,
so nothing request-specific lives in module state.
Typed versions
A library that caches grants across requests passes its own version cache to
the server as versions. The type flows to the authorizer's runtime, so
runtime.versions is the library's cache with its own methods, not the
AuthzVersionCache the server needs (evict(userId) only):
import {
createServer,
defineAuthorizer,
type AuthorizerRuntime,
} from "better-supabase/server";
import { grantVersions } from "./grants";
const authorizer = defineAuthorizer({
name: "grants",
key: (permission: string) => permission,
async evaluate(request, runtime?: AuthorizerRuntime<typeof grantVersions>) {
const version = await runtime?.versions?.current(request.subject.id);
return decide(request, version);
},
});
export const bsb = createServer(betterSupabase, {
authorizer,
versions: grantVersions,
});createServer, createNext, createHono, createEdge and createMcp all
take versions and hand it to every decision. bsb.versions is typed the
same way.
Outcomes
evaluate returns one of three outcomes, each with an optional context:
| Outcome | Answer |
|---|---|
{ outcome: "granted" } | The request goes on |
{ outcome: "denied", reason? } | 403 with code: "PERMISSION_DENIED"; reason is the message |
{ outcome: "approval-required", approval? } | 403 with code: "APPROVAL_REQUIRED" and approval: { id } |
Both refusals are forbidden errors that carry the permission key in
permission, rendered as Problem Details.
Approvals
approval-required stops the call and returns the approval id. Once someone
approves it, the client sends the call again with the id, and better-supabase
puts it in context.approval so the authorizer can grant it. Name the header
the id travels in with the server's approval option:
const bsb = createHono(betterSupabase, {
authorizer,
approval: { header: "x-approval-id" },
});The id is read only when the option is set, must match
[A-Za-z0-9._:;,@/+=-] and be at most 256 characters, and is never part of
the subject. An MCP tool call that needs approval returns a tool error with
structuredContent: { code: "APPROVAL_REQUIRED", approval: { id } }. The
client resumes with _meta.approval on the next tools/call (or the header).
The tool stays in tools/list, since the caller may call it once approved.
Fail closed
Every way an answer can go wrong denies:
| Case | Error message |
|---|---|
| A permission is declared but no authorizer is set | A permission is declared, but no authorizer is set |
key() throws | Unknown permission |
evaluate throws or rejects | The authorizer failed for <key> |
evaluate returns anything but the three outcomes | The authorizer gave no decision for <key> |
All of them are PERMISSION_DENIED. A permission check never throws: the
operation returns the error as a Result, like every other database error.
When a resource lists rows, each row is checked (through evaluations when
the authorizer has it), and any failure leaves the row out.
Set the authorizer
Pass it once, where the server is created. Every resource, action, route guard and MCP tool of that server uses it:
import { createHono } from "better-supabase/hono";
import { authorizer } from "./lib/authorizer";
const bsb = createHono(betterSupabase, { authorizer });| Where | Option |
|---|---|
createServer (better-supabase/server) | authorizer |
createHono, createEdge, createNext, createMcp | authorizer |
| The standalone route guards (Express, Fastify, Koa, h3, Elysia, NestJS) | authorizer on the guard |
defineApi | authorizer, for the keys in the document |
Give defineApi the same authorizer so the document shows each operation's
permission key and its 403 response (see
Permissions in the document).
Read claims
better-supabase/claims reads the claims the token hook writes, from a
session, a session snapshot or plain claims, without a server. An adapter
uses it instead of hard-coding claim names:
import { permissionsOf } from "better-supabase/claims";
import type { SessionSnapshot } from "better-supabase/claims";
export function can(
snapshot: SessionSnapshot,
key: string,
tenant?: string,
): boolean | "pending" {
const keys = permissionsOf(snapshot.claims, tenant);
return keys === undefined ? "pending" : keys.includes(key);
}permissionsOf takes a server session, a client snapshot or plain claims,
and reads the active tenant from the tenant claim when you pass none. It
returns undefined when the token can't answer (no claim, no entry for the
tenant, or the hook's truncated marker is set), so the caller asks the
database. Pass truncatedClaim when the provider names its own marker. The
entry also exports the claim names (PERMISSIONS_CLAIM, MEMBERSHIPS_CLAIM,
FEATURES_CLAIM, AUTHZ_VERSION_CLAIM, PERMISSION_CAP_CLAIM,
PERMISSIONS_TRUNCATED_CLAIM), tenantOf, isTruncated,
decodeEntitlementClaim, permissionCapOf, and the isUserSession,
isApiKeySession and isSessionSnapshot guards.
Enforcement
context.enforcement says whether the database checks the write again. A
provider that reads its live authorization version before each write, so a
stale grant can't pass, may skip that read for rls:
| Value | Set by | What the database does |
|---|---|---|
rls | Repository create, update, delete and upsert through a caller's db | Runs the write as the caller, so RLS checks it again |
definer | Block verbs, and actions, routes or tools that declare it | A security definer function skips RLS: the check is the only gate |
| unset | Reads, actions, routes and tools without enforcement, and any admin db | Unknown: treat it as definer |
An action, a route (AuthorizeOptions), a resource action and an MCP tool
take enforcement on their definition. It stays unset by default, because the
library can't see what a handler calls: set rls only when the handler writes
through the caller's own client. A repository write through the admin client,
or a db with no actor, never carries rls. The field is additive on
apiVersion: 1, so an authorizer that ignores it behaves as before.
recordingAuthorizer from better-supabase/testing wraps an authorizer and
records each check's operation, intent and enforcement, so a test can
assert what a call site sent:
import { recordingAuthorizer, staticAuthorizer } from "better-supabase/testing";
const authorizer = recordingAuthorizer(
staticAuthorizer({ roles: { authenticated: ["notes.create"] } }),
);
// ...create a note through the caller's db, then:
expect(authorizer.checks.at(-1)).toMatchObject({
operation: "create",
enforcement: "rls",
});Test an authorizer
testAuthorizer from better-supabase/testing runs the conformance kit
against your adapter. It checks that the authorizer targets API v1 and has a
name, that key() returns a stable, non-empty string, that every answer is
one of the three outcomes and leaves the request unchanged, that
evaluations agrees with evaluate and keeps the order, that the decision
comes from the subject and never from a forged input (a role, claims or
memberships placed in the resource properties, a source: "input" resource,
its change, the context or enforcement: "rls"), and that an unknown
permission is never granted.
The kit builds its requests with authorizationRequest, so they carry the
intent, operation and requestId a server sends:
import { test } from "vitest";
import { testAuthorizer } from "better-supabase/testing";
import { authorizer } from "../src/lib/authorizer";
test("the authorizer conforms", async () => {
await testAuthorizer(authorizer, {
permissions: ["customers.read", "customers.delete"],
unknown: "nothing.here",
granted: { permission: "customers.read", context: adminContext },
});
});It resolves with the report, and rejects with a ConformanceError that
lists every failed check.
For your own tests, authorizationRequest and sessionSnapshot build the
shapes the server builds, through the same code:
import { expect, test } from "vitest";
import { authorizationRequest, sessionSnapshot } from "better-supabase/testing";
import { authorizer } from "../src/lib/authorizer";
const claims = {
sub: userId,
permissions: { [tenantId]: ["projects.update"] },
};
test("grants an update to a member with the key", async () => {
const request = authorizationRequest({
action: "projects.update",
claims,
resource: { type: "projects", id: "p1", source: "loaded" },
context: { tenant: tenantId, intent: "write", operation: "update" },
});
expect(await authorizer.evaluate(request)).toEqual({ outcome: "granted" });
});
test("reads the same claims from a snapshot", () => {
expect(sessionSnapshot({ claims }).userId).toBe(userId);
});For tests and examples that need an authorizer but not a library,
staticAuthorizer decides from the subject's role and id. See
Testing.
Last updated on