PermDock
Adapters

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, id and role default to user_id, scope, scope_id and role. columns.role may be a reference to a roles table, and columns.user a reference to a table that holds the user id (below). within names a jsonb column of ancestor ids; via, expiresAt, disabledAt (a nullable timestamp that suspends the row: suspended memberships), managedBy (a text column where idp marks an IdP-owned row), seats (a text[] column) and x (a jsonb column of app data, read into Membership.x and never written into claims) are optional. Rows for the same instance, kind, expiry, owner, seats and x merge 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. roles is a role column, a reference to a roles table (below), or fixed roles (['contact']), so a contact table needs no role column. user is the user id column (default user_id) or a reference to a table that holds the user id (below). id defaults to <scope>_id, within maps each ancestor scope to its column, via is the kind every row has, and managedBy is 'idp' (every row) or { column }.
  • blockMembershipSource({ table?, scope?, columns?, roleThrough?, roles?, query?, suspension? }) from permdock/better-supabase reads better-supabase's memberships block table: a junctionMembershipSource over better_supabase.memberships with scope organization, organization_id, user_id, role and disabled_at. columns takes the block's logical names (tenant, user, role, disabledAt; disabledAt: null for none), as in blocks.memberships.columns.memberships. roleThrough is the value of blocks.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 with roleThrough.
  • query(text, values) runs one statement: pg's client.query and postgres's sql.unsafe both fit. Without it a source only describes SQL, which is all permdock.config.ts needs.
  • suspension has the shape of rls.suspension: rows of a suspended user, instance or ancestor instance are left out, and a missing status row counts as suspended. A scope with keep keeps the rows of its suspended instances instead, each with a keep column of the permission keys it still grants (permissions a suspended scope keeps); a source without keep adds the column only next to one that has it. A row whose disabledAt column is set is a suspended membership: it is left out, or with suspension.memberships.keep kept 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:

permdock.config.ts
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.

FieldIn the record
membershipsThe 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.
rolesThe user's global roles, unchanged.
customRolesThe 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.
customRolesVersionsThe version of p_tenant alone, when a held role is a custom one.
claims.team_idsThe 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 claimsThe 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 getPermDock reports source-threw and 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, record and memberships.globalRolesFor still read the whole user.
  • The instance memo and a memorySubjectCache key the record by user and tenant, and evict(id) drops every tenant's record. A custom SubjectCache that ignores the tenant argument is never served another tenant's record, because the source discards a record whose tenant differs; 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 --check

The output is one idempotent migration:

  • custom_access_token_hook(event jsonb), stable, search_path = '', which writes:
    • roles (every global role) and user_role (a string for one role, an array for several; absent for none, so app_metadata still applies) from supabase.hook.roles, by default rls.roles, else <schema>.user_roles (user_id, role). A role of { through: 'roles', on: { role_id: 'id' }, column: 'key' } reads the key through a roles table, which also gets the auth-admin read. When rls.customRoleWrites.roles names that table with a tenant column, only its rows without a tenant are global roles;
    • memberships: a union all over every source, in the canonical { scope, id, within?, roles, via?, expires_at?, managed_by?, entitlements?, keep? } claim form, expires_at in NumericDate seconds;
    • the active tenant claim (rls.tenantClaim, default tenant_id), whenever the user holds a membership in it, also when the budget left that membership out of memberships. The generated RLS helpers narrow to it unless rls.tenants is 'all' (active tenant). The active first-scope id comes from app_metadata.active_<first scope> by default, or in a project with a better-supabase.config.* from the claim better-supabase writes (auth.tenant.claim, then rls.tenantClaim, then tenant_id); --active-from (or supabase.hook.activeFrom) takes app_metadata.<key>, <table>.<column> joined on id, 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 and app_metadata keys (below), never other columns;
    • authz_ver: the user's authorization version (below);
    • custom_roles_ver: the custom-role version of the active tenant, when rls.customRoles keeps the roles in the permdock tables (database mode). The hook reads it with custom_roles_version_for(active tenant); the claim is absent without an active tenant or in jwt mode;
    • the claims other packages own, from supabase.hook.claims (below).
  • The supabase_auth_admin grants: usage on the schema, execute on the hook and on its security definer readers (memberships_for(p_user), global_roles_for(p_user) and the team reader), and select with a read policy on the tables the hook body reads itself: the attrs table, the suspended-user table and the version table. The membership sources, their suspension tables, global roles and every roles or user table a through references are read inside the readers, so they get no grant. memberships_for drops 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. execute is revoked from authenticated, anon and public, and so is every privilege on each supabase.hook.claims and supabase.hook.before function, which returns any user's claims for the user id or event it is given. Nothing is granted to service_role, except to the supabase.hook.api wrappers when you set it.
  • With supabase.hook.security: "definer", the hook is security definer and reads with the rights of the role that applies the migration (postgres on Supabase). supabase_auth_admin then gets usage on the hook schema and execute on the hook only: no select and no read policies. The hook.claims and hook.before functions 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 for supabase_auth_admin. The default "invoker" keeps the hook's reads to the tables the grants name. Doctor PD085 runs the hook as supabase_auth_admin against a database in either mode.
  • permdock_authz_version (user_id, version) and the permdock_bump_authz_version function, 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. With through on the global roles or on a source, permdock_bump_authz_version_role_keys on 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 their roles and memberships claims. A source that reads its user through another table gets permdock_bump_authz_version_member_users instead, which bumps the users its old and new rows reference, and the referenced table gets permdock_bump_authz_version_linked_users on 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 in auth.users, so deleting a user whose profile is set to null still 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_managed trigger on sources with managedBy.
  • The config.toml block, 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.

  1. Apply the migration that creates custom_access_token_hook and its grants. Auth calls the function as soon as the hook is enabled; a missing function makes every sign-in fail.
  2. Set the hook on the project: hook_custom_access_token_enabled to true, hook_custom_access_token_uri to pg-functions://postgres/<schema>/custom_access_token_hook, and jwt_exp to the lifetime [auth] jwt_expiry sets. permdock supabase inspect prints all three under managementApi, so the values to send come from the same run that wrote the SQL.
  3. Check a freshly issued token for memberships, roles and authz_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_hook

