Supabase token hook
permdock supabase hook generate compiles the app's membership sources into one custom_access_token_hook, with the active scope first, a size budget, an authorization version for sensitive permissions, and protection for memberships the identity provider owns.
A Supabase app usually reads memberships in two places: the server asks its tables on every request, and the access token carries a copy so RLS and the browser do not have to. The two drift apart as soon as they are written by hand. permdock supabase hook generate removes the second copy of the logic: the app declares its membership sources once, passes them to getPermDock as memberships, and the generator compiles the same sources into the Custom Access Token Hook.
Sources
permdock/supabase exports two SQL membership sources. Each one runs a single parameterised select at runtime and hands the same select to the generator, so the claim the hook writes and the memberships the server reads come from identical SQL.
// src/memberships.ts
import {
junctionMembershipSource,
tableMembershipSource,
type SqlQuery,
} from "permdock/supabase";
const suspension = {
users: { table: "profiles", id: "id", disabledAt: "disabled_at" },
scopes: {
organization: {
table: "organizations",
id: "id",
disabledAt: "disabled_at",
},
},
};
export function sources(query?: SqlQuery) {
const shared = query === undefined ? { suspension } : { query, suspension };
return [
// one row per user, scope, instance and role
tableMembershipSource({
table: "memberships",
columns: {
via: "via",
expiresAt: "expires_at",
managedBy: "managed_by",
seats: "seats",
},
...shared,
}),
// portal contacts: every row is a customer membership with the fixed role `contact`
junctionMembershipSource({
table: "customer_contacts",
scope: "customer",
within: { organization: "organization_id" },
roles: ["contact"],
via: "contact",
...shared,
}),
];
}tableMembershipSource({ table, columns?, query?, suspension? })reads a table that holds every scope.columns.user,scope,idandroledefault touser_id,scope,scope_idandrole.columns.rolemay be a reference to a roles table, andcolumns.usera reference to a table that holds the user id (below).withinnames ajsonbcolumn of ancestor ids;via,expiresAt,disabledAt(a nullable timestamp that suspends the row: suspended memberships),managedBy(a text column whereidpmarks an IdP-owned row),seats(atext[]column) andx(ajsonbcolumn of app data, read intoMembership.xand never written into claims) are optional. Rows for the same instance, kind, expiry, owner, seats andxmerge into one membership with every role.junctionMembershipSource({ table, scope, roles, user?, id?, within?, via?, expiresAt?, disabledAt?, managedBy?, seats?, x?, query?, suspension? })reads a table of one scope.rolesis a role column, a reference to a roles table (below), or fixed roles (['contact']), so a contact table needs no role column.useris the user id column (defaultuser_id) or a reference to a table that holds the user id (below).iddefaults to<scope>_id,withinmaps each ancestor scope to its column,viais the kind every row has, andmanagedByis'idp'(every row) or{ column }.blockMembershipSource({ table?, scope?, columns?, roleThrough?, roles?, query?, suspension? })frompermdock/better-supabasereads better-supabase'smembershipsblock table: ajunctionMembershipSourceoverbetter_supabase.membershipswith scopeorganization,organization_id,user_id,roleanddisabled_at.columnstakes the block's logical names (tenant,user,role,disabledAt;disabledAt: nullfor none), as inblocks.memberships.columns.memberships.roleThroughis the value ofblocks.memberships.options.roleThrough({ table, id, column }), so a role column holding a roles table id reads the custom role's key.roles: { table, membership, role, id? }reads a junction with one row per role instead, for a member who holds several roles; it can't be combined withroleThrough.query(text, values)runs one statement:pg'sclient.queryandpostgres'ssql.unsafeboth fit. Without it a source only describes SQL, which is allpermdock.config.tsneeds.suspensionhas the shape ofrls.suspension: rows of a suspended user, instance or ancestor instance are left out, and a missing status row counts as suspended. A scope withkeepkeeps the rows of its suspended instances instead, each with akeepcolumn of the permission keys it still grants (permissions a suspended scope keeps); a source withoutkeepadds the column only next to one that has it. A row whosedisabledAtcolumn is set is a suspended membership: it is left out, or withsuspension.memberships.keepkept with the keys it still grants (suspended memberships).- Each source also implements
list({ scope, id }), which returns every member of one instance for member lists, share dialogs and access reviews.
A membership table that stores a role id reads the role key through the roles table, with the same { through, on, column } shape as global roles:
// organization_users (user_id, organization_id, role_id references roles (id))
// roles (id, scope, key, organization_id): built-in rows have no organization, custom rows have one
junctionMembershipSource({
table: "organization_users",
scope: "organization",
roles: { through: "roles", on: { role_id: "id" }, column: "key" },
via: "staff",
...shared,
});on maps a column of the membership table to the roles table column it references, and an unqualified through is in the membership table's schema. A role set keyed by several columns, such as better-supabase's membership_roles (organization_id, user_id, role), maps each one (on: { organization_id: "organization_id", user_id: "user_id" }); the join matches all of them, and the version trigger on the role set bumps the members it matches. A global role, a user through and rls.roles still take exactly one column. The hook, the in-process membershipsFor and list, and the database mode helpers all run the same select with the join, so a membership's roles hold keys. A tenant's custom role is a roles row with a key unique within the tenant; the membership carries that key and resolves as a custom role of its tenant. A tenant row keyed like a declared role (owner) holds that declared role, so keep the keys apart with a check constraint or the code that writes roles.
A membership row that holds roles in more than one column (a plan tier and a role id) lists them as role sources: tableMembershipSource columns.role takes an array, and junctionMembershipSource takes roles: { sources }, because an array of strings there is fixed roles.
// organization_users (user_id, organization_id, tier text, role_id references roles (id))
junctionMembershipSource({
table: "organization_users",
scope: "organization",
roles: {
sources: [
"tier",
{ through: "roles", on: { role_id: "id" }, column: "key" },
],
},
});The row holds every non-null key of its sources: a user with tier = 'member' and a role_id keyed admin gets roles: ["admin", "member"], and a row whose sources are all null holds no membership. The hook, membershipsFor, list and the database mode helpers expand the row with one cross join lateral, and a key rename on any referenced roles table bumps every holder's authorization version. Each source column is a deciding column, and the manifest lists the sources as an array under role.
A membership table whose rows name a profile instead of a login reads the user id through the profile table, with the same shape. CentraKit's portal contacts are customer_contacts (customer_id, organization_id, contact_profile_id), and the login is contact_profiles.user_id:
// contact_profiles (id, user_id references auth.users (id) on delete set null)
// customer_contacts (customer_id, organization_id, contact_profile_id references contact_profiles (id))
junctionMembershipSource({
table: "customer_contacts",
scope: "customer",
id: "customer_id",
within: { organization: "organization_id" },
user: {
through: "contact_profiles",
on: { contact_profile_id: "id" },
column: "user_id",
},
roles: ["customer"],
via: "contact",
...shared,
});The select joins the profile table and filters on its user column, so a row whose profile is missing or has no user_id holds no membership, and suspension.users checks the joined user id. A source may read both its user and its role through other tables. The hook declares the lookup variable with the profile column's type, so its index applies; rls generate indexes the profile's user column and the reference.
A source's deciding columns (the user, scope, id, within, role, via and expiry columns, the id and key columns of a roles table its role references, and the id and user columns of a table its user references) must not be client-writable, or a user can give themselves a membership: a portal contact who may edit their own customer_contacts row could set user_id on another row, or customer_id on their own. Revoke insert and update on the table from anon and authenticated and grant update back only on the columns clients edit:
revoke insert, update on public.customer_contacts from anon, authenticated;
grant update (name, phone) on public.customer_contacts to authenticated;A column-level revoke update (user_id) alone is not enough: Postgres keeps a table-level update grant (Supabase's default privileges give one on every public table), and has_column_privilege still answers true. Doctor PD028 warns on each deciding column the migrations leave writable.
On the server, pass the sources as an array. getPermDock composes them with composeMemberships: memberships are merged and de-duplicated, entries that differ in via, expiry, owner or seats stay separate, and a source that throws makes the whole lookup fail closed.
import { claimsFirst, getPermDock } from "permdock";
import { authzVersion, subjectFromSupabase } from "permdock/supabase";
const query: SqlQuery = async (text, values) =>
(await pool.query(text, [...values])).rows;
const memberships = claimsFirst(sources(query), {
version: authzVersion({ query }),
});
const { data } = await supabase.auth.getClaims();
const permdock = await getPermDock(
policy,
subjectFromSupabase(data?.claims ?? null),
{ memberships },
);claimsFirst(sources, { version?, onStale? }) keeps the memberships the verified token carries and reads the sources only when the token says it dropped some (memberships_truncated), or, with onStale: 'reread', when the token's authz_ver is behind the version table (one version read, then one memberships read only when the token is behind). versions: memoryVersionCache({ maxStaleMs }) shares that version read across instances (freshness and the version cache). Staleness applies only to permissions the policy marks fresh: with the default onStale: 'deny' every other permission keeps the token's claims, and only 'reread' replaces the claims for every decision. A reread replaces principal.roles as well when the source has globalRolesFor (postgrestSources().memberships has it), so a revoked platform role is lost with the memberships; actor, delegation, session and the token's other claims stay on the subject. Without claimsFirst, a memberships source is always read and the token's copy is ignored. getPermDock in permdock/next takes the same memberships option.
A stored user over PostgREST
The sources above run SQL through SqlQuery. A backend that reaches Postgres only through supabase-js reads the same answers from subject_for(p_user uuid) returns jsonb, which the hook file defines next to the hook: the global roles, the memberships of every source with their expiry and suspension filters, the authorization version, and in database mode with rls.customRoles the custom roles the user holds with their grants and includes. A suspended user comes back as { id, active: false }, an unknown one as null. execute is revoked from public, anon and authenticated, because the caller names the user; grant it to the role your backend client uses. The hook file also defines members_of(p_scope text, p_id text) returns jsonb: every live membership of one scope instance as [{ principal: { id }, membership }], from the same sources with the same expiry and suspension filters, under the same grants. It also defines subject_for(p_user uuid, p_tenant <tenant type>) returns jsonb, the same record cut down to one tenant (see One tenant's subject). It also defines authz_version_for(p_user uuid) returns bigint: the authorization version subject_for reports, null for an unknown or suspended user, read without the roles and memberships. The hook and subject_for read their rows from two shared functions in the hook schema: memberships_for(p_user uuid) returns table(ord integer, entry jsonb), a security definer reader, for the membership entries of every source (with a second form, memberships_for(p_user uuid, p_tenant text), that keeps one tenant's entries inside each source's read), and global_roles_for(p_user uuid) returns jsonb for the global roles (not written with roles: false). Each is revoked from public, anon and authenticated; an invoker hook gets execute for supabase_auth_admin, and a security: 'definer' hook calls them as its owner. A membership source is therefore written once per file, and hook.budget still applies in the hook's loop over the entries.
The Data API serves only exposed schemas, and permdock is not one. Set supabase.hook.api and hook generate writes a wrapper for each reader in an exposed schema:
supabase: {
hook: {
memberships: [/* ... */],
api: { schema: "public", prefix: "permdock_" }, // both are the defaults
},
},That writes public.permdock_subject_for(p_user uuid), public.permdock_subject_for(p_user uuid, p_tenant <tenant type>), public.permdock_members_of(p_scope text, p_id text) and public.permdock_authz_version_for(p_user uuid). Each is a security invoker function with an empty search_path that calls the function in the hook schema, revoked from public, anon and authenticated and granted to service_role. The security definer readers stay in the permdock schema, which the Data API does not expose, so the API schema holds no definer function and a catalog test that forbids them passes without an allow-list. To let service_role reach them, hook generate also grants it usage on the hook schema and execute on each reader: the only grants the hook makes to service_role, and only with api. The trade-off: a role that can execute a wrapper needs the grant on the inner function too, so granting a wrapper to another role means granting the reader. Without api, no wrapper is written and nothing is granted to service_role. generate refuses an api that would replace the function it wraps (the hook schema with an empty prefix).
postgrestSources(client, { api?, schema?, fn?, membersFn?, versionFn?, policy?, onSourceCall?, subjects?, tenantScoped? }) in permdock/supabase returns the three inputs createPermDock takes. It keeps no answers, so create it once at module scope and share it across requests, cache scopes and workers. Within one instance, getPermDock shares each call: subject_for runs at most once per user, whether membershipsFor, globalRolesFor or a custom-role read asks for it, and the next instance reads again. sources.memberships.version calls authz_version_for (or the record already read), so claimsFirst(sources.memberships, { onStale: "reread" }) checks the token's freshness with one cheap call per request and reads subject_for only when the token is behind. When the version function does not exist, version throws and the check denies; permdock doctor PD083 reports a hook file without it, and permdock supabase hook generate writes it. Pass policy when the app has custom roles: customRoles then reads nothing while every role the subject holds is declared, and version calls subject_for instead of authz_version_for when the token claims a role the policy does not declare, because the custom roles need that record anyway. A current token with only declared roles costs one version call; a custom-role token costs one subject_for call, fresh or stale. sources.memberships.list(query) is the member list countHolders and whoCan read, so a role change can pass the holders decideRoleChange needs:
import { claimsFirst, countHolders, getPermDock } from "permdock";
import { postgrestSources, subjectFromSupabase } from "permdock/supabase";
// module scope: created once per process
const sources = postgrestSources(admin, {
api: { schema: "public", prefix: "permdock_" }, // the supabase.hook.api setting
policy,
});
const memberships = claimsFirst(sources.memberships);
// a request: the token's memberships, the database's when it was truncated
const subject = subjectFromSupabase(claims);
const permdock = await getPermDock(policy, subject, {
memberships,
...(subject.principal === null
? {}
: { customRoles: sources.customRoles(subject.principal) }),
});
// a job acting for a stored user
const actor = await getPermDock(policy, await sources.subject(userId), {
customRoles: sources.customRoles({ id: userId }),
});
// the holders a role change counts
const holders = await countHolders(sources.memberships, {
scope: "organization",
id: organizationId,
role: roles.owner,
});api sets the defaults of schema, fn, membersFn and versionFn to the wrappers supabase.hook.api writes; any of the four still overrides it. Without api they default to the hook schema's own functions, for a client that can reach it. sources.memberships answers membershipsFor and version, so claimsFirst freshness works without a SqlQuery. sources.customRoles(principal) returns the custom roles that principal holds; a role-management page that needs every role of a tenant composes customRoleSource over its own read. sources.subject(userId) is the anonymous subject for a suspended or unknown user, and a failed call rejects, which createPermDock turns into a denial.
One tenant's subject
subject_for(p_user uuid, p_tenant <tenant type>) returns jsonb answers what subject_for(p_user) answers, restricted to the tenant p_tenant (the type of the first scope's id: uuid by default, rls.scopeTypes otherwise). A backend that acts for a user inside one organisation reads that organisation's rows instead of every organisation the user belongs to.
| Field | In the record |
|---|---|
memberships | The entries of p_tenant only: a membership of the tenant scope or of a scope inside it, with the same expiry and suspension filters as the one-argument form. |
roles | The user's global roles, unchanged. |
customRoles | The roles a kept membership holds that are pinned to p_tenant or shared, and the platform roles among the global roles. A tenant role of another tenant never appears. |
customRolesVersions | The version of p_tenant alone, when a held role is a custom one. |
claims.team_ids | The user's teams in p_tenant, when the user has a membership there and supabase.hook.teams names a tenant column; absent otherwise. |
authzVersion, active, other claims | The user's, unchanged. |
The function fails closed. An unknown tenant, a tenant the user holds no membership in, a tenant that is suspended and a null p_tenant return the record with memberships: [], never another tenant's rows. A suspended user comes back as { id, active: false } and an unknown user as null, as with subject_for(p_user). The function is security definer with an empty search_path, never grants service_role, and has execute revoked from public, anon and authenticated. hook.api writes the wrapper <prefix>subject_for with the extra p_tenant argument.
One tenant over PostgREST
postgrestSources(client, { tenantScoped: true }) reads the memberships of the instance's tenant through subject_for(p_user, p_tenant) instead of every tenant's through subject_for(p_user), so a user in 11 organisations loads one. The tenant is the tenant option of getPermDock (or the adapter's equivalent), which your server code sets from the verified session or claims; never pass one taken from a header, query string or body.
- An instance with no
tenant, or an empty one, reads no memberships and makes no call. The source never falls back to the all-tenants read. - A failing call rejects, so
getPermDockreportssource-threwand the subject has no memberships. - A tenant the user holds nothing in answers no memberships, so every permission there is denied.
customRoles(principal).rolesFor(tenant)reads that tenant's record.globalRoles,sharedRoles,subject,refresh,recordandmemberships.globalRolesForstill read the whole user.- The instance memo and a
memorySubjectCachekey the record by user and tenant, andevict(id)drops every tenant's record. A customSubjectCachethat ignores thetenantargument is never served another tenant's record, because the source discards a record whosetenantdiffers; it only misses. - The custom-role version is per tenant, so a scoped record carries the version of its tenant alone.
The generated SQL does not change: the two-argument function already exists after permdock generate --only rls or permdock supabase hook generate, and no data migration is needed.
<helpers schema>.permdock_subject() is subject_for for the signed-in user: security definer, stable, executable by authenticated only, and null for an anonymous or suspended caller. A backend that holds the user's JWT calls it once and passes the record to permdockFor as the bootstrap subject (better-supabase); it cannot name another user.
subject_for also returns a claims object with the team_ids the hook would write (every team, with no budget) and each supabase.hook.claims entry, and sources.subject(id) and sources.refresh(subject) put them on principal.claims. A stale path therefore keeps team-scoped levels without the caller merging the claims back.
sources.refresh(subject) rereads the principal of a token subject you already hold: roles, memberships and authzVersion come from subject_for, while actor, delegation, session, expiresAt, the context and the token's other claims are kept. Use it where sources.subject(id) would drop an OAuth client's actor and delegation and lift its ceiling. A user that is unknown or suspended becomes a subject with no principal that still carries the actor and delegation.
Generate
// permdock.config.ts
import { sources } from "./src/memberships.ts";
export default defineConfig({
policy: "./src/policy.ts",
supabase: {
hook: {
memberships: sources(),
attrs: {
table: "profiles",
columns: ["region", "clearance", "app_metadata.regions"],
},
},
},
});permdock supabase hook generate --out supabase/migrations/20260929_permdock_hook.sql
permdock supabase hook generate --active-from profiles.active_organization_id --budget 2048
permdock supabase hook generate --checkThe output is one idempotent migration:
custom_access_token_hook(event jsonb),stable,search_path = '', which writes:roles(every global role) anduser_role(a string for one role, an array for several; absent for none, soapp_metadatastill applies) fromsupabase.hook.roles, by defaultrls.roles, else<schema>.user_roles (user_id, role). Aroleof{ through: 'roles', on: { role_id: 'id' }, column: 'key' }reads the key through a roles table, which also gets the auth-admin read. Whenrls.customRoleWrites.rolesnames that table with atenantcolumn, only its rows without a tenant are global roles;memberships: aunion allover every source, in the canonical{ scope, id, within?, roles, via?, expires_at?, managed_by?, entitlements?, keep? }claim form,expires_atin NumericDate seconds;- the active tenant claim (
rls.tenantClaim, defaulttenant_id), whenever the user holds a membership in it, also when the budget left that membership out ofmemberships. The generated RLS helpers narrow to it unlessrls.tenantsis'all'(active tenant). The active first-scope id comes fromapp_metadata.active_<first scope>by default, or in a project with abetter-supabase.config.*from the claim better-supabase writes (auth.tenant.claim, thenrls.tenantClaim, thentenant_id);--active-from(orsupabase.hook.activeFrom) takesapp_metadata.<key>,<table>.<column>joined onid, or{ table, id, column };supabase.hook.activeTenant: "request"records in the manifest that the app resolves the tenant per request, which silences doctor PD078 and better-supabase's BS409 (PD078); attrs: the allow-listed attribute columns andapp_metadatakeys (below), never other columns;authz_ver: the user's authorization version (below);custom_roles_ver: the custom-role version of the active tenant, whenrls.customRoleskeeps the roles in thepermdocktables (databasemode). The hook reads it withcustom_roles_version_for(active tenant); the claim is absent without an active tenant or injwtmode;- the claims other packages own, from
supabase.hook.claims(below).
- The
supabase_auth_admingrants:usageon the schema,executeon the hook and on itssecurity definerreaders (memberships_for(p_user),global_roles_for(p_user)and the team reader), andselectwith a read policy on the tables the hook body reads itself: theattrstable, the suspended-user table and the version table. The membership sources, their suspension tables, global roles and every roles or user table athroughreferences are read inside the readers, so they get no grant.memberships_fordrops a suspended user's entries and the entries in a suspended tenant (rls.suspension.scopes.<root scope>) for every source, keeping those that carry the tenant's kept keys.executeis revoked fromauthenticated,anonandpublic, and so is every privilege on eachsupabase.hook.claimsandsupabase.hook.beforefunction, which returns any user's claims for the user id or event it is given. Nothing is granted toservice_role, except to thesupabase.hook.apiwrappers when you set it. - With
supabase.hook.security: "definer", the hook issecurity definerand reads with the rights of the role that applies the migration (postgreson Supabase).supabase_auth_adminthen getsusageon the hook schema andexecuteon the hook only: noselectand no read policies. Thehook.claimsandhook.beforefunctions are still revoked from the client roles, and the hook calls them as its owner. Pick it when a table the hook reads is owned elsewhere and cannot take a read policy forsupabase_auth_admin. The default"invoker"keeps the hook's reads to the tables the grants name. Doctor PD085 runs the hook assupabase_auth_adminagainst a database in either mode. permdock_authz_version (user_id, version)and thepermdock_bump_authz_versionfunction, run by three statement triggers (_insert,_update,_delete, with transition tables) on every source table and the global-roles table: a statement bumps each affected user once, however many rows it changes, and the version table's own statement triggers send one broadcast per bumped user. Withthroughon the global roles or on a source,permdock_bump_authz_version_role_keyson each referenced roles table bumps every user who holds a renamed role, globally or through a membership, when its key or id changes, since a rename changes theirrolesandmembershipsclaims. A source that reads its user through another table getspermdock_bump_authz_version_member_usersinstead, which bumps the users its old and new rows reference, and the referenced table getspermdock_bump_authz_version_linked_userson updates of its user and id columns and on delete, which bumps both the old and the new user when a profile is re-linked to another login. That trigger skips a login that no longer exists inauth.users, so deleting a user whose profile is set tonullstill succeeds.permdock_bump_authz_version_for(p_users uuid[]), which bumps each listed user once, for membership data the hook does not read (below).- The
permdock_protect_managedtrigger on sources withmanagedBy. - The
config.tomlblock, printed and repeated as a comment:
[auth]
jwt_expiry = 900
[auth.hook.custom_access_token]
enabled = true
uri = "pg-functions://postgres/public/custom_access_token_hook"jwt_expiry = 900 bounds how long a demotion can take to reach a token: 15 minutes, set with supabase.hook.jwtExpiry. The command refuses a source whose scope the policy does not declare, a single-scope source without a within column for every ancestor (such a membership grants nothing), a non-positive budget and unsafe identifiers.
Hosted rollout
config.toml configures the local stack and a branch. A hosted project takes the same settings from the Management API, and the order matters.
- Apply the migration that creates
custom_access_token_hookand its grants. Auth calls the function as soon as the hook is enabled; a missing function makes every sign-in fail. - Set the hook on the project:
hook_custom_access_token_enabledtotrue,hook_custom_access_token_uritopg-functions://postgres/<schema>/custom_access_token_hook, andjwt_expto the lifetime[auth] jwt_expirysets.permdock supabase inspectprints all three undermanagementApi, so the values to send come from the same run that wrote the SQL. - Check a freshly issued token for
memberships,rolesandauthz_ver. Tokens issued before the change keep their old claims until they expire.
Supabase branching reapplies config.toml on every push, so a branch whose [auth.hook.custom_access_token] table is missing or disabled loses the hook. Doctor PD074 reports a config.toml that does not enable the generated function.
Declarative schemas
hook generate writes for Declarative Schemas 2.0 (pg-delta) unless the project opts out with [experimental.pgdelta] enabled = false, supabase.schemas or --schemas (schema workflow). pg-delta's supabase db schema declarative sync keeps grants and policies, so the hook file keeps its grants. Without --out, hook generate writes it to supabase/schemas/<schema>/functions/custom_access_token_hook.sql, under declarative_schema_path when that is set. supabase/config.toml needs [experimental.pgdelta] with enabled = true, or the Supabase CLI diffs the file with migra; doctor PD068 fails until it does.
permdock supabase hook generate
supabase db schema declarative sync --no-apply -f permdock_hookA project on Declarative Schemas 1.0 (--schemas migra), which writes migrations with supabase db diff, cannot keep every privilege in the hook file: db diff drops schema and function privileges, so the hook would land executable by public and not by the auth server. --grants-out moves those statements to a migration of their own and leaves a comment in the hook file that says where they went:
permdock supabase hook generate --schemas migra --out supabase/schemas/identity/056_permdock_hook.sql --grants-out -
supabase db diff -f permdock_hook
supabase migration new permdock_hook_grants
permdock supabase hook generate --schemas migra --out supabase/schemas/identity/056_permdock_hook.sql \
--grants-out supabase/migrations/<timestamp>_permdock_hook_grants.sqlThe grants file starts with -- permdock:grants v1 schema=<schema> and holds usage on each schema the hook reads, execute on the hook and on each supabase.hook.claims and supabase.hook.before function, the revokes on the hook and on those functions from authenticated, anon and public, the revokes on the version and protection trigger functions, and the revoke on the hook schema from public. The select grants and permdock_auth_admin_read_* policies on the tables the hook reads stay in the hook file, because db diff diffs table privileges and policies and would drop them from a migration that held them. --check compares both files. permdock rls generate --split helpers,policies,hook writes the hook as one part next to the helpers and policies and takes the same --grants-out under migra (migra). Doctor PD042 errors while no migration from the one that creates the hook on carries the grants. A project without declarative schemas (--schemas migrations) gets supabase/permdock-hook.sql by default and keeps the grants in it.
Attributes
supabase.hook.attrs fills the attrs claim that attribute conditions read: where: { region: principal.claims.attrs.region } compiles to region = ((select auth.jwt()) -> 'attrs' ->> 'region') in RLS and reads principal.claims.attrs.region from subjectFromSupabase in the app, from the same claim.
attrs: {
table: 'profiles', // joined on `id` (set `id` for another column)
columns: ['region', 'clearance', 'app_metadata.regions'],
}- A plain entry is a column of
table;app_metadata.<key>readsauth.users.raw_app_meta_data, which only the server writes. Each entry's last segment is the claim key, and must match^[A-Za-z_][A-Za-z0-9_]*$so a nested ref can name it. - Only server-owned values may become attributes.
generaterefusesuser_metadataandraw_user_meta_datain any form,auth.usersas the table (useapp_metadata.<key>), prototype keys and a key named twice. - The migration starts with a guard: when
anonorauthenticatedcan insert or update any listed column (has_column_privilege, which counts table-level andpublicgrants), it raises42501and installs nothing. Grant clients column-levelupdateon other columns only.permdock doctorPD028 reports the same from your migrations, before you run them. - The hook drops any
attrsthe incoming claims carry and writes its own, so an attribute is never whatever the client sent.
Teams
supabase.hook.teams fills the team_ids claim, the uuid of every team the user belongs to, for a policy or an Edge Function that filters by team without a join:
teams: {
table: 'team_members', // user and team columns of one table
user: 'user_id',
team: 'team_id',
tenant: 'organization_id', // optional: the active tenant's teams come first
}- The claim shares the
membershipsbudget (size budget). The hook adds the teams after the memberships it kept. When the whole list would exceed the budget it writes noteam_idsand setsteam_ids_truncated: true: the claim is never a prefix, and team rows never setmemberships_truncated. - A suspended user gets no
team_ids, and the hook drops anyteam_idsthe incoming claims carry. team_idsis reserved:hook.claimscannot name it.supabase-claims-v1.jsonandSupabaseClaimstype it as an array of strings.member_team_ids_for(p_user uuid, p_active text default null)reads the table,security definer, executable bysupabase_auth_adminonly; a row withdisabledAtset is no team, and withtenanta suspended tenant's teams are left out. Ateamorteamsscope'smember_<scope>_ids_fortakes the same arguments, and the hook calls it instead.- The table's
user,team,tenantanddisabledAtcolumns are deciding columns in the manifest. A client role that can write the table can choose its ownteam_ids, so revoke insert and update on it. - Without a
teamorteamsscope that has membership sources, the hook file also writesmember_team_ids_of(p_user uuid) returns setof uuidin therls.schemafrom the same table. It answers only for the caller, skips a suspended user, andauthenticatedmay execute it; better-supabase'steamIdsOfcalls it. Theteamcolumn is auuid.
Suspended tenants
A user whose tenant is suspended (rls.suspension.scopes.<root>, without keep) has no entry for it in memberships, the same as a user who was never a member. With rls.suspension.scopes.<root> set the hook also writes suspended_in: the ids of the tenants where the user holds a membership and the tenant is suspended, sorted, at most 16, outside the memberships budget. It is absent when there are none.
subjectFromSupabasereads it asprincipal.suspendedIn.permdock_subject()andpermdock_subject(p_tenant)return it assuspendedIn. For a tenant, a user with no membership who is suspended there gets the record withmemberships: []andsuspendedIn: [tenant]instead ofnull; a user who was never a member still getsnull.suspended_in_for(p_user uuid) returns jsonbis the reader behind both, granted tosupabase_auth_adminonly.- RLS is unchanged: the user holds no membership there, so every policy denies.
suspendedInonly lets the application show "your organisation is suspended" instead of "not a member". - A membership the source itself drops because of its own
suspensionoption is invisible to the function. Put the suspension inrls.suspension.scopes.<root>and leave it off the source. - A token refresh that reuses its claims keeps the
suspended_init holds untilauthz_vermoves. - A tenant beyond the 16th says nothing:
suspendedInis not a proof of absence.
Claims other packages own
supabase.hook.claims adds claims PermDock does not own to the one hook Supabase allows, for example per-tenant plan features from a billing module. PermDock owns the hook and the claims the SQL helpers read; the other package owns its claim and the function that computes it (better-supabase shows one such split):
supabase: {
hook: {
memberships: sources(),
claims: { features: 'public.feature_claims' },
},
}-
Each value is a schema-qualified function
(user_id uuid) returns jsonb; the hook runs withsearch_path = '', so an unqualified name is refused. The hook sets the claim to the result, and anullresult leaves the claim out. -
A name PermDock or Supabase Auth writes is refused:
roles,user_role,memberships,memberships_truncated,suspended_in,attrs,authz_ver, the tenant claim, andsub,aud,role,exp,iat,iss,aal,amr,session_id,is_anonymous,email,phone,app_metadata,user_metadata. -
The hook drops each named claim from the incoming claims before it calls the function, so the value is always the function's.
-
The claims sit outside the size budget: the budget decides which memberships a token keeps, and a claim the hook cannot size must not push memberships out. Keep each one small; the function owns its size.
-
A suspended user gets none of them, and the function is not called. A user with no memberships still gets them.
-
The migration grants
supabase_auth_adminusageon each function's schema andexecuteon the function, afterrevoke all on function <fn>(uuid) from public, anon, authenticated: the function returns the claims of any user id it is passed, so no client role may call it. An app that also calls one from the client grants it again in its own migration, after the hook's. Doctor PD049 warns while a client role can execute one. A function that raises makes the hook fail, so Supabase Auth issues no token. -
A function that needs the user's memberships calls
<schema>.member_<scope>_ids_for(user_id)instead of reading the membership tables itself, so it agrees with the hook and RLS about expiry and suspension:create function public.feature_claims(user_id uuid) returns jsonb language sql stable as $$ select jsonb_object_agg(f.organization_id, f.features) from public.organization_features f where f.organization_id in (select permdock.member_organization_ids_for(user_id)) $$;permdock rls generatewrites these helpers (SQL helper contract); withsupabase.hook.claimsset, the hook migration (or the--grants-outfile) grantssupabase_auth_adminexecuteon each, so apply the helpers migration first.Why. Auth runs the hook as
supabase_auth_adminbefore a token exists, soauth.uid()andauth.jwt()are empty andmember_<scope>_ids()returns nothing. A copy of the membership query in each package drifts from the hook's as soon as a source gains expiry or suspension; one helper that takes the user keeps a single rule. The grant only exists withhook.claims, so a hook with no claims of its own still installs before the helpers.
Checks before the hook
supabase.hook.before runs checks of your own, or of another package, inside the one hook Supabase allows, before PermDock computes any claim. A typical check refuses a password sign-in for a user whose email domain enforces single sign-on, or a sign-in to a locked account:
supabase: {
hook: {
memberships: sources(),
before: 'auth_checks.require_sso', // or a list, run in order
},
}create function auth_checks.require_sso(event jsonb) returns jsonb
language plpgsql stable as $$
begin
if auth_checks.sso_required(event ->> 'user_id')
and event ->> 'authentication_method' is distinct from 'sso/saml' then
return jsonb_build_object('error', jsonb_build_object(
'http_code', 403, 'message', 'Sign in with single sign-on'));
end if;
return event;
end;
$$;- Each entry is a schema-qualified function
(event jsonb) returns jsonb; the hook runs withsearch_path = '', so an unqualified name is refused. - The hook calls each one first, in order, with the event it received. A result with an
errorkey is returned as it is, so Supabase Auth refuses the token with that status and message, and no later function and no PermDock claim runs. Anullor non-object result is refused the same way, with status 500 and<function> returned no event. - Otherwise the result is the event the hook continues with, so a check may also change incoming claims. PermDock still drops and writes the claims it owns afterwards, so a check cannot set
roles,membershipsor the tenant claim. - The migration (or the
--grants-outfile) grantssupabase_auth_adminusageon each function's schema andexecuteon the function, afterrevoke all on function <fn>(jsonb) from public, anon, authenticated, so no client role can call a check with an event it made up. Doctor PD049 warns while a client role can execute one. Grantsupabase_auth_adminwhatever the function reads. permdock supabase inspectlists the functions ashook.beforein the manifest.
Why. Supabase Auth calls one access token hook. A package that has to refuse a sign-in, such as single sign-on enforcement, would otherwise need its own hook and lose PermDock's claims, or ask the application to hand-edit the generated function on every regeneration. A check that runs first and can only refuse or pass the event keeps one hook and leaves the claims PermDock owns to PermDock.
Claim validation
supabase.hook.validate: true makes the hook check its own claims against supabase-claims-v1.json with pg_jsonschema, as the last step before it returns:
if not extensions.jsonb_matches_schema('<permdockClaims>'::json, claims) then
claims := claims - 'user_role' - 'roles' - 'memberships' - 'memberships_truncated' - 'attrs' - 'authz_ver' - 'tenant_id';
end if;- The schema is the
permdockClaimsdefinition with itsmembershipentries,keepincluded. - On a mismatch the hook drops every claim it owns and returns the event. The user signs in with no roles or memberships, so every PermDock check denies; sign-in itself does not fail.
- A mismatch comes from data the hook did not produce, such as an incoming tenant claim of the wrong type that no active tenant replaced.
hook.claimsentries belong to other packages and stay. - The migration runs
create extension if not exists pg_jsonschema with schema extensionsand grantssupabase_auth_adminusageonextensionsandexecuteonextensions.jsonb_matches_schema(json, jsonb). - Off by default: the check costs one schema compile per token.
Why. A token whose PermDock claims break the schema would fail later, in every reader at once. Dropping them at the source turns that into a sign-in with no access, which is the fail-closed outcome, and keeps a bad row from locking a user out with an Auth error.
Token shape
The hook receives the claims Supabase Auth built and returns them with PermDock's added. Auth rejects the token when the hook drops a required claim, so the hook only adds and removes its own keys: iss, aud, exp, iat, sub, role, aal, session_id, email, phone and is_anonymous come back unchanged, for a suspended user and after truncation too (tests/integration/src/hook-token-shape.test.ts asserts each). supabase.hook.claims cannot name any claim Supabase Auth or its OAuth server issues (jti, nbf, acr, act, client_id, scope and the ones above), nor custom_roles_ver, and the config check fails when one does (JWT fields).
- A token holds only claims that stay true until
exp. Anything that changes sooner, such as a role edit, travels asauthz_verand is checked against the version table, so a stale token cannot outlive a revocation. user_metadatais writable by the signed-in user and must never carry authorization data. Membership claims belong inapp_metadataor in the claims the hook adds.- The Postgres hook has 2 seconds and an HTTP hook 5 seconds with a 20 KB payload. Supabase does not retry a hook that errors, and the hook runs in the sign-in transaction. The hook is granted to
supabase_auth_adminand revoked fromanon,authenticatedandpublic; Supabase advises againstsecurity definer(custom access token hook, auth hooks). The same test mints the token of a user with 500 memberships and asserts the slowest of seven runs stays under 2 seconds. permdock claims sizeand doctor PD110 measure a token as an OAuth sign-in produces it: a long email, theuser_metadataa social provider writes and an OAuthclient_id.- Verify tokens against the project's asymmetric signing key. A project on the legacy HS256 secret can verify only with the secret or by calling
GET /auth/v1/user; doctor PD113 warns about the secret (signing keys).
Size budget
The hook writes memberships in a compact form: an object whose s, r and v list the scopes, roles and via labels the entries use, and whose e holds one [scope index, id, via index, ...role indexes] row per plain entry. A UUID id is its 22 character base64url form, any other id is = and the text. An entry with more than a scope, an id, roles and a via (within, grants, expires_at, …) stays an object in o. subjectFromSupabase, readMemberships, the jwt-mode authorize and the claims-first permdock_token_current() read both this form and the older array. On the CentraKit policy (UUID ids, via: "staff", one role) the 1,024-byte budget keeps 9 memberships as an array and 25 in the compact form; with two roles, 8 and 23 (permdock claims size reports both). Tokens issued before the upgrade carry the array and keep working until they expire.
Claims travel in the session cookie and on every request. The budget, supabaseMembershipsBudget bytes of JSON (1024 by default, measured with octet_length; set with --budget or supabase.hook.budget), covers the roles, user_role, attrs, authz_ver, memberships, team_ids and tenant claims together. The hook reads the roles, the memberships, the teams and the authorization version in one statement, so the roles, user_role (one role, or the list again), the tenant claim, the custom-role version and the version count first and the memberships and teams share what is left. attrs is sized next: when it alone exceeds the budget it is left out whole and memberships_truncated: true is set, so attribute conditions deny rather than read half an object. The hook then adds memberships in order, the active tenant's first, then source order, and stops before the two together would exceed the budget, again setting memberships_truncated: true.
The generated hook writes no grants on a membership and no permission key anywhere, so custom roles resolve only in database mode, from the tables; a jwt-mode project that stores custom roles in the token has to write grants from its own hook.claims function.
Measured with tests/integration/src/hook-token-shape.test.ts (base64url of the header and the claims plus a 64-byte signature, with a typical Supabase Auth payload), the whole token is 1,128 characters for one membership and at most 2,154 for 12 to 500 memberships with 1 to 20 roles each, at the 1024-byte default. The test asserts 4,096 as the ceiling. A larger budget adds its excess to that.
subjectFromSupabase surfaces the flag as principal.membershipsTruncated. With claimsFirst, the subject then reads every membership from the sources, so a user in 40 organizations still gets all 40 on the server while the token stays small. RLS in jwt mode only sees the kept entries; use database mode (RLS) when members routinely exceed the budget.
supabase.hook.membershipsClaim: false writes memberships as [] and sets memberships_truncated: true for a user who holds a membership, so every reader takes the subject from the database (permdock_subject(), subject_for or a claimsFirst source). The tenant claim, team_ids, roles and authz_ver are written as before. No refresh reuses the incoming claims, and an explicit refresh: 'reuse' fails generate. It needs rls.authorize: 'database': in jwt mode the RLS helpers read the claim, so generate exits 2.
In database mode the claim saves no time in SQL. tests/integration/src/claims-branch-bench.test.ts (run with PERMDOCK_CLAIMS_BENCH=1; results in tests/integration/claims-branch.json) times permitted_<scope>_ids(key) on Postgres 16 with a current token, which takes the claims branch, and with the same token marked truncated, which takes the table branch. The table branch was as fast or faster at every size:
| Memberships | rls.memo | Claims branch, mean / p95 | Table branch, mean / p95 |
|---|---|---|---|
| 1 | none | 0.417 / 0.602 ms | 0.406 / 0.583 ms |
| 8 | none | 0.495 / 0.614 ms | 0.457 / 0.578 ms |
| 11 | none | 0.728 / 0.983 ms | 0.673 / 0.902 ms |
| 1 | permdock | 0.219 / 0.319 ms | 0.209 / 0.333 ms |
| 8 | permdock | 0.329 / 0.410 ms | 0.281 / 0.355 ms |
| 11 | permdock | 0.386 / 0.467 ms | 0.335 / 0.417 ms |
The claim pays off in process: claimsFirst builds the subject from it without a database read. membershipsClaim: false makes every user's token truncated, so every instance rereads memberships, one PostgREST round trip (1.33 ms mean in scripts/authz-latency.json). That is why the default stays true. Set it to false when users routinely hold more memberships than the budget keeps, or when the server reads memberships through an instance cache. The helpers read the claims only when the hook keeps no suspension of its own and every scope's rls.memberships table matches its hook source. A memberships table keyed by a scope column, or a hook with suspension, always reads the tables.
node scripts/hook-bench.ts times the hook on Postgres 17 and records scripts/hook-bench.json. Times are the median and p95 of 25 server-side calls on an Apple M5 Max; bytes are exact. Each entry of the claim takes about 56 bytes. Cookie chunks use better-supabase's BS405 estimate: claims times 4/3, plus 1,700 bytes, in 3,180-byte chunks.
| Memberships | Claim | Full read, median / p95 | Claims | Chunks |
|---|---|---|---|---|
| 1 | on, 1,024-byte budget | 0.07 / 0.16 ms | 614 B | 1 |
| 500 | on, 1,024-byte budget | 1.32 / 1.39 ms | 1,491 B | 2 |
| 500 | on, no budget cap | 2.44 / 2.71 ms | 28.8 KB | 13 |
| 500 | off | 1.01 / 1.04 ms | 588 B | 1 |
Authorization version
A token is a copy, and a copy can be stale: a demoted admin keeps their token until it expires. For most permissions jwt_expiry bounds that. For sensitive ones (removing a member, creating a payout), list them in the policy:
definePolicy(permissions, {
fresh: [permissions.member.remove, permissions.payout.create],
// ...
});The generated triggers bump permdock_authz_version.version for the affected user on every insert, update or delete in a source table or the roles table, and the hook writes the current value as authz_ver. authzVersion({ query }) reads the same table. When the subject's memberships come from the token (claimsFirst without truncation), createPermDock compares the two. If the token is behind, or either side is missing, the subject is stale and every fresh permission denies with reason stale-credentials; other permissions still use the token. Memberships read live from a source are never stale. A stale subject's snapshot omits allows for fresh permissions, so the browser denies them too. A suspension change does not bump the version; RLS checks suspension live instead (RLS).
A table that changes what a user may do without being a hook source, such as better-supabase's entitlement_members, bumps its users with permdock_bump_authz_version_for(array[...]) from its own trigger. The function is security definer, and execute is revoked from public, anon and authenticated and granted to no one, so only the function's owner can call it: a security definer trigger owned by the table owner, or a migration. The manifest names it in authzVersionBump.
Version broadcast
A custom-role edit bumps the tenant's custom_role_version once per statement and, with broadcast on, sends { tenant, version } with event custom_roles on authz-tenant:<tenant>, one message per edited tenant however many users hold the role; an edit of a shared or platform role sends one message on the server topic. No receive policy is written for authz-tenant:<tenant>, so a secret-key server client subscribes to it and a browser does not.
Every row written to permdock_authz_version is broadcast through Supabase Realtime as { user_id, version } with event changed, on two private topics:
| Topic | Who joins it |
|---|---|
permdock:authz, or better_supabase:authz with better-supabase | A secret-key server client that evicts its VersionCache; no user |
authz:<uid> | The signed-in user, to refresh the browser snapshot |
The hook also writes the permdock_authz_version_receive policy on realtime.messages, which lets a user receive only their own authz:<uid>. better-supabase's blocks.sessions.authzVersions writes the same policy, so in a project with it on the policy is left out; doctor PD082 asks to turn that option off. supabase.hook.broadcast sets topic and receivePolicy, and broadcast: false sends nothing. The hook broadcasts on better_supabase:authz when better-supabase is found: a better-supabase.config.* from permdock.config.ts up to the workspace root, the file betterSupabase.config names, or a better-supabase dependency in the nearest package.json or a workspace package. With only the dependency, activeFrom and the receive policy keep their defaults, and doctor PD087 asks for betterSupabase.config. AUTHZ_TOPIC, AUTHZ_EVENT and authzUserTopic(uid) in permdock/supabase name the topics for a subscriber. The trigger skips the send where realtime.send does not exist, such as in a shadow database.
Refresh and OAuth tokens
The hook branches on how the token is issued, from authentication_method and client_id in its event.
Refresh. With authentication_method: 'token_refresh', the hook keeps the roles, memberships and team_ids of the incoming claims instead of reading them again when all of these hold, and reads them again otherwise:
- the incoming
authz_veris a number equal to the user's currentpermdock_authz_version.version; - the incoming claims have
rolesandmembershipsarrays and nomemberships_truncatedorteam_ids_truncated; - the reused claims, counted as the full path counts them, still fit
budget.
The hook always runs the suspension check, attrs, hook.claims and hook.before again, and rewrites the tenant claim and custom_roles_ver for the current active tenant. It drops user_role and the tenant claim from the incoming claims before it writes them. A revoked or changed membership, a removed global role or a changed teams row bumps authz_ver through the triggers above, so the next refresh reads the sources.
The fast path is compiled only when every change to what the claims read bumps authz_ver. It is left out, and the hook reads on every refresh, for:
- a source with
expiresAt: a row expires without a write; - a source that reads a scope suspension table: a change there does not bump the version;
version: false.
supabase.hook.refresh: 'reuse' (the default) compiles the fast path where it holds. 'full' never compiles it. An explicit 'reuse' that cannot hold fails hook generate and names the source.
Supabase Auth builds the claims of a refresh itself. The fast path runs only where the event's claims carry the previous token's authz_ver; where they do not, the hook reads as before and nothing is lost. tests/integration/src/hook-refresh.test.ts covers the cases and records, over 100 runs with 5 memberships, 0 calls to memberships_for on the fast path against 100 on the full path.
OAuth clients. A token with a client_id acts for a scope the user granted to an OAuth client (token security), not as the user. supabase.hook.oauth: 'full' (the default) writes the same claims as a user session. 'slim' returns the incoming claims with empty roles and memberships, and without user_role, attrs, team_ids, the tenant claim, custom_roles_ver, authz_ver and the hook.claims claims. It reads nothing, and a suspended user gets the same empty claims. Every claim Supabase Auth requires comes back unchanged.
Changing refresh or oauth rewrites only the function: run permdock generate --only supabaseHook and apply the new migration. It needs no data migration, and tokens already issued keep their claims until they expire.
Memberships the identity provider owns
A membership provisioned by SCIM belongs to the IdP: an edit in the app would be undone by the next sync. Such memberships carry managedBy: 'idp'. directoryMembershipSource sets it on every group membership, and the SQL sources read it from managedBy. isExternallyManaged(membership) tells a member list to render the row read-only, and decideRoleChange refuses a change whose target.managedBy is idp with reason externally-managed. In the database, permdock_protect_managed raises 42501 when anon or authenticated inserts, updates or deletes an IdP-owned row; the server and the SCIM relay, which connect with their own role, are unaffected.
Plans and seats
entitlements on createPermDock is an EntitlementSource: entitlementsFor(principal, { tenant }) returns plan names for the active tenant, merged into principal.plans, so plan('<name>') grants apply. It is read for the validated active tenant only; a requested tenant without a membership gets none. stripeEntitlementSource({ stripe, customer }) reads Stripe's active entitlements (stripe.entitlements.activeEntitlements.list, every page) for the tenant's Stripe customer and returns their lookup_keys. memoryEntitlementSource is the in-process default.
A seat belongs to one membership, not the tenant: a Dev Mode seat in one organization says nothing about another. Membership.entitlements holds seats (from the sources' seats column), and a plan() grantee matches a seat only through a membership that applies under the active tenant.
Manifest
permdock supabase inspect --out permdock.manifest.json writes what the hook and helpers expect as one JSON file, and --check fails CI when it falls behind the config. It is the stable contract for packages that build on the hook: better-supabase reads it instead of PermDock's config or its generated SQL.
| Field | What a reader learns |
|---|---|
hook, markers | Where custom_access_token_hook lives and the majors of the -- permdock:hook / -- permdock:grants lines its migrations start with |
claims, tenantClaim, budget, authzVersion, authzVersionBump | Every claim the hook writes, who owns it, what the budget measures, and the function that bumps authz_ver for a list of users |
helpers, rls | The helper schema, each helper's arguments, return type and the roles that may execute it, the RLS mode (jwt or database) and each scope's id type |
memberships | Each source's table and the columns (or fixed values) for user and role (each with the table it reads through), scope, id, within, via and expiry |
rls.memberships | The same shape for the tables member_<scope>_ids_for reads, which differ from the hook's when rls.memberships or rls.membershipSources is set |
rls.helpers (_for and assignment forms) | The _for helpers trusted SQL calls for a stored user, and permdock_can_assign_any with the other assignment checks when a role declares assigns |
rls.customRoles, rls.roles, rls.suspension, rls.assignments | Whether custom roles live in tables, the global-roles table, the suspension tables, and the tables the assignment triggers guard |
managementApi | The Management API fields a hosted project needs for Auth to call the hook: hook_custom_access_token_enabled, hook_custom_access_token_uri and jwt_exp |
decidingColumns | Every schema.table.column a membership or an attrs claim is computed from, which clients must not be able to write |
names | Every SQL helper, view and claim name the generated RLS gives application SQL, per scope and per resource |
The format, its JSON Schema (schemas/supabase-manifest-v1.json) and the versioning rule are on wire formats; supabaseHookManifestFixture in permdock/testing is a sample to test a reader against.
Why
- A manifest, not a shared config. A package next to the hook needs what the generated SQL reads, not how PermDock's config spells it. A versioned file that only gains fields keeps the two packages on separate release schedules, and a committed copy lets its doctor check a project without loading the PermDock config.
- One definition, two readers. The sources run the exact
selectthe hook compiles, and the integration suite checks that the claim equals whatcomposeMembershipsreturns for the same user. A hand-written hook next to a hand-written source is two definitions of who belongs where. - The active scope first, then truncation. A token that cannot hold every membership should hold the ones the next request needs. Truncating silently would turn a large customer into a user with random missing access; the flag makes the server read the rest.
- Roles are read by key, through a roles table when the app has one. Role grants,
role_permissionsseeds, therolesclaim and each membership'srolesall name roles by key, while apps that manage roles in a UI usually keepuser_roles.role_idandorganization_users.role_idreferencing arolestable. Copying keys into those tables would make a rename a data migration; joining at read time keeps one source of truth, and the version trigger onrolesmakes a rename reach existing tokens at the nextfreshcheck. Global roles and membership sources take the same{ through, on, column }shape, so one roles table serves both and gets one trigger. - A membership's user can be read through a profile table. Portal contacts are often rows of a contact or profile table that a login is attached to later, or moved between logins. Copying
user_idonto every membership row would make each re-link a fan-out update that the app has to keep consistent; reading it through the profile keeps one place to change, and the trigger on that column bumps both logins, so the old one loses the memberships and the new one gains them at the nextfreshcheck. - A version, not a shorter expiry, for sensitive verbs. Dropping
jwt_expiryto a minute taxes every request to protect a few. The version costs one indexed lookup per request that usesclaimsFirstwithversion, and onlyfreshpermissions depend on it. Missing either side counts as stale, because a check that passes when it cannot compare fails open. - Attributes are server-owned or absent. An attribute that decides row access and that the user can edit is a self-grant. Refusing
user_metadatacatches the obvious case; the migration guard catches aprofilestable with a broadupdategrant, which is the common one. - IdP ownership is enforced where edits happen. The member list,
decideRoleChangeand the database all refuse, so a client that skips the UI still cannot edit a SCIM-provisioned row. - pg-delta by default, grants in their own migration for
db diff.db diffreads the schema files back from a shadow database and leaves out what it cannot diff for the auth role. A separate, hand-created migration keeps those statements in the history in the right order; putting them in the schema file would make them silently disappear, and a hook the auth server cannot call fails every sign-in. pg-delta diffs grants, which was checked againstdeclarative syncin Supabase CLI 2.119 and is covered by an integration test against@supabase/pg-delta, so under pg-delta the grants stay in the hook file. Supabase made pg-delta the declarative engine in Declarative Schemas 2.0, so it is the default; migra and plain migrations stay as opt-outs for projects that have not moved. uidis a uuid. Supabase Auth issues uuid user ids, so the hook castsuser_idonce and a malformed one fails the sign-in. Each%typevariable is then assigned from a uuid, whichsupabase db lintaccepts.- Plans from billing, seats per membership. Stripe recommends reading entitlements as a projection of billing state; a per-membership seat keeps "which products this person uses here" apart from permissions and from other tenants.
Related
- Supabase provider:
subjectFromSupabase,supabaseRls, the RBAC scaffold. - RLS: helpers,
jwtanddatabasemodes, suspension. - Tenancy and scopes: memberships, sources, the active tenant.
- supabase CLI command.
Last updated on
Supabase
The permdock/supabase provider maps Supabase JWT claims to a PermDock subject, scaffolds the authorize() RBAC tables and hook, and pairs them with the per-statement RLS helpers (permdock_has, permitted_<scope>_ids and member_<scope>_ids per named scope) that generated policies call.
better-supabase
The permdock/better-supabase entry fills better-supabase's authorization slots with PermDock, an authorization provider for its SQL modules and doctor, bucket and topic policies, API keys, MCP tool hooks, a credential guard, and a subject from its session.