A 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.sql

The 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> reads auth.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. generate refuses user_metadata and raw_user_meta_data in any form, auth.users as the table (use app_metadata.<key>), prototype keys and a key named twice.
  • The migration starts with a guard: when anon or authenticated can insert or update any listed column (has_column_privilege, which counts table-level and public grants), it raises 42501 and installs nothing. Grant clients column-level update on other columns only. permdock doctor PD028 reports the same from your migrations, before you run them.
  • The hook drops any attrs the 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 memberships budget (size budget). The hook adds the teams after the memberships it kept. When the whole list would exceed the budget it writes no team_ids and sets team_ids_truncated: true: the claim is never a prefix, and team rows never set memberships_truncated.
  • A suspended user gets no team_ids, and the hook drops any team_ids the incoming claims carry.
  • team_ids is reserved: hook.claims cannot name it. supabase-claims-v1.json and SupabaseClaims type it as an array of strings.
  • member_team_ids_for(p_user uuid, p_active text default null) reads the table, security definer, executable by supabase_auth_admin only; a row with disabledAt set is no team, and with tenant a suspended tenant's teams are left out. A team or teams scope's member_<scope>_ids_for takes the same arguments, and the hook calls it instead.
  • The table's user, team, tenant and disabledAt columns are deciding columns in the manifest. A client role that can write the table can choose its own team_ids, so revoke insert and update on it.
  • Without a team or teams scope that has membership sources, the hook file also writes member_team_ids_of(p_user uuid) returns setof uuid in the rls.schema from the same table. It answers only for the caller, skips a suspended user, and authenticated may execute it; better-supabase's teamIdsOf calls it. The team column is a uuid.

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.

  • subjectFromSupabase reads it as principal.suspendedIn.
  • permdock_subject() and permdock_subject(p_tenant) return it as suspendedIn. For a tenant, a user with no membership who is suspended there gets the record with memberships: [] and suspendedIn: [tenant] instead of null; a user who was never a member still gets null.
  • suspended_in_for(p_user uuid) returns jsonb is the reader behind both, granted to supabase_auth_admin only.
  • RLS is unchanged: the user holds no membership there, so every policy denies. suspendedIn only lets the application show "your organisation is suspended" instead of "not a member".
  • A membership the source itself drops because of its own suspension option is invisible to the function. Put the suspension in rls.suspension.scopes.<root> and leave it off the source.
  • A token refresh that reuses its claims keeps the suspended_in it holds until authz_ver moves.
  • A tenant beyond the 16th says nothing: suspendedIn is 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 with search_path = '', so an unqualified name is refused. The hook sets the claim to the result, and a null result 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, and sub, 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_admin usage on each function's schema and execute on the function, after revoke 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 generate writes these helpers (SQL helper contract); with supabase.hook.claims set, the hook migration (or the --grants-out file) grants supabase_auth_admin execute on each, so apply the helpers migration first.

    Why. Auth runs the hook as supabase_auth_admin before a token exists, so auth.uid() and auth.jwt() are empty and member_<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 with hook.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 with search_path = '', so an unqualified name is refused.
  • The hook calls each one first, in order, with the event it received. A result with an error key 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. A null or 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, memberships or the tenant claim.
  • The migration (or the --grants-out file) grants supabase_auth_admin usage on each function's schema and execute on the function, after revoke 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. Grant supabase_auth_admin whatever the function reads.
  • permdock supabase inspect lists the functions as hook.before in 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 permdockClaims definition with its membership entries, keep included.
  • 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.claims entries belong to other packages and stay.
  • The migration runs create extension if not exists pg_jsonschema with schema extensions and grants supabase_auth_admin usage on extensions and execute on extensions.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 as authz_ver and is checked against the version table, so a stale token cannot outlive a revocation.
  • user_metadata is writable by the signed-in user and must never carry authorization data. Membership claims belong in app_metadata or 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_admin and revoked from anon, authenticated and public; Supabase advises against security 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 size and doctor PD110 measure a token as an OAuth sign-in produces it: a long email, the user_metadata a social provider writes and an OAuth client_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:

Membershipsrls.memoClaims branch, mean / p95Table branch, mean / p95
1none0.417 / 0.602 ms0.406 / 0.583 ms
8none0.495 / 0.614 ms0.457 / 0.578 ms
11none0.728 / 0.983 ms0.673 / 0.902 ms
1permdock0.219 / 0.319 ms0.209 / 0.333 ms
8permdock0.329 / 0.410 ms0.281 / 0.355 ms
11permdock0.386 / 0.467 ms0.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.

MembershipsClaimFull read, median / p95ClaimsChunks
1on, 1,024-byte budget0.07 / 0.16 ms614 B1
500on, 1,024-byte budget1.32 / 1.39 ms1,491 B2
500on, no budget cap2.44 / 2.71 ms28.8 KB13
500off1.01 / 1.04 ms588 B1

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:

TopicWho joins it
permdock:authz, or better_supabase:authz with better-supabaseA 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_ver is a number equal to the user's current permdock_authz_version.version;
  • the incoming claims have roles and memberships arrays and no memberships_truncated or team_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.

FieldWhat a reader learns
hook, markersWhere custom_access_token_hook lives and the majors of the -- permdock:hook / -- permdock:grants lines its migrations start with
claims, tenantClaim, budget, authzVersion, authzVersionBumpEvery claim the hook writes, who owns it, what the budget measures, and the function that bumps authz_ver for a list of users
helpers, rlsThe 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
membershipsEach 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.membershipsThe 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.assignmentsWhether custom roles live in tables, the global-roles table, the suspension tables, and the tables the assignment triggers guard
managementApiThe 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
decidingColumnsEvery schema.table.column a membership or an attrs claim is computed from, which clients must not be able to write
namesEvery 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 select the hook compiles, and the integration suite checks that the claim equals what composeMemberships returns 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_permissions seeds, the roles claim and each membership's roles all name roles by key, while apps that manage roles in a UI usually keep user_roles.role_id and organization_users.role_id referencing a roles table. 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 on roles makes a rename reach existing tokens at the next fresh check. 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_id onto 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 next fresh check.
  • A version, not a shorter expiry, for sensitive verbs. Dropping jwt_expiry to a minute taxes every request to protect a few. The version costs one indexed lookup per request that uses claimsFirst with version, and only fresh permissions 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_metadata catches the obvious case; the migration guard catches a profiles table with a broad update grant, which is the common one.
  • IdP ownership is enforced where edits happen. The member list, decideRoleChange and 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 diff reads 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 against declarative sync in 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.
  • uid is a uuid. Supabase Auth issues uuid user ids, so the hook casts user_id once and a malformed one fails the sign-in. Each %type variable is then assigned from a uuid, which supabase db lint accepts.
  • 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.

Last updated on

On this page