PermDock
Adapters

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.

permdock/better-supabase connects PermDock to better-supabase. better-supabase verifies tokens, builds sessions and owns the data layer; PermDock owns roles, permissions, the claim contract and the one token hook. better-supabase never imports PermDock: it reads a versioned AuthorizationProvider object from its config, and this entry builds that object and the other values its slots take from the files PermDock already generates.

The entry needs better-supabase 0.87.0 or later as a peer (>=0.87.0). The range has no upper bound: CI tests 0.87.0 on every pull request, and a daily job tests the newest release. Coming from 0.58 to 0.84, run better-supabase gen and better-supabase upgrade, then a schema diff. Before you deploy 0.61 or later, give each API key the scopes it needs: a key holds only the permissions its scopes map to, and a key with no scopes holds none (0.61.0 changelog). An app older than 0.58 follows better-supabase's 0.57 to 0.58 guide first: run better-supabase codemod naming and the other codemods it lists.

Everything on the Supabase page still applies: the hook, the helpers and the claims are the same with or without better-supabase.

A better-supabase app imports definePermDock from permdock/better-supabase. That definition owns the caches and adds .authorizer, .next and .fromClient. It is the one factory for an app that also runs permdock/supabase/middleware: pass it the subject options, and hand the result to createPermDock from permdock/supabase/middleware, which reads the same version, instance and subject caches. Calling definePermDock from permdock/supabase as well builds a second set of caches (PD100). defineBlocksConfig<typeof policy>()(blocks) returns the blocks config unchanged and rejects a blocks.<name>.permissions value that is not a permission key of the policy, where PD079 would otherwise report it. Each definition builds its own version, instance and subject caches: entries are keyed by principal, authorization version and tenant, bounded to 10,000 per cache with least-recently-used eviction, and expire after maxStaleMs. The definition keeps no module-level subject state, and the admin client is a WeakMap key only. permdock/app has neither. authorizationProvider fills platformRoles and functions.subject unless the option is false. suspension.userKey is the user id column. personas: "roles" is sent as written, with the fixtureRoles the manifest lists.

Why

  • better-supabase has slots, not a PermDock mode. Its config takes an authorization provider, a bucket or topic takes an access policy, and its API key block takes a claim and a verifier. Each slot is a neutral, versioned contract (apiVersion: 1), so PermDock fills it the way permdock/better-auth fills Better Auth's role source, and any other authorization package could fill it too.
  • The provider is data built from the manifest. permdock supabase inspect --out already writes permdock.manifest.json with the helper schema, the scopes, the membership tables and the hook's claims. authorizationProvider maps that file to the contract, so better-supabase's SQL and doctor follow the helpers permdock rls generate wrote without reading a PermDock file themselves.
  • The slot types come from better-supabase/contract, the types-only entry better-supabase versions with ContractApiVersion. The entry never imports a runtime entry such as better-supabase/config or better-supabase/mcp for a slot's type, so its runtime graph stays the same whichever better-supabase entries the app loads.
  • The token hook names one truncated marker. better-supabase reads tokenHook.truncatedClaim for its permissions readers and budget.truncatedClaim for doctor's budget check, and its conformance kit requires them to agree. PermDock's hook writes only memberships_truncated, so the provider names it in both: a token whose memberships were cut makes permissionsOf ask the database, which fails closed.
  • permdock/supabase stays plain Supabase. It names no better-supabase identifier, and an app on @supabase/supabase-js or @supabase/server alone never loads this entry.

Who owns what

ConcernOwner
Token verification (@supabase/server), sessions, refresh and the AuthSession shapebetter-supabase
Typed clients, repositories and typegenbetter-supabase
Storage and Realtime plumbing (defineBucket, defineTopic), jobs and webhooksbetter-supabase
MCP protected-resource metadata and the scope guards (createMcp, createMcpAuth)better-supabase
Token lifetime, refresh-token reuse, signing keys, splinter and claim size lintsbetter-supabase
The claim contract: user_role, roles, memberships, the active-tenant claim, attrs, authz_ver, memberships_truncatedPermDock
The one token hook (permdock supabase hook generate)PermDock
role_permissions, authorize(), the SQL helpers and the table policiesPermDock
Building each access request from the verified context, and the permission option of routes, actions and toolsbetter-supabase
Deciding each request (authorizer), and tool and route authorizationPermDock
Share-link rows: creating, hashing, expiring and revoking thembetter-supabase
The guest subject a share link becomes, and its reads under RLS (subjectFromShareLink)PermDock
Approval delegation (out-of-office covers) when both are installedPermDock

API

import {
  authorizationProvider,
  authorizer,
  bucketPolicy,
  topicPolicy,
  apiKeyVerifier,
  apiKeyClaimOptions,
  subjectFromBetterSupabase,
  subjectFromShareLink,
  toolPolicy,
  credentialGuard,
  hookCan,
  handlerCan,
  supportPolicy,
  subscriberPolicy,
  principalSource,
  principalFromMemberships,
  accessReviewApplier,
  authorizationHooks,
  roleOrderFromCatalog,
} from "permdock/better-supabase";
  • authorizationProvider({ manifest, catalog?, scope?, approver?, approvers?, activeTenant?, rowHelpers?, roleIn?, doctor? }) returns better-supabase's AuthorizationProvider (apiVersion: 1, name: "PermDock"). manifest is permdock.manifest.json, parsed or as JSON text; catalog is permissions.catalog.json. Without a catalog the provider lists no permissions, so better-supabase refuses every key a bucket, topic or module checks, and problems asks for it. scope names the tenant scope and defaults to the manifest's one root scope.
  • Its functions call permitted_<scope>_ids_by_permission, member_<scope>_ids, permdock_has_permission and their _for forms in rls.schema. These take a permission key and subtract the instances a deny of it reaches, so a permission split into #n grant keys still matches. permissionsFor calls permitted_<scope>_permission_keys_for, so better-supabase's member_permissions lists a member's keys; like the other _for templates it is set only when the manifest lists the helper, which rls.mode: 'database' writes.
  • canAssign and canAssignFor call permdock_can_assign and permdock_can_assign_for. When the manifest's rls.customRoles is set and the tenant scope is a root scope, they call permdock_can_assign_any and permdock_can_assign_any_for at the tenant scope instead, so better-supabase's can_assign and can_assign_as also answer for a custom role.
  • roleSources read each membership's role through its roles table with tenant set to rls.customRoleWrites.roles.tenant. When that table has a scope column, where is {row}.<scope> = '<membership scope>'; without one, it is the catalog's roles at that scope or any row with a tenant. platformRoles comes from rls.roles: canAssign and canAssignFor ask permdock_can_assign_any at the 'global' scope with no tenant, and through.where is {row}.<scope> = '<globalScope>' when rls.customRoleWrites.roles sets scope and globalScope. better-supabase then fills blocks.memberships.options.roleThrough and blocks.invitations.options.platformRoles from them, and doctor PD094 reports a copy left in the config.
  • With roleIn: true, roleIn is permdock_role_in({role}, {tenant}) when the manifest lists it (rls.customRoles in database mode) and the tenant scope is a root scope. With blocks.memberships.options.roles.many, better-supabase's trigger on membership_roles then refuses a role that is neither declared nor a custom role of the row's tenant, such as another organization's custom role, with SQLSTATE 23514 and MEMBERSHIP_ROLE_SCOPE. It is off by default so a provider built from an older manifest keeps its output; problems reports roleIn: true without the helper.
  • holdersOf is permitted_<scope>_users(permission, tenant), the user ids holding a permission in a tenant, for a notification's audience. actorMayWrite is permdock_actor_may_write(), which the inbox and workflow modules call before a write. Each is set when the manifest lists its helper, with the role that runs it in requires.
  • teamIdsOf is member_<scope>_ids_of(user) for a scope named team or teams. With blocks.permissions.model: 'provider', better-supabase's team_ids_of() and the team-sharing policies of saved-views and collections call it instead of reading the teams block. The helper answers only for the caller and returns no rows for another user's id. team_ids_of() itself refuses a signed-in caller who names another user with TEAM_FORBIDDEN; the service role and direct database sessions still pass through. It is set when the manifest lists the helper. permdock rls generate writes it for a team scope with membership sources; without one, permdock supabase hook generate writes member_team_ids_of from supabase.hook.teams (teams). With neither, a scope directly within the tenant scope whose memberships name no via is the team scope when it is the only one, read through the caller-bound member_<scope>_ids() as (select m.id from member_<scope>_ids() as m(id) where {user} = (select auth.uid())); two such scopes leave it unset with a problem. Otherwise team_ids_of() reads the teams block, and doctor reports BS417.
  • permitted answers better-supabase's permitted(resource, id, permission): for a resource that names a scope, whether id is among permitted_<scope>_ids_by_permission(permission); for any other resource, whether the key is granted in the tenant. That second branch only holds for a key the catalog marks rowConditions: false; a key with row conditions is false there, so its table policies decide.
  • operations lists each catalog operation as better-supabase tools: a name without a dot becomes ai.tool.<name> and mcp.tool.<name>, and a dotted name is used as written. risk: 'critical' maps to high, and the effects send and spend to external. A permission whose code allows require an approval (the catalog's approvals) adds <resource>:<action>, the name better-supabase's approvals block reads as an approval floor, with approval.steps: by is one step and each of stages one step, quorum is required (default 1), and combine: 'sequential' sets mode: 'sequential'. A step's approvers are user() ids, one holder() permission, one role at the tenant scope and a one-level manager(), alone or in anyOf(). ttl, escalation, staleOn and mode have no counterpart and are left out. A "human" approval sets no floor; an allOf list, a relation approver, a role at another scope, or several different approvals on one permission set none either, and problems names the permission. blocks.approvals.options.policies entries still win.
  • actionKeys maps each block, record type, bucket and topic action to the permission whose meta.answers names it (answers), so blocks.<name>.permissions in better-supabase.config.ts can go. An action two permissions answer is left out, and problems names both keys. Doctor PD123 lists the installed actions no catalog key answers.
  • delegation.scopes maps each catalog permission's .scope to its key, so an OAuth client or agent token granted invoice:read gets invoice.read. Each coarse scope in the catalog's oauthScopes maps to the keys it covers (OAuth scopes). Keys are sorted by code point. A scope the catalog does not list grants nothing.
  • delegation.interactiveOnly lists the catalog keys whose meta sets interactiveOnly: true, sorted. better-supabase's cap_allows refuses them to an API key, an OAuth client and an act chain whatever their scopes, and no delegation.scopes entry maps to them (interactive-only permissions).
  • approver is a permission. It becomes the 'ai-tool' entry of approvers unless approvers names one. A key the catalog lacks is a problem.
  • In a project with a readable better-supabase.config.* object export, found from the directory of permdock.config.ts up to the workspace root (nearest first), the CLI defaults the hook's active source to app_metadata.<claim>, where the claim is better-supabase's auth.tenant.claim (or claims.tenant in a flat config), then rls.tenantClaim, then tenant_id. An explicit supabase.hook.activeFrom or --active-from wins. Plain Supabase keeps app_metadata.active_<first scope>. A better-supabase.config.* that throws while loading, for example because it reads a permdock.manifest.json that generate has not written yet, counts as a config that sets no claim, with a [better_supabase_config] warning, so the hook does not change between the first and second run. This makes generation, inspection and PD078 agree without changing plain Supabase projects.
  • activeTenant is better-supabase's blocks.permissions.activeTenant. When the token hook reads the active tenant from another place than better-supabase writes it, problems names the supabase.hook.activeFrom to set: app_metadata.<tenant claim> for "claim", or the profile column for { profileColumn }. Doctor reports the same as PD078.
  • rowHelpers: true fills better-supabase's rowsWith and rowsWithFor from the permitted_<resource>_rows helpers that rls.rowHelpers writes and the manifest names. A better-supabase record type whose action in recordTypes.<type>.permissions names rows: "<resource SQL name>" with a key then checks the rows the caller holds that key on, through the candidate form permitted_<resource>_rows(permission, ids) with better-supabase's text ids cast to the manifest's idType (uuid when a manifest written before 0.22.1 omits it, and the one-argument form when the row helpers disagree on it), and for another user through permitted_<resource>_rows_for. Without row helpers in the manifest, problems names the step to run.
  • tokenHook.activeOrganizationFrom names where the token hook reads the active tenant, from the manifest's hook.activeFrom: "claim" for app_metadata.<tenant claim>, or { profileColumn, key? } for a profile column. better-supabase's doctor BS409 warns when it differs from blocks.permissions.activeTenant. It is "resolver" when the manifest's hook.activeTenant is "request" (supabase.hook.activeTenant), so BS409 needs no blocks.permissions.activeTenant entry and problems reports no mismatch. It stays unset for an app_metadata key other than the tenant claim, which better-supabase has no name for, and when activeTenant is "resolver", where the tenant comes from the request.
  • approvers maps each better-supabase request kind to user(), holder() or anyOf() approvers and fills isApprover, which better-supabase asks for every request that waits on an approval (Approvers). It needs permdock_is_approver, which rls.approvals writes; without it isApprover is unset and problems names the helper. The provider never sets canApprove.
  • portalParties comes from a scope directly within the tenant scope whose memberships all name via, such as customer contacts: each (tenant, '<scope>', id) among member_<scope>_ids(), with the tenant read from the membership row's within column. portalParties: false leaves it out.
  • portalSubjects: true fills portalSubjects from the same scope: the ids that permitted_<scope>_ids_by_permission('<scope>.' || {action}) also returns, so a guest reaches a read, comment or upload only through a <scope>.<action> grant. It is off by default because better-supabase reads it for every record-attached comment, note and attachment: a contact's customer.read would read every comment and internal note on their customer, unless the inbox block hides notes. A guest source with no tenant column in within is left out and named in problems, as is a missing permitted_<scope>_ids helper. better-supabase's guests block adds its own grants.
  • versions is <hook schema>.authz_version_for when the hook keeps the authorization version (supabase.hook.version, default on), so better-supabase's sessions block reads PermDock's version instead of keeping its own. It answers null for an unknown or suspended user. The provider does not check supabase.hook.broadcast; with broadcast: false, no authz:<uid> message reaches better-supabase's clients.
  • doctor.command is ["permdock", "doctor", "--format", "findings"], so one better-supabase doctor run also runs PermDock's checks and reports their findings as BS705, under one baseline. doctor: { timeoutMs } passes through as doctor.timeoutMs; better-supabase stops the run after 60,000 ms by default. A timeoutMs that is not a positive whole number is left out and named in problems. The permdock bin must resolve from the project root.
  • wildcards is 'none' with a catalog whose keys hold no *: PermDock grants name exact keys, so better-supabase's permission_matches treats a stray * row as the literal key.
  • scopes carry each scope's idType: uuid, text, bigint or integer, with int8, int and int4 normalised. Any other id type is a problem.
  • requires lists each helper with the role that must execute it; memberships, suspension and roleSources come from rls; tokenHook names the hook function, the claims it owns and the grantsCommand that restores the hook's grants for the manifest's hook.schemas: permdock supabase hook generate && supabase db schema declarative sync -f permdock_hook under pg-delta, the --grants-out command under migra. A manifest written without supabase.hook (rls.authorize: 'database') has no hook section, so tokenHook is absent. A manifest that cannot fill a field is recorded in problems, which better-supabase's doctor reports, and an invalid manifest throws a TypeError.
  • authorizer({ policy, permdockFor?, subject?, operations?, memberships?, version?, versions?, instances?, intent?, store?, onError?, options? }) returns better-supabase's Authorizer (apiVersion: 1, name: "PermDock") for its authorizer server option. It decides every permission a resource, action, route guard or MCP tool declares (Authorizer).
  • permdockFor({ policy, subject?, memberships?, version?, versions?, instances?, subjects?, options? }) returns one resolver, (input, query?, versions?) => Promise<PermDock<V>> over the policy's vocabulary V, for a bsb.getClaims() snapshot, a bsb.bootstrap() or bsb.getAccess() result, a session or a Subject. Its sources(versions?) returns the frozen options to spread into createPermDock from permdock/next, permdock/orpc or permdock/mcp (One instance per version).
  • bucketPolicy(access, options) and topicPolicy(access, options) return the access policy for defineBucket and defineTopic. access maps the operations (read, list, write, delete for a bucket; receive, send for a topic) to permissions, and options is { manifest, catalog, scope, segment? } or { policy, schema?, scope, segment? }. With policy, the definePolicy result the app already imports, nothing is read at runtime: the scopes, the permissions with row conditions and the scopes each permission is granted at come from the definitions, and schema names the helper schema (rls.schema, default permdock). The checks below are the same either way. They call permitted_<scope>_ids_by_permission and permdock_has_permission, which check role and scope only and subtract denies, so a permission the catalog marks rowConditions: true (or a conditioned grant in policy), or does not grant at scope, throws. scope: "platform" checks a permission granted globally.
  • apiKeyVerifier({ keys, manifest?, serviceRoles?, allPermissions? }) is a CredentialVerifier over better-supabase's createApiKeys(), for subjectFromApiKey. A personal key is a user credential acting as its user, a tenant key a service credential holding serviceRoles in its tenant, and the key's scopes are the credential's permissions. serviceRoles defaults to the manifest's rls.apiKeys.serviceRoles. A rotated key in its grace period verifies, and its credential's expiresAt is the end of the grace period when that comes before the key's own expiry. An invalid, revoked, expired or rate-limited key, and a failed lookup, verify to null.
  • apiKeyClaimOptions(manifest) returns the claim and tenantClaim options of better-supabase's apiKeyClaims() and apiKeyResolver(), from the manifest's rls.apiKeys, so a key's token carries the scopes ceiling, tenant and roles the helpers read. It throws when the manifest has no rls.apiKeys.
  • subjectFromBetterSupabase(session, options?) is subjectFromSupabaseSession with better-supabase's defaults: memberships for the memberships and the entitlements module's features claim for principal.plans. A user session maps through subjectFromSupabase. With apiKeys: { permissions, manifest?, serviceRoles? }, an apiKey session maps like apiKeyVerifier's credential; without it, and for anon, service and invalid sessions, the subject is anonymous. plans: { claim?, keys? } decodes the short codes entitlements.claim.keys writes back to feature keys. Other options override the defaults.
  • subjectFromShareLink(token, { shareLinks, links, ttl?, linkPolicy?, onAuth? }) resolves a better-supabase share-link token into a link subject (Share links).
  • toolPolicy({ permdock, data? }) returns the authorize and visible hooks of createMcp for tools whose meta is a permission (MCP tools).
  • credentialGuard(provider, { permdock, use, revoke? }) wraps a CredentialProvider so PermDock decides each token use (Credentials).
  • hookCan(permdock) and handlerCan({ getPermDock }) return the can options of authorizeHook and protectWebHandler in better-supabase/workflow-sdk; workflowResource(subject, types) maps a run's RecordRef to the resource of workflow.start (Workflows).
  • supportPolicy({ policy, subject?, options?, writable?, approval?, approved? }) returns the authorize option of supportSessions (Support sessions).
  • subscriberPolicy({ policy, principals, events, row?, sender?, options? }) returns the per-subscriber check for an outbox, webhook or realtime fan-out (Subscriber fan-out).
  • principalSource({ claims, identities?, subject? }) returns a PrincipalSource over the claims better-supabase mints (Principals).
  • principalFromMemberships(userId, rows, { scope?, tenant? }) builds a frozen Principal from rows of the memberships block's table (BetterSupabaseMembershipRow: user_id, organization_id, role, disabled_at?), for server code that reads the table instead of the token (Server code).
  • accessReviewApplier({ client, reviews, policy, demoteTo?, email?, permdockFor?, schema?, scope?, now? }) applies the revoked items of an access review through the organizations and invitations blocks, then marks each one applied (Access reviews).
  • authorizationHooks({ policy, claims?, permdockFor?, ... }) returns better-supabase's AuthorizationHooks for createServer(betterSupabase, { authorization }) (Authorization hooks).
  • roleOrderFromCatalog(catalog, { scope?, owner? }) returns the catalog's role keys highest first, for the SSO block's roleOrder (SSO role order).

Setup

Generate the helpers, the hook and the manifest first, as on the Supabase page:

SPLIT="--target sql --split helpers,seeds,indexes,policies,hook"
permdock rls generate $SPLIT --seeds-out -                    # the schema files under supabase/schemas
supabase db schema declarative sync --no-apply -f permdock    # their migration
permdock rls generate $SPLIT --seeds-out supabase/migrations/ # the role_permissions seeds, after it
permdock supabase inspect --out
permdock collect

That is Declarative Schemas 2.0, the default: supabase/config.toml needs [experimental.pgdelta] with enabled = true. A project on supabase db diff sets supabase.schemas: 'migra', and one without declarative schemas sets supabase.schemas: 'migrations' (schema workflow); the manifest records which, and better-supabase's doctor names the matching grants command.

Then hand the provider to better-supabase. The config runs in Node, so it reads the two files directly:

better-supabase.config.ts
import { readFileSync } from "node:fs";
import { defineConfig } from "better-supabase/config";
import { authorizationProvider } from "permdock/better-supabase";

const read = (file: string) =>
  readFileSync(new URL(file, import.meta.url), "utf8");

export default defineConfig({
  auth: {
    authorization: authorizationProvider({
      manifest: read("permdock.manifest.json"),
      catalog: read("permissions.catalog.json"),
    }),
  },
  blocks: { permissions: { model: "provider" }, organizations: {} },
});

Run better-supabase upgrade and better-supabase gen after a change to the policy, so the rendered SQL and the provider agree. Rerun permdock supabase inspect --out first.

The provider templates call the generated helpers as prepared statements. Connect through the session pooler, or set prepare: false for the transaction pooler (connection pooling).

Claims

Validate sessions with the claim contract's Standard Schema, extended with the app's own claims:

src/lib/supabase/index.ts
import { createSupabase } from "better-supabase";
import { supabaseClaims } from "permdock/supabase";
import { z } from "zod";
import { schema } from "./generated-schema";

export const betterSupabase = createSupabase(schema).claims(
  supabaseClaims().extend(
    z.object({ datetime_preferences: z.object({ timezone: z.string() }) }),
  ),
);

A token whose claims fail either schema resolves to an invalid session. Pass supabaseClaims({ tenantClaim }) when rls.tenantClaim is not tenant_id, and set the same name in better-supabase's auth.tenant.claim.

Memberships

PermDock's token hook writes the membership claims; the memberships block supplies the table that blocks such as share links and organizations read. Run both over one table the app declares:

  1. Create the memberships table in the app's own schema file, one row per member: (organization_id, user_id, role).
  2. Map the block onto it with blocks.memberships.tables.memberships. The block runs over a table it does not own: it adds only the columns it lacks and its bsb_ policies and triggers.
  3. With the organizations block installed, set blocks.organizations.options.assignmentGuard: "external". PermDock's assignment triggers then check role changes, and better-supabase drops its own guard; it refuses "external" on a table the block created.
  4. Point PermDock's sources at the same table with blockMembershipSource.
better-supabase.config.ts
export default defineConfig({
  blocks: {
    memberships: { tables: { memberships: "public.organization_memberships" } },
    organizations: { options: { assignmentGuard: "external" } },
  },
});

blockMembershipSource from permdock/better-supabase reads the block's logical columns: organization_id, user_id, role and disabled_at, under the organization scope. Rename a column through columns, and pass disabledAt: null when the table has none. A role kept in another table goes through roleThrough (the block's option of the same name). Several roles per member go through roles: a junction keyed by the membership's id, or "many" for the membership_roles table that blocks.memberships.options.roles.many keeps, joined on the tenant and user columns:

permdock.config.ts
import { blockMembershipSource } from "permdock/better-supabase";

export default {
  supabase: {
    hook: {
      memberships: [
        blockMembershipSource({
          table: "public.organization_memberships",
          columns: { disabledAt: null },
        }),
        // Several roles per member, from blocks.memberships.options.roles.many:
        // blockMembershipSource({ roles: "many" }),
        // or from your own junction:
        // blockMembershipSource({ roles: { table: "public.membership_roles", membership: "membership_id", role: "role" } }),
      ],
      claims: { features: "public.feature_claims" },
    },
  },
};

Pass tables from blockTables in better-supabase/sql to follow the app's blocks.memberships.tables and columns renames, membership_roles included, instead of repeating them. An explicit table or columns entry wins over tables:

permdock.config.ts
import { resolveConfig } from "better-supabase/config";
import { blockTables } from "better-supabase/sql";
import { blockMembershipSource } from "permdock/better-supabase";
import config from "./better-supabase.config";

const tables = blockTables(resolveConfig(config, import.meta.dirname));

export default {
  supabase: {
    hook: { memberships: [blockMembershipSource({ tables, roles: "many" })] },
  },
};

With roles: "many", the manifest records the role set's through.on, and authorizationProvider names it as the membership's rolesTable, so better-supabase's role checks read every role and doctor BS411 stays quiet.

A role read through a roles table that also holds system roles, whose tenant column is null, needs an explicit blocks.memberships.options.sameTenant entry. better-supabase derives an entry for each foreign key between two tables with the tenant column, and sets shared when the referenced tenant column may be null. Write shared yourself so the entry does not change when the column does:

better-supabase.config.ts
export default defineConfig({
  blocks: {
    memberships: {
      options: {
        sameTenant: [
          {
            table: "public.organization_memberships",
            column: "role_id",
            references: { table: "public.roles", shared: true },
          },
        ],
      },
    },
  },
});

With shared: true a member may hold a system role, and another tenant's role still fails with TENANT_MISMATCH; with shared: false both fail.

Don't let the block write the claims. better-supabase add memberships stops while the provider's tokenHook.ownedClaims lists memberships, and better-supabase's doctor reports BS407 for a hook that calls membership_claims() next to PermDock's. The features claim above goes through supabase.hook.claims.

With the provider set, the entitlements module reads membership through member_<scope>_ids and its _for form, so an expired membership or a suspended organization loses its features in the same token that loses the membership (claims other packages own).

SSO role order

The SSO block's roleOrder lists the roles an identity-provider group may map to, highest first, without the owner role. roleOrderFromCatalog derives it from the catalog's assigns: a role that assigns another comes before it, and roles assigns does not order keep catalog order. Roles that assign each other stay together at the first one's place. scope keeps the roles declared on that scope, and owner leaves that role out.

better-supabase.config.ts
import { parseCatalog } from "permdock/catalog";
import { roleOrderFromCatalog } from "permdock/better-supabase";

const catalog = parseCatalog(read("permissions.catalog.json"));

export default defineConfig({
  // authorization as above
  blocks: {
    sso: {
      options: {
        roleOrder: roleOrderFromCatalog(catalog, {
          scope: "organization",
          owner: "owner",
        }),
        defaultRole: "member",
      },
    },
  },
});

Server code

src/lib/access.ts
import { getPermDockSync } from "permdock";
import { subjectFromBetterSupabase } from "permdock/better-supabase";
import { policy } from "../policy";
import { bsb } from "./supabase/server";

export async function permdockFor() {
  const session = await bsb.claims();
  return getPermDockSync(policy, subjectFromBetterSupabase(session));
}

The same subject works in the Hono, oRPC and @supabase/middleware adapters: map c.get("auth"), context.auth or the session the middleware put on the context.

Server code that reads memberships from the database, such as a page that lists another member's rights, builds the principal from the rows with principalFromMemberships:

import { principalFromMemberships } from "permdock/better-supabase";

const { data: rows } = await admin
  .from("memberships")
  .select("user_id, organization_id, role, disabled_at")
  .eq("user_id", userId);
const permdock = getPermDockSync(
  policy,
  principalFromMemberships(userId, rows ?? [], {
    scope: "organization",
    tenant: organizationId,
  }),
);

Each organization becomes one membership { scope, id: organization_id, roles }. scope defaults to tenant, the policy's first declared scope. Rows of another user, disabled rows and rows without an organization or role are dropped. A scoped grant applies only in the active organization: pass tenant, or pick one with permdock.tenant(id), or every scoped check denies with no-tenant. A role the policy does not declare grants nothing (isRoleName checks one).

Authorizer

better-supabase asks an Authorizer to decide each permission that a resource, action, route guard or MCP tool declares. authorizer({ policy }) answers with PermDock, in process, from the claims better-supabase has already verified:

src/lib/supabase/server.ts
import { createNext } from "better-supabase/next";
import { authorizer } from "permdock/better-supabase";
import { permissions, policy } from "../policy";
import { betterSupabase } from "./index";

export const bsb = createNext(betterSupabase, {
  authorizer: authorizer({ policy }),
  // env, postgres and auth as before
});

export const GET = bsb.route(
  async (_request, { db }) => Response.json(await db.staff.list().orThrow()),
  { requireTenant: true, permission: permissions.staff.list },
);

The adapter maps the request this way:

  • The subject is subjectFromBetterSupabase over subject.properties.claims, the verified access-token claims. A user or a delegated agent subject maps through them. anon, service, a missing claims and anything else is the anonymous subject, so every check denies.
  • context.tenant selects the active tenant only among the memberships the claims hold. A tenant with no membership is no tenant.
  • resource.properties is the row, and decide treats it as untrusted data: a claims or memberships key in it changes nothing. A row better-supabase loaded itself (source: "loaded") skips schema validation; a row from the request (source: "input", or no source) is validated against the resource schema.
  • resource.change is a write. A create ({ next }) decides on the new values. An update ({ current, next }) decides on the stored row and on the stored row with next over it, so a condition must hold before and after the write. Both are validated.
  • A throw, a value that is not a PermDock permission and an unknown role deny.
PermDock outcomebetter-supabase outcome
grantedgranted
denieddenied with the permission key and the first denial reason as the reason
approval-requiredapproval-required with the approval token as approval.id (Approval resume)

evaluations builds one PermDock instance per caller and tenant, so a list that checks each row costs one instance. permissions: true on a resource needs operations, a map from a table to the permission of each of list, get, create, update and delete; without it such a resource is refused. Pass subject to change the claim names and options for the sources and sinks of each instance (customRoles, sink, limits). tenant, actor, delegation, session and intent always come from the verified request.

Options

Prop

Type

memberships supplies live rows when token memberships are stale or truncated. version reads the current authorization version; it defaults to the source's own version method. A generated SQL membership source does not necessarily read the version stored by the token hook: pass authzVersion({ query }) from permdock/supabase when the hook's authz_ver is the freshness contract. version is the reader function, authz_ver is the token claim, and principal.authzVersion is the verified claim mapped onto the subject.

versions is the cache of those version reads, not a membership source. better-supabase's runtime cache takes precedence over this fallback option. It caches reads only within maxStaleMs, which defaults to 30,000 for memoryVersionCache and instanceCache (the ceiling stays 60,000); memoryVersionCache({ shared }) takes a VersionStore (get answers { version, at }, set(id, version, at), delete; the shape of better-supabase's store) so instances share what one read, and counts maxStaleMs from at, the database read, and betterSupabaseVersionCache(cache) from permdock/better-supabase wraps better-supabase's createVersionCache as a PermDock VersionCache. authorizer and permdockFor accept either shape; a write check reads the version live. Without memberships, the authorizer does not install claimsFirst, and version and versions do not add freshness checks on their own.

Each check builds its instance with an intent, the first row that applies:

CheckIntent
The intent option is setits answer
better-supabase sets context.intent (read or write)context.intent
A write whose context.enforcement is rlsdatabase-write
evaluations: list filtering and per-row checksread
evaluate of a permission whose action is read, list or viewread
Every other evaluate: actions, mutations, route guardswrite

Pass intent: (request) => Intent to decide it yourself. With read and database-write, claimsFirst may answer the version from the cache; with write it reads the version live. database-write marks a write that Postgres checks again under RLS on current data, so a stale version cannot grant the row change itself; a write with enforcement: "definer" or none stays live. See Shared cache. The function replaces the whole table, evaluations included:

import type { AuthorizationRequest } from "better-supabase/contract";
import { isPermission, type Intent, type Permission } from "permdock";

const intent = (request: AuthorizationRequest<Permission>): Intent =>
  isPermission(request.action) &&
  ["read", "list", "view"].includes(request.action.action)
    ? "read"
    : "write";

authorizer({ policy, memberships, version, intent });

Approval resume

Without a store, an approval-required decision returns its token as approval.id and files nothing. With an ApprovalStore, the first evaluate files an approval request, and a retry that carries the approved token passes once:

src/lib/supabase/server.ts
import { createNext } from "better-supabase/next";
import { authorizer } from "permdock/better-supabase";
import { supabaseApprovalStore } from "permdock/supabase";
import { admin } from "./admin"; // a service_role supabase-js client

export const bsb = createNext(betterSupabase, {
  authorizer: authorizer({ policy, store: supabaseApprovalStore(admin) }),
  approval: { header: "PermDock-Approval" },
  // env, postgres and auth as before
});
  • better-supabase refuses the call with a forbidden error carrying approval.id. The approver decides it through approvalsHandler.
  • The client retries with PermDock-Approval: <approval.id>. better-supabase passes the header as context.approval, and evaluate grants the call and consumes the token.
  • A replayed token, a pending one and a token issued for another permission, subject or row deny. A malformed header is no token, so the call asks again.
  • evaluations never consumes a token, so a list check does not spend the approval of the call it guards.

onError: (error, { permission, tenant }) => void receives every error a check threw. The check still denies, and a sink that throws is ignored.

testAuthorizer from better-supabase/testing checks the adapter against the contract; tests/better-supabase/authorizer.test.ts runs it on a fixture policy.

Warm the first request

authorizer(...) and authorizationHooks(...) each have warm(): Promise<{ ok: boolean; ms: number }>. It builds one anonymous instance through the same resolver, runs one can and never rejects. Call it from instrumentation.ts after the policy import; a failure answers ok: false and the first request builds the instance itself. Without a server permdock/next use, this is the one line:

instrumentation.ts
export async function register() {
  const { authorizer } = await import("./src/authorizer");
  await authorizer.warm();
}

On the CentraKit fixture it moves 1.24 ms out of the first request (Shared cache). better-supabase does not call warm itself yet; the request is in docs/agents/better-supabase-requests.md.

Version cache and session snapshots

One memoryVersionCache serves both libraries. Create it and the sources once at module scope, pass the cache to better-supabase as versions, and pass the membership source and version reader to authorizer:

src/lib/supabase/server.ts
import { createNext } from "better-supabase/next";
import { memoryVersionCache } from "permdock";
import { authorizer } from "permdock/better-supabase";
import { authzVersion, supabasePostgresQuery } from "permdock/supabase";
import { sources } from "@/sources";

const query = supabasePostgresQuery(postgres.admin);
const memberships = sources({ query });
const version = authzVersion({ query });
export const versions = memoryVersionCache({ maxStaleMs: 5_000 });

export const bsb = createNext(betterSupabase, {
  versions,
  authorizer: authorizer({ policy, memberships, version }),
  // env, postgres and auth as before
});

Here sources is the app's generated membership-source factory. authorizer wraps memberships in claimsFirst(source, { onStale: "reread", version, versions }) with the cache better-supabase passes at runtime. For a server created without versions, set versions on authorizer too. A read check answers from the cache within maxStaleMs; a write check reads the version live (Authorizer). postgrestSources(...).memberships already has a version reader; pass a separate version only to override it.

  • await bsb.evictSession(userId, { tags }) forgets the user's verified session and calls versions.evict(userId), so the next PermDock instance reads the version live. authorizationHooks sets sessionTags(userId) to [snapshotTag(userId)], so it also clears the user's cached PermDock snapshots, as sign-out and refreshSessionCache do.
  • better-supabase passes authorizer a request-scope memo, and the checks of one scope share one PermDock instance per claims, tenant and intent. With instances, requests share it too.
  • bsb.getClaims() verifies the token once per request and returns a SessionSnapshot. subjectFromBetterSupabase(snapshot) maps it like the user session of its claims, with iat as Subject.issuedAt and authz_ver as principal.authzVersion. A snapshot whose claims.sub is not its userId maps to the anonymous subject.

Bootstrap seed

When better-supabase passes runtime.seed ({ userId, version, subject }), the authorizer uses it only if userId equals the token's sub. It then seeds the subjects cache with the subject and passes version: { known }, so the instance reads no subject_for. A seed for another user is ignored, and so is one whose version differs from the live one. PermDockForResult.subject carries the record out of a bootstrap result. Supply the subject with <helpers schema>.permdock_subject() (hook).

bsb.bootstrap() reads authz_ver with the app's bootstrap data once per request and seeds versions through AuthzVersionCache.seed, which PermDock's VersionCache implements. A later read in the same process skips the version call, and permdockFor passes a bootstrap's version as version: { known }, so the request that read it skips it too.

One tenant's snapshot

definePermDock(...).next() returns getSnapshot(source, { tenant, omitStatic? }) next to authorization, authorizer and versions. It builds the snapshot of one tenant for a session, a bsb.bootstrap() or bsb.getAccess() result, or a subject: that tenant's grants and the subject's whole membership list, so the client can show its other tenants. A bootstrap that read permdock_subject(p_tenant) (the provider's subjectForTenant) seeds the subject read:

src/app/layout.tsx
const { getSnapshot } = permdock.next();
const access = await bsb.bootstrap();
const snapshot = await getSnapshot(access, {
  tenant: access.tenant,
  omitStatic: true,
});

With omitStatic, pass the generated clientBundle to the provider's bundle prop. Each extra membership adds about 40 bytes: on CentraKit's policy the snapshot weighs 1,850 bytes at 12 memberships and 3,383 at 50 (snapshots).

One instance per version

permdockFor and an instanceCache at module scope give every island, action and authorizer check of a user the same instance while the user's authorization version holds. Pass the resolver to authorizer and authorizationHooks, and spread permdock.sources(versions) into createPermDock:

src/lib/permdock.ts
import { instanceCache, memoryVersionCache } from "permdock";
import {
  authorizer,
  permdockFor,
  subjectFromBetterSupabase,
} from "permdock/better-supabase";
import { createPermDock } from "permdock/next";

export const versions = memoryVersionCache({ maxStaleMs: 5_000 });
export const permdock = permdockFor({
  policy,
  memberships,
  versions,
  instances: instanceCache(),
});
export const authorize = authorizer({ policy, permdockFor: permdock });
export const { protectAction } = createPermDock(policy, {
  subject: async () => subjectFromBetterSupabase(await bsb.getClaims()),
  ...permdock.sources(versions),
});

A better-supabase app guards its own actions with bsb.action and authorizer, which read the version and subject better-supabase already holds. protectAction is the wrapper for an app that has no bsb.action, or that wants Problem Details results with args, after and result (Server Actions); both read one shared instance when they use the same permdockFor.

The resolver holds subject, memberships, version, versions, instances, subjects and options. subjects is the SubjectCache of the app's postgrestSources; a call with a known authzVersion tells it that version, which drops an older record. authorizer and authorizationHooks throw a TypeError when given one of those next to permdockFor, so the two cannot drift apart. sources(versions) answers the same frozen object for the same cache, and authorizer passes the cache better-supabase hands it at runtime, so a bsb.action check and a protectAction of the same user at the same version share one instance. tests/better-supabase/sharing.test.ts checks this for protectAction, permdock/orpc and permdock/mcp.

src/app/[orgSlug]/quotes/island.tsx
async function QuotesIsland({ orgId }: { orgId: string }) {
  "use cache: private";
  const access = await permdock(await bsb.getClaims(), { tenant: orgId });
  // …
}
InputSubjectVersion
bsb.getClaims() snapshot or a sessionsubjectFromBetterSupabase(input, subject)The token's authz_ver, checked through versions
bsb.bootstrap() resultIts session; anonymous when sessionActive is falseauthzVersion as version.known, no read
bsb.getAccess() resultIts session, in its tenantauthzVersion as version.known, no read
SubjectAs givenThrough versions

getPermissions(permdock, input, { edit: [permissions.quote.update, quote] }, query?) decides named checks on one instance and returns frozen { [name]: { allowed, outcome, reason? } }, as getPermissions on permdock/next does. Inside another private scope that already sets its lifetime, add cacheLife({ stale: Infinity }) so the inner call does not shorten it.

The second argument is { tenant?, intent? } or a tenant id, so the resolver also fills an approvals handler's permdockFor and an access-review handler's permdockFor. intent defaults to read. authorizationHooks, supportPolicy and subscriberPolicy take instances too and resolve through the same code.

Other processes learn of a role or membership change from the version table's broadcast. In a better-supabase project, permdock supabase hook generate sends every bump as { user_id, version } with event changed on better_supabase:authz and on the user's own authz:<uid>, so subscribeAuthzVersions and SessionProvider read it with their defaults:

src/lib/supabase/server.ts
import { subscribeAuthzVersions } from "better-supabase/server";

subscribeAuthzVersions({ client: admin, versions });

admin is a secret-key client: no realtime.messages policy admits better_supabase:authz, so no user can join it. Subscribe in the module that creates versions. Leave better-supabase's blocks.sessions.authzVersions off: it keeps a second version table that never reaches the authz_ver claim PermDock writes, and doctor PD082 reports it. tests/better-supabase/version-cache.test.ts checks that evictSession and subscribeAuthzVersions evict a shared cache.

Vercel functions without subscribeAuthzVersions

A Vercel function instance has no long-lived Realtime subscription, so no broadcast evicts its cache. Bound the staleness with maxStaleMs instead, and evict after the process's own writes:

src/server/permdock.ts
import { instanceCache, memoryVersionCache } from "permdock";
import {
  authorizationHooks,
  authorizer,
  permdockFor,
} from "permdock/better-supabase";
import { createServer } from "better-supabase/server";

const versions = memoryVersionCache({ maxStaleMs: 5_000 });
export const permdock = permdockFor({
  policy,
  memberships,
  versions,
  instances: instanceCache(),
});
export const server = createServer(bsb, {
  versions,
  authorizer: authorizer({ policy, permdockFor: permdock }),
  authorization: authorizationHooks({ policy, claims, permdockFor: permdock }),
});

Create all of it at module scope, so warm invocations of the same instance reuse the cache. A read check answers the version from the cache for up to maxStaleMs; a write check reads it live, so a removed member loses write access at once and read access within maxStaleMs. Pick maxStaleMs as the longest a revoked read may last.

After a write that changes a user's roles or memberships, call await server.evictSession(userId) in the same function. It evicts the user from versions, so the next request in this instance reads the new version. Other instances still answer from their cache until maxStaleMs passes.

Storage and Realtime

import { defineBucket } from "better-supabase/storage";
import { bucketPolicy } from "permdock/better-supabase";

export const documents = defineBucket({
  id: "documents",
  path: "{organizationId}/{name}",
  policy: bucketPolicy(
    { read: permissions.documents.browse, write: permissions.documents.upload },
    { policy, scope: "organization" }, // or { manifest, catalog, scope }
  ),
});

Pass policy when the bucket file can import the app's policy: no JSON file is read at runtime, and bucketPolicy fails at definition time on a key with a conditioned grant. Pass manifest and catalog when the file cannot import the policy, for example because the policy module does not load where better-supabase reads its config.

A permission's row conditions (such as ownerId = principal.id) are applied by the table policies, not by the helpers, so bucketPolicy refuses a key the catalog marks rowConditions: true. Grant browse-style permissions per scope with no row condition for objects. permdock doctor PD037 reports a storage.objects or realtime.messages policy that calls a helper for such a key.

API keys

PermDock parses better-supabase keys only when the block uses PermDock's prefix: pass prefix: "pdk" to createApiKeys. The format is the same, checksum included. The credential's id is the key's public id, the part between the prefix and the secret.

Use apiKeyClaimOptions where better-supabase turns a key into a token, so the token carries the claims the helpers read:

import { apiKeyResolver, createApiKeys } from "better-supabase/blocks/api-keys";
import { apiKeyClaimOptions } from "permdock/better-supabase";

const keys = createApiKeys({ transport, prefix: "pdk" });
const resolver = apiKeyResolver({
  keys,
  ...apiKeyClaimOptions(manifest),
  serviceRoles: () => ["integration"],
});

Use apiKeyVerifier where PermDock reads the key itself, for example a route outside better-supabase's middleware:

import { apiKeyVerifier } from "permdock/better-supabase";
import { subjectFromApiKey } from "permdock/server";

const subject = await subjectFromApiKey(request.headers.get("x-api-key"), {
  verifier: apiKeyVerifier({
    keys,
    manifest,
    allPermissions: Object.values(permissions),
  }),
  permissions,
});

permdock/server exports an apiKeyVerifier too, over PermDock's own key store. This one reads better-supabase's api_keys table instead; import the one that matches where the keys live.

When better-supabase's middleware already verified the key, the session is kind: "apiKey". Pass apiKeys to subjectFromBetterSupabase to map it the same way:

const subject = subjectFromBetterSupabase(session, {
  apiKeys: { permissions, manifest },
});

MCP tools

Give createMcp the authorizer and set permission on each tool: tools/list hides the tools the authorizer denies, and a call is checked after its arguments validate. toolPolicy is the route for a permission checked on the row data returns.

permdock/mcp wraps the official MCP SDK's server, so it cannot wrap better-supabase's createMcp. With createMcp, put the permission in each tool's meta and spread toolPolicy into the options. A tool without a permission is hidden and refused. A denial's reason names the permission key and the first denial reason, as the authorizer's does. A check that throws refuses and reaches onError:

supabase/functions/mcp/index.ts
import { createMcp } from "better-supabase/mcp";
import { getPermDock } from "permdock";
import {
  subjectFromBetterSupabase,
  subjectFromShareLink,
  toolPolicy,
} from "permdock/better-supabase";
import { betterSupabase } from "../_shared/supabase.ts";
import { permissions, policy } from "../_shared/policy.ts";

type Auth = Parameters<typeof subjectFromBetterSupabase>[0];
type Instance = Awaited<ReturnType<typeof getPermDock>>;

// One PermDock instance per request: `visible` runs once per tool.
const instances = new WeakMap<object, Promise<Instance>>();
function permdockFor(ctx: { auth: Auth }): Promise<Instance> {
  let permdock = instances.get(ctx.auth);
  if (!permdock) {
    permdock = getPermDock(policy, subjectFromBetterSupabase(ctx.auth));
    instances.set(ctx.auth, permdock);
  }
  return permdock;
}

const server = createMcp(betterSupabase, {
  name: "crm",
  version: "1.0.0",
  advertisedScopes: ["openid"],
  ...toolPolicy({
    permdock: permdockFor,
    onError: (error, { permission }) => console.error(permission, error),
  }),
}).tool({
  name: "export_customers",
  description: "Export the organisation's customers as CSV.",
  meta: permissions.customers.export,
  run: (_args, { db }) => db.customers.list(),
});

visible uses mayUse, so a tool is listed when some grant could apply, including one with a row condition. A page that lists many tools reads them in one pass with permdock.mayUseMany(permissions), which returns a boolean[] in order from one snapshot read. authorize decides with decide on the row data(ctx, tool, args) returns, or on no row, which a row-scoped permission denies; check those inside run or rely on RLS. A permission that needs approval is refused, because better-supabase's tool decision has no approval outcome. A tool that declares permission instead goes through authorizer, which with a store refuses with the approval id and resumes the retry (Approval resume). For an approval flow inside MCP itself, serve those tools through permdock/mcp on the official SDK, with better-supabase's createMcpAuth from better-supabase/mcp/sdk for the bearer token and metadata. tests/better-supabase/mcp.test-d.ts type-checks this recipe against better-supabase/mcp.

Credentials

credentialGuard wraps a better-supabase CredentialProvider, the interface its AI and integration blocks fetch third-party tokens through. Every getToken, startAuthorization and completeAuthorization is decided against use, and revoke against revoke or use, with the CredentialRef as the row. A denial or a failed check returns a forbidden error with hint PERMDOCK_DENIED; capabilities and verifyInbound pass through.

import { credentialGuard } from "permdock/better-supabase";

const credentials = credentialGuard(vault, {
  permdock: () => permdockFor(request),
  use: permissions.integrations.use,
  revoke: permissions.integrations.manage,
});

Build it per request, with that request's PermDock. testCredentialProvider from better-supabase/testing accepts the guarded provider.

Workflows

better-supabase/workflow-sdk checks a permission key before a workflow hook resumes and before a web handler runs. hookCan and handlerCan answer both with decide, on no row unless data loads one:

import { authorizeHook, protectWebHandler } from "better-supabase/workflow-sdk";
import { handlerCan, hookCan } from "permdock/better-supabase";

await authorizeHook(hook, { can: hookCan(await permdockFor()) });

export const POST = protectWebHandler(handler, {
  permission: "invoices.approve",
  can: handlerCan({ getPermDock: (request) => permdockForRequest(request) }),
});
  • hookCan(permdock) grants only when the caller is a member of the hook's tenant and the permission its hookMetadata names is granted there.
  • handlerCan returns undefined, which better-supabase answers with 401, when the request has no signed-in principal or getPermDock throws. Otherwise it decides in the request's active tenant, and a denial is 403.
  • An unknown key, approval-required and a throw are false.
  • Without data, a permission with a row condition denies. hookCan(permdock, { data: (tenant, key) => row }) and handlerCan(source, { data: (request, key) => row }) load the row first, so the condition decides on it; a throwing data is false.
await authorizeHook(hook, {
  can: hookCan(permdock, {
    data: (tenant, key) => runs.get(tenant, hook.metadata.runId),
  }),
});

A better-supabase workflow run belongs to a record: its subject is a RecordRef, stored as the bsb.subject attribute (type/id), and the workflow editor starts a run on one with start(subject_type, subject_id). workflowResource(subject, types) maps it to the resource PermDock's start takes, so the run's permissions on that type hold on that row only (bind a run to a record). types maps each config.recordTypes type to the PermDock resource name:

import { workflowResource } from "permdock/better-supabase";

const target = workflowResource(run.subject, {
  invoice: "invoice",
  deal: "crm_deal",
});
if (!target.ok) return target.decision; // denied, reason "validation"
await workflow.start("chase-invoice", {
  caller: permdock,
  resource: target.resource,
});

A subject type types does not name (own keys only), a missing or empty id, or an id over 256 characters returns { ok: false, cause: "validation", decision }; the run never starts on a record PermDock cannot name.

tests/better-supabase/workflow.test-d.ts type-checks both against better-supabase/workflow-sdk.

Support sessions

supportPolicy is the authorize option of better-supabase's supportSessions. It decides each start with decideSupportSession as the admin, in the requested tenant:

import { supportPolicy } from "permdock/better-supabase";

const support = supportSessions({
  authorize: supportPolicy({
    policy,
    options: { settings }, // the tenant's supportSessions rules
    approved: async (_input, pending) => approvals.find(pending.token),
  }),
});
  • The admin's verified claims become the subject, and a principal whose id is not admin.user.id is refused.
  • A read-only start gets every readOnlyHint permission the admin can use. readOnly: false is refused unless writable lists the session's permissions.
  • metadata.reference becomes the request's reference, for settings that require a ticket.
  • An approval-required start passes once approved(input, pending) returns { approvedBy } for pending.token, and decideSupportSession refuses an approver who is the admin. The token is bound to the admin, target, tenant, reason and mode, so a retried start gets the same token. approval: false skips approval.
  • denied, a missing approval and a throw are false.

supportPolicy holds no approval of its own, so the app records approvals and looks them up in approved.

Approvers

approvers names who may approve each kind of request better-supabase holds for approval. The kinds are 'ai-tool' for a tool call, 'support-session' for a support session, and '<subject type>.<action>' for the approvals block:

better-supabase.config.ts
import { anyOf, holder, user } from "permdock";
import { authorizationProvider } from "permdock/better-supabase";

authorizationProvider({
  manifest,
  catalog,
  approvers: {
    "ai-tool": holder(permissions.tools.approve),
    "support-session": anyOf(
      holder(permissions.support.approve),
      user(securityLead),
    ),
    "invoice.send": holder(permissions.invoice.approve),
  },
});
  • isApprover is one case over the kind. Each branch calls permdock_is_approver with that kind's approvers and the request's tenant. A kind approvers does not name answers false.
  • better-supabase refuses the requester before it asks, so nobody approves their own request.
  • For tool calls and support sessions, isApprover replaces the module's default approver. Leave 'support-session' out and only the service role can approve a support session.
  • permdock_is_approver checks user() by id and holder() through permitted_<root scope>_ids_by_permission in the tenant, and manager() with rls.approvals.managers. A role, relation or other grantee approver matches nobody in SQL and is a problem, as is manager() without rls.approvals.managers. So is a holder() key the catalog lacks, and a tenant scope that is not the root scope.
  • With rls.approvals.delegations, the manifest lists the four-argument permdock_is_approver, and each branch also passes better-supabase's {requester} and the kind's resource, so a delegate inside an active cover matches.
  • requestApprovers: true also passes better-supabase's {approvers}, the approvers of the request's current step, to the five-argument permdock_is_approver, and a kind approvers does not name calls it too (covers for policy approvers). It needs rls.approvals.delegations or rls.approvals.managers, and a better-supabase release that fills {approvers}.

Manager approvers

manager({ levels? }) matches in SQL when rls.approvals.managers names the app's table of reporting lines. With managers set, the two-argument permdock_is_approver(p_approvers, p_tenant) also answers manager; without it, that overload is unchanged and a manager approver matches nobody:

permdock.config.ts
export default {
  permissions: "./permissions.ts",
  policy: "./policy.ts",
  rls: {
    dialect: "supabase",
    approvals: {
      managers: {
        table: "public.reporting_lines",
        user: "user_id",
        manager: "manager_id",
        tenant: "organization_id",
      },
    },
  },
};
  • permdock rls generate writes permdock_manages(p_requester, p_levels), a recursive walk up table from the requester's row. It stops after levels steps, at most 8, and never revisits a user, so a cycle in the table ends the walk. No client role may execute it.
  • It also writes the four-argument permdock_is_approver, which decides manager leaves through permdock_manages and every other leaf as the two-argument form does. A levels outside 1 to 8 matches nobody. The requester never manages themselves into an approval, even when the table names them as their own manager.
  • The table must exist before the generated SQL runs, because permdock_manages is a SQL function whose body Postgres checks on create. Its rows are read as the function owner, so the table needs no policy for authenticated.
  • Rerun permdock supabase inspect --out. authorizationProvider sees permdock_manages in the manifest and passes {requester}.
  • With delegations: true as well, the caller's own check includes manager(), and a cover passes a manager() leaf when the delegator manages the requester within levels, through permdock_manages_for(p_user, p_requester, p_levels). No client role may execute it.
  • authorizationHooks({ approvers }) decides manager() in process through the relations source in its options or its permdockFor, reading manager on the requester's user record as manager() does.

tests/integration/src/approval-managers.test.ts runs the walk on Postgres: levels, a cycle, the requester, lists and covers.

With managers set, permdock rls generate also writes permdock_request_approver_ids(p_requester, p_tenant), with p_resource text default null after them when delegations is on: the requester's managers up the chain, at most 8 steps, plus each delegate inside an active cover of one of them. A cover counts only in its own tenant (or with none), only for a resource its resources lists (or with none), and never when it lists permissions, so a cover for leave requests grants nothing on expenses. Without p_resource only a cover for every resource counts. The requester is never in the set. authorizationProvider fills approverFor from it as permdock_request_approver_ids({requester}, {tenant}, pg_catalog.split_part({kind}, '.', 1)), the same resource permdock_is_approver gets, so the leave, expense and time-entry blocks need no *_chain_decides decider.

Self-referencing manager tables

An app whose employees table names each row's manager row writes that table instead of an edge table:

permdock.config.ts
export default {
  rls: {
    approvals: {
      managers: {
        table: "public.employees",
        id: "id",
        reportsTo: "manager_employee_id",
        user: "user_id",
        tenant: "organization_id",
        active: { status: "status", inactive: ["ended"] },
      },
    },
  },
};

The walks join the table to itself through reportsTo and keep the rows active admits: a status in active, not in inactive, or both. A with recursive walk with a depth cap of 8 and a cycle guard answers each helper; no closure table is needed. Besides the user helpers this form writes four row helpers:

HelperAnswers
permdock_manages_row(p_row)Whether one of the rows above p_row belongs to the caller
permdock_managed_row_ids_in(p_tenant)The rows below the caller's rows in one tenant
permdock_managed_row_ids()The rows below the caller's rows in every tenant
permdock_accessible_row_ids(p_permission)The caller's own rows, the rows below them, and every row in a tenant where the caller holds p_permission

The caller's own rows are never in a managed set, so a self-decision stays refused. The two set helpers have distinct names and no overload, which pg-topo needs to order them. permdock codemod manager-chain replaces hand-written walks of the same table: it matches each function in supabase/schemas to a helper by signature, rewrites every call site, in policies and in function bodies, and deletes the definition with its grants. A walk whose status filter differs from active stays, and the report names the difference.

Approval delegation

When both libraries are installed, PermDock owns approval delegation. Configure out-of-office covers once, in PermDock, and leave better-supabase's own delegation unused:

permdock.config.ts
export default {
  permissions: "./permissions.ts",
  policy: "./policy.ts",
  rls: {
    dialect: "supabase",
    authorize: "database",
    approvals: { delegations: true },
  },
};
  • rls.approvals.delegations writes approval_delegations in the helper schema. Each row is a cover: a delegator, a delegate, an optional tenant, optional resources, and a required from and until window. A signed-in user reads the covers they gave or received, and writes only their own, in a tenant they belong to.
  • It also writes a four-argument permdock_is_approver(p_approvers, p_tenant, p_requester, p_resource). The check passes when the caller matches the approvers. It also passes for a delegate inside an active cover whose delegator matches them. The delegator must not be the requester, and the delegate must be a member of the tenant. The two-argument form keeps no covers.
  • Rerun permdock supabase inspect --out. authorizationProvider sees the four-argument helper in the manifest and passes {requester}, which better-supabase fills for the approvals block, AI tool calls and support sessions.
  • tableApprovalDelegationSource({ query }) from permdock/supabase reads the same rows as approvalDelegations for approvalsHandler, so an approval decided in process and one decided in SQL follow the same covers.
  • A cover is checked against the delegator's own rights, one hop: the delegator's covers are never followed. A holder() approver through a cover needs rls.authorize: "database", where permdock_has_permission_for and permitted_<scope>_ids_by_permission_for exist. In jwt mode only user() approvers pass through a cover. A cover with permissions set matches only in approvalsHandler, because the SQL check has the request kind but not its permission. permdock_approver_for_ids() has no tenant or resource to match, so it follows only covers with no tenant, resources or permissions; call permdock_approver_for_ids(p_tenant, p_resource) in a policy to follow the covers of one tenant and resource (a null p_resource takes only covers for every resource).
  • rls.approvals: { store: false, delegations: true } writes the covers and the approver checks without PermDock's approval store, for an app whose requests live in the approvals block. store: false with table or another option of an adopted store is refused.

Covers for policy approvers

The approvals block names approvers in its policies: users, manager: true and a permission. permdock rls generate with delegations or managers also writes a five-argument permdock_is_approver(p_approvers, p_tenant, p_requester, p_resource, p_request_approvers), where p_request_approvers is the block step's approvers object. It runs the four-argument check over p_approvers and the step's users, manager and permission, so a cover reaches a user a policy names and the requester's manager, whether or not they hold a permission:

better-supabase.config.ts
authorizationProvider({ manifest, catalog, requestApprovers: true });
  • Every kind, including one approvers does not name, calls the five-argument form with pg_catalog.split_part({kind}, '.', 1) as the resource. A step's role and team match nobody through a cover.
  • The cover rules stay: an active window, the cover's tenant and resources, a delegate who is a member of the tenant, and a delegator who is not the requester. A cover outside its window or scope grants nothing.
  • Set requestApprovers only with a better-supabase release whose isApprover fills {approvers}. Without it the template has a placeholder better-supabase does not know.
  • authorizationHooks({ approvers }) checks the kinds' approvers only. better-supabase requires both checks when the hook is set, so leave it out for kinds whose covers come from policy approvers.

The approvals block

blockApprovalStore(approvals, options?) and blockApprovalPolicySource(approvals, options?) take createApprovals(...) from better-supabase/blocks/approvals, so PermDock asks for approval where the block holds the requests and the tenant and platform policies:

import { approvalPolicies } from "permdock";
import {
  blockApprovalPolicySource,
  blockApprovalStore,
} from "permdock/better-supabase";

const store = blockApprovalStore(approvals, { tenantless: true });
const permdock = await getPermDock(policy, user, {
  approvalPolicies: approvalPolicies(
    blockApprovalPolicySource(approvals, {
      platform: true,
      permissions,
      effects: { "money-movement": ["spend"] },
    }),
  ),
});
  • blockApprovalStore files each approval-required decision as a block request on the resource, under the permission's action, with the PermDock request in payload.permdock and its fingerprint. consume calls the block's consume, which refuses a second use and another fingerprint. get, getById and list read the block's latest 2,000 requests in its tenant; a cancelled request reads as rejected.
  • With tenantless: true, a request whose subject has no tenant is filed with request(..., { tenantless: true }), and get, getById and list also read the latest 2,000 requests without one. The resource's type must be in the block's options.tenantless.
  • resolve checks the verdict against the PermDock request as any store does, then calls the block's approve or reject with decidedBy set to the approver, so approvalsHandler works over a service-role client and the block records the user who decided. The block still refuses the requester. A client without approve and reject makes resolve throw.
  • blockApprovalPolicySource reads listPolicies, and with platform: true also listPolicies({ platform: true }), and maps each enabled policy to ApprovalPolicy entries. A tenant policy keeps its tenant; a platform policy has none, so it applies in every tenant and to requests without one. The client must be allowed to list platform policies, or the source fails.
  • Steps become sequential stages whose approvers are any of the step's permission (holder), role (held in roleScope, default tenant), users and manager (manager()); required is the stage quorum, and required: "all" over users alone needs each of them. confirm with selfApproval becomes mode: "confirm", and expiresIn in seconds, minutes, hours, days or weeks becomes ttl.
  • conditions become a check over the call's input, or the row without one. Each rule reads one top-level field; is, is_not, eq, neq, is_any_of and is_none_of match a number and its text alike, as the block does, and gt, gte, lt, lte, between, not_between, contains, not_contains, has_any_of, has_all_of, has_none_of, empty and not_empty map to their PermDock forms. A tree with a nested path, a date or another operator is dropped, so the policy applies to every call: stricter, never looser.
  • A policy on <subjectType>.<action> keys that permission and ignores its effect, so it applies to every call of the permission. A * subject type or action with an effect PermDock knows (a PermDock operation effect, or one effects maps) matches every operation call with that effect. Without one, * expands over permissions: a key matches by the part before and after its last dot. A * policy that can do neither makes the source fail.
  • A step with only a team approver, required: "all" over anything but users, another interval format or a failed read makes the source fail, and every call an allow would grant denies.
  • approvalFingerprint from permdock returns the same string as the block's, so a fingerprint computed on either side matches.

better-supabase's approvals block keeps its own delegate_approval for apps without an authorization provider. With PermDock installed, don't configure covers there too: the provider's isApprover decides who may approve, so a cover written only in better-supabase is not consulted.

better-supabase's share-links block stores guest links: a hashed token, the subject it points at, a role, an optional expiry and a revocation. subjectFromShareLink turns a live row into a PermDock link principal, so a guest page decides with can() and reads rows under RLS through exchangeCapability, the same way as a signed PermDock link:

app/q/[token]/page.tsx
import { subjectFromShareLink } from "permdock/better-supabase";
import { getPermDock } from "permdock";
import { exchangeCapability } from "permdock/supabase";

const subject = await subjectFromShareLink(token, {
  shareLinks, // the share-links block's client, called as anon
  links: {
    quote: {
      resource: permissions.quote,
      roles: { view: ["viewer"], comment: ["viewer", "commenter"] },
    },
  },
  ttl: 300,
});
const permdock = await getPermDock(policy, subject);
if (!permdock.can(permissions.quote.read, { id: quoteId }).granted) notFound();
const db = await exchangeCapability(subject, { key, alg: "HS256", ttl: 300 });
  • links maps each share-link subject type to its PermDock resource and maps the row's role to PermDock roles. A type or role it does not name denies. The row's subject is subject: { type, id }; a row without it denies.
  • The capability holds the row's subject id and expires at the earlier of ttl (default 300 seconds, at most 3600) and the row's expiresAt. Revoking the row stops new subjects at once; a token already exchanged lasts until its ttl.
  • Every failure is the anonymous subject, so every check denies: an empty, unknown, revoked or expired token, a failed or throwing resolve, a malformed row, and a linkPolicy that refuses. So is a link pinned to a version (versionId): the capability grants the subject's current rows, so read a pinned link through better-supabase's versions.getShared(token). onAuth receives each denial with source: "share-link".
  • linkPolicy applies link rules to the capability. The row carries no issue time, so a maxLifetime rule always refuses.
  • better-supabase resolves the token in its own security definer function, which reads only the share-link table. The guest's reads of the quote itself still go through the exchanged token and RLS.

A calendar subscription or a feed reader polls one URL for months and sends no headers, so the token sits in the path. Create the link without expiresAt and maxUses: it lives until revoked, and resolve counts every poll as a use. Each request resolves the token again, so the first poll after revoke(id) gets the anonymous subject and an empty feed.

app/feeds/[token]/route.ts
export async function GET(
  _request: Request,
  { params }: { params: Promise<{ token: string }> },
) {
  const { token } = await params;
  const subject = await subjectFromShareLink(token, {
    shareLinks,
    links: {
      calendar: { resource: permissions.calendar, roles: { view: ["viewer"] } },
    },
    ttl: 60,
  });
  const jwt = await exchangeCapability(subject, { key, alg: "HS256", ttl: 60 });
  if (jwt === undefined) return new Response(null, { status: 404 });
  const events = await eventsUnderRls(jwt); // a client with `jwt` as its token
  return new Response(toICalendar(events), {
    headers: {
      "content-type": "text/calendar; charset=utf-8",
      "cache-control": "private, no-store",
    },
  });
}
  • A link with no expiry still yields a capability that ends after ttl; keep it near the poll's own duration.
  • The URL is the credential. Proxies and calendar providers log it, so offer a "reset link" that revokes the row and creates a new one.
  • no-store keeps a shared cache from serving the feed after the link is revoked.

tests/integration/src/better-supabase-share-link-feed.test.ts creates a link with no expiry, reads it under RLS on two polls, revokes it and reads nothing.

Access reviews

accessReviewApplier applies the revoked items of an access review through better-supabase's organizations and invitations blocks, then calls markApplied for each:

import { accessReviewApplier } from "permdock/better-supabase";

const apply = accessReviewApplier({
  client: supabase, // the reviewer's client
  reviews,
  policy,
  demoteTo: { admin: "member" },
  email: (userId) => directory.emailOf(userId),
});

const { applied, failed } = await apply("review_1");
  • The review's tenant is the organization argument. A revoked member moves to the demoteTo role with update_member_role when no allow grant in policy gives that role the permission at the tenant scope. Otherwise, or without demoteTo, remove_member removes the member. A role the policy does not declare, such as a custom role, counts as granting it.
  • With email, the tenant's open invitations to that address whose role grants the permission are revoked with revoke_invitation.
  • Pass the reviewer's client, so the blocks' own updateRole, removeMember and role-ceiling checks run as the reviewer.
  • A member who is no longer in the organization (ORGANIZATION_NOT_MEMBER) counts as applied. Any other error, such as ORGANIZATION_ROLE_CEILING or the owner invariant, leaves the item unapplied in failed with the message. One item's failure does not stop the others.
  • With permdockFor(principalId, tenant), the applier decides the permission again after the change. It does not mark applied an item the member still holds through another source, such as a global role.
  • schema names the blocks' schema and defaults to better_supabase. scope defaults to the policy's first scope.

Subscriber fan-out

subscriberPolicy filters the subscribers of an outbox event to those who may read it, with subscribersFor as the event's sender in its tenant:

import { principalSource, subscriberPolicy } from "permdock/better-supabase";

const audience = subscriberPolicy({
  policy,
  principals: principalSource({ claims: store.claims }),
  events: {
    "invoice.paid": permissions.invoices.read,
    "invoice.*": permissions.invoices.manage,
  },
});

const allowed = await audience(event, subscribers); // each subscriber has a `principal`
  • events maps an event type to the permission a subscriber needs: an exact type first, then the longest prefix.*, then *. A type with no entry reaches no one.
  • The row is event.payload, validated against the resource schema, or what row(event) returns.
  • The sender is event.actorId, or what sender(event) returns. An event without a tenant or sender, a sender outside the tenant and a throw reach no one.

Principals

principalSource loads principals for decideFor, subscribersFor and delivery from the claims better-supabase mints:

import { principalSource } from "permdock/better-supabase";

const principals = principalSource({
  claims: (userId, { tenant }) => store.claims(userId, { tenant }),
  identities: (identity) => links.find(identity),
});
  • principal(id) maps the claims with subjectFromBetterSupabase. Claims for another user and null claims are null, so a deleted or suspended user reaches nothing.
  • principalByIdentity exists only with identities. A { user } link loads that user, and a { contact } link is accepted only for a principal with kind: "contact". Only links the app created through a signed-in link flow or a verified address belong there.

tests/better-supabase/principals.test.ts runs testPrincipalSource from permdock/testing on it.

Authorization hooks

better-supabase asks AuthorizationHooks the questions its blocks cannot answer in SQL. authorizationHooks answers them with PermDock:

src/lib/supabase/server.ts
import { createServer } from "better-supabase/server";
import { authorizationHooks, principalSource } from "permdock/better-supabase";

const principals = principalSource({
  claims: store.claims,
  identities: links.find,
});

export const server = createServer(betterSupabase, {
  authorization: authorizationHooks({
    policy,
    claims: store.claims, // (userId, { tenant }) => the claims better-supabase mints now
    delegation: true, // OAuth client and agent tokens get the keys their scopes name
    service: (tenant) => store.serviceClaims(tenant),
    principals,
    events: { "invoice.paid": permissions.invoices.read },
    approvers: { "ai-tool": holder(permissions.tools.approve) },
    support: { options: { settings } },
    tickets: (ticket) => runs.ticket(ticket),
  }),
});

claims is optional. Without it the hooks hold apiVersion, name, sessionTags and shareKey, plus approverOf with approvers and delegation with the delegation option, but no automation or tickets, because both load a user's claims. service, support and tickets need claims; passing one without it is a type error.

  • automation.mayPublish lets a user publish an automation only with every key it uses granted to them in its tenant. automation.runAs loads the publisher's current claims, or service(tenant) for an organization-owned automation, checks every key again, and adds the automation's keys as bsb_permission_cap. A deleted or suspended publisher, a key they lost and a missing service run as no one.
  • delegation is set only with delegation: true or delegation: { permissions }; authorizationHooks({ policy }) returns { apiVersion, name, sessionTags, shareKey }. An app that relied on the implicit hook adds delegation: true. The object form replaces the scope mapping with permissions(ref), and a throw or rejection grants nothing.
  • delegation.permissions maps a token's OAuth scopes to the keys whose .scope they are or were renamed from, and to the keys a policy oauthScopes entry covers. It reads no authorization_details.
  • approverOf exists with approvers. It refuses the requester and claims whose sub is not the approver, then matches user() by id and holder() with decide in the request's tenant.
  • identities.principalByIdentity exists when principals has principalByIdentity; a contact maps to { kind: "contact" }. delivery.subscribers and delivery.audience are subscriberPolicy and exist with principals and events.
  • support.authorize is supportPolicy and exists with support.
  • tickets.subject exists with tickets. It looks the ticket up, then loads the user's current claims, so a suspended user's ticket is refused.
  • Every hook builds the subject from the claims claims loads, never from the request, and fails closed: a throw, an unknown key and approval-required refuse.

tests/better-supabase/hooks.test.ts runs testAuthorizationHooks from better-supabase/testing on them.

OAuth scopes

better-supabase narrows a delegated token (one with client_id or an agent act) inside member_can, member_can_while_deleting, platform_can and tenant_ids_with: a permission passes only when one of the token's scopes maps to it through the provider's delegation.scopes. A policy's coarse oauthScopes reach that map through the catalog:

policy.ts
definePolicy(permissions, {
  oauthScopes: {
    "mcp:read": [permissions.task.read],
    "mcp:write": [permissions.task.read, permissions.task.update],
  },
  // ...
});
permissions.catalog.json
"oauthScopes": [
  { "scope": "mcp:read", "permissions": ["task.read"] },
  { "scope": "mcp:write", "permissions": ["task.read", "task.update"] }
]

authorizationProvider merges each entry into delegation.scopes next to the per-permission scopes and the former scopes of renamed keys, so a token with scope: "openid mcp:read" passes member_can('task.read') and fails member_can('task.update'). A key the catalog does not list is dropped. Run permdock collect after changing oauthScopes; doctor PD070 warns when the catalog lacks them. tests/integration/src/better-supabase-oauth-scopes.test.ts runs that token through better-supabase's generated SQL.

PermDock's own SQL helpers (permitted_<scope>_ids, permdock_has, the table policies) narrow by token scope with rls.tokenScopes. They then read the same map through permdock_token_scope_allows, so a module check and a row policy agree about the same token. Without it, a delegated token that reaches the Data API keeps the user's row access there. deny(…, { to: actor("oauth-client") }) is the blunter rule: it refuses a key to every token with client_id or act, for writes an OAuth client must never make through PostgREST. permdock_api_key_allows reads the backend-set api_key.scopes claim, which is a different ceiling.

Agents and tool approval

better-supabase's createAgentRuntime({ toolApproval }) from better-supabase/ai-sdk/agents takes an AI SDK tool-approval function and combines it with the tenant's ask tools; the stricter answer wins. toolApproval and composeToolApproval(...) from permdock/ai-sdk are such functions: a call PermDock answers approval-required asks for the user's approval, and a denied call is refused. tests/better-supabase/agents.test-d.ts type-checks the pairing.

For Eve agents, strictestApproval from better-supabase/eve (0.81.0 or later) combines permdock/eve's approvalFor with approvalPolicy and tenantToolApproval on one tool (Eve with better-supabase).

Agent and team claims

Three claims shape what an agent or a team member reaches. PermDock and better-supabase each read some of them, in different places:

Claimbetter-supabasePermDock
act.read_onlyactor_may_write() guards module tables and its own security-definer writespermdock_actor_may_write() guards app tables under rls.readOnlyActors; in process, readOnly denies a permission without readOnlyHint
act.toolsassertToolDelegated in better-supabase/ai-sdk/agents throws AGENT_TOOL_NOT_DELEGATED before a tool runssubjectFromSupabase maps it to actor.tools; the agent kernel and adapters deny any other tool with agent-tool-not-delegated
team_idsnot read; module checks call team_ids_of(auth.uid()), which calls teamIdsOfthe hook writes it from supabase.hook.teams; conditions read principal.claims.team_ids in process; generated RLS does not read it
  • Read-only agents. authorizationProvider sets functions.actorMayWrite to permdock_actor_may_write() when the manifest lists it, so both libraries answer the same for module tables. App tables follow act.read_only only when rls.readOnlyActors is set: each write policy then gets a restrictive <table>_<verb>_read_only_actors twin. Without it, a read-only agent token still writes every app table its user may write, because the generated policies do not read act.
  • Tools. Neither check exists in SQL. A delegated tool list stops an agent at the tool call, in the server; a token that reaches the Data API directly keeps its user's row access, narrowed only by read_only.
  • Teams. team_ids is a PermDock claim, and only process-side conditions read it; RLS on team rows joins the membership table instead. authorizationProvider fills teamIdsOf with member_team_ids_of(user): from the membership sources of a team scope, or else from supabase.hook.teams. With a team scope, keep supabase.hook.teams on the same membership table, so team_ids_of() and the claim list the same teams.

An agent token also needs a policy delegation to actor("agent"); without one, permdock/ai-sdk denies every tool with no-delegation. The example delegates its owner's quotes permissions:

delegations: [
  { from: roles.owner, to: actor("agent"), permissions: [permissions.quotes] },
],

apps/examples/next-better-supabase/src/agent/tools.ts binds two tools, quotes.read and quotes.update, through permdock/ai-sdk. tests/stack/agent.stack.test.ts signs tokens through the PermDock hook against the local stack (pnpm test:stack):

Token actquotes.readquotes.update toolupdate public.quotes as the token
read_only: true, tools: ["quotes.read"]rowsagent-tool-not-delegated0 rows
read_only: true, both toolsrowsdenied0 rows
read_only: false, both toolsrowsapproved, the row changesevery row the owner may update

Module permission keys

better-supabase's SQL modules check permission keys, such as audit.read, api_keys.manage and the AI, workflow and inbox modules' keys. Its doctor reports a key the provider's permissions lacks, so pass catalog and declare each key the installed modules check in the policy. Rename a key with blocks.<block>.permissions in better-supabase.config.ts; doctor PD079 lists each key a configured block checks that the catalog lacks (doctor). The example declares the audit block's audit.read and audit.revert on an audit resource with no table: set rls.tables.audit: false, or rls generate writes policies for a public.audit table the block does not create.

The attachments and comments blocks take per-subject keys from the subject registry, recordTypes.<type>.permissions in better-supabase.config.ts: upload and manage for attachments, create and moderate for comments. Point each at a catalog key of the subject's resource, such as contracts.update for upload, so a member who may not update a contract cannot attach files to it. The registry's read stays the key for the subject row; set the files' own read in blocks.attachments.on.<type>.permissions. Without per-subject keys, any tenant member with attachments.read reads every subject's files, and better-supabase's doctor warns with BS345 when the subject table's policies check more than tenant membership.

Audit the PermDock tables

better-supabase's audit module registers a table with better_supabase.audit(target regclass, …), which creates the audit trigger and reads the table's primary key. rls.audit writes that call into the generated SQL for the custom-role tables, so every save through permdock_replace_custom_role_grants leaves an audit row:

permdock.config.ts
rls: {
  customRoles: true,
  audit: {
    function: "better_supabase.audit",
    tables: ["custom_role_permissions", "custom_role_includes"],
    args: { category: "permissions", tenant_column: "tenant_id", label_column: "role" },
  },
},

The arguments apply to every listed table, so user_roles, which has no tenant_id, needs a second call of your own or no tenant_column. Apply better-supabase's migrations before PermDock's, because the function must exist when the call runs.

When to use bucketPolicy and topicPolicy

bucketPolicy and topicPolicy decide in better-supabase's Storage and Realtime policies through the provider's helpers, for buckets and topics defined with defineBucket and defineTopic. PermDock's own rls.storage and rls.realtime write the policies on storage.objects and realtime.messages from permdock rls generate instead. Pick one per bucket or topic: both on the same one write two policies that Postgres combines with or.

Compatibility

Each permdock release fills the provider fields its better-supabase peer floor knows. The floor is 0.87.0. The better-supabase column names the release that added the field; the floor knows every field below, and authorizationProvider returns better-supabase's own AuthorizationProvider type. A field whose helper the manifest does not list stays unset.

Provider option or fieldpermdockbetter-supabaseNotes
memberships[].disabledAt0.25.00.53.0Filled from the membership source's disabledAt column.
platformRoles0.25.00.53.0Filled from rls.roles when the manifest lists permdock_can_assign_any; platformRoles: false leaves it out.
functions.subject0.25.00.53.0Names permdock_subject(); subject: false leaves it out.
functions.memberIdsFor0.25.00.53.0Names member_<scope>_ids_for. From 0.26.0 the helpers file grants it to supabase_auth_admin wherever it writes the function, with or without a hook.
personas: "roles"0.26.00.58.0Sent as written, with one fixtureRoles entry per role the manifest's fixtureRoles lists; permdock supabase inspect writes that list.
functions.subjectForTenant0.26.00.58.0Names permdock_subject(p_tenant), which answers null for a tenant the caller is no member of; subject: false leaves it out.
functions.bootstrapPermissions0.26.00.58.0Names permdock_bootstrap_permissions(p_tenant), the compact BootstrapPermissionsWire.
functions.canIn0.26.00.58.0The set form over permitted_<scope>_ids_by_permission, so an access policy makes no per-row call.
functions.approverFor0.26.00.58.0Never set from 0.31.0: better-supabase reads it as the users who may decide a request, and permdock_approver_for_ids() always holds the caller.
functions.managedUsers0.26.00.58.0Names permdock_managed_user_ids({tenant}) when the manifest lists it; better-supabase fills {tenant}.
permissions[].levels0.26.00.58.0Filled from the catalog's levels.
tokenHook.teamIdsTruncatedClaim0.26.00.58.0Set when the hook writes team_ids.
functions.roleIn0.29.00.77.0roleIn: true names permdock_role_in({role}, {tenant}) when the manifest lists it. Off by default.
roleSources[].role.through.tenant, platformRoles.through.where0.31.00.84.0From rls.customRoleWrites.roles tenant, scope and globalScope; canAssign asks at 'global'.
functions.portalSubjects, functions.portalParties0.31.00.84.0portalParties from a child scope whose memberships name via; portalSubjects only with portalSubjects: true.
versions0.31.00.84.0The hook's authz_version_for when authzVersion is on.
wildcards0.31.00.84.0'none' with a catalog whose keys hold no *.
operations[].approval0.31.00.84.0<resource>:<action> floors from the catalog's approvals.
doctor0.31.00.84.0permdock doctor --format findings, with timeoutMs from the doctor option.
actionKeys0.31.00.84.0Filled from the catalog's answers.

definePermDock(...).next().getSnapshot arrives in 0.26.0 (one tenant's snapshot). Pin both packages to the pair a release lists, and update the table in the same pull request as a provider change.

Sessions and actors

  • better-supabase's verifySession(sql, auth) checks that a token's session is still in auth.sessions. Call it before a sensitive action and pass the result as liveSession (live sessions).
  • A support session and actingAs write act with kind: "support" or "impersonation", so the subject's actor has that kind and every call denies with no-delegation until the policy names the actor in a delegation (support and impersonation actors).
  • The scopes guard answers 403 insufficient_scope before PermDock runs; PermDock's delegation narrowing still applies after it.
  • Only allow: ["anonymous"] admits a signInAnonymously() user past a guard. Pair the default allow: ["user"] with anonymousSignIns: "deny" (anonymous sign-ins).

Testing

testAuthorizationProvider and testAuthorizationHooks from better-supabase/testing check the provider and the hooks against the contract; tests/better-supabase/provider.test.ts runs it on the provider built from a fixture manifest. tests/integration/src/better-supabase-provider.test.ts applies the example's migrations to Postgres and checks that every requires entry exists with its grant and every template runs at every scope. tests/integration/src/better-supabase-assignments.test.ts runs the canAssign templates against PGlite for declared and custom roles. supabaseClaimFixtures.tenantPlans in permdock/testing is a token with features claims for subjectFromBetterSupabase.

Example app

apps/examples/next-better-supabase: better-supabase on Next.js 16.4 with Cache Components. It runs on better-supabase 0.87.0.

  • better-supabase.config.ts passes authorizationProvider the example's permdock.manifest.json and permissions.catalog.json with tables, widened and sharedFunctions, sets blocks.permissions.model: "provider", and sets canAssign to false because its membership tables are service-only.
  • src/lib/supabase/server.ts passes authorizer({ policy, memberships, version, intent }), authorizationHooks({ policy, widened }) and the shared versions cache to createNext. memberships comes from the generated source factory, version is authzVersion({ query }), and intent makes a read, list or view permission read and every other check write. src/proxy.ts calls bsb.proxy and mayAccess.
  • src/lib/supabase/index.ts validates sessions with supabaseClaims().extend(appClaims). Bearer routes map the verified token with subjectFromBetterSupabase or subjectFromJwt.
  • supabase/schemas/public/functions/feature_claims.sql adds public.feature_claims(user_id), which reads organization_features for the organizations permdock.member_organization_ids_for(user_id) returns. permdock.config.ts registers it as the features claim.
  • The share-links block requires better-supabase's memberships block. blocks.memberships maps onto the app's public.organization_memberships table, and src/sources.ts reads the same table with blockMembershipSource, so the block and the token hook share one set of rows. The example installs no organizations block, so it sets no assignmentGuard.
  • src/app/[locale]/share/[token]/page.tsx is the guest quote page. src/lib/share.ts resolves the token with subjectFromShareLink, checks quotes.read for the link-only guest role and reads the quote under RLS with the exchangeCapability claims (rls.capabilities). The seed's link opens at /en/share/acme-initech-rollout.
  • rls.approvals.delegations writes approval_delegations, and the seed gives Mason a 30-day cover for Olivia's Acme approvals.
  • supabase/tests holds pgTAP tests over the seeded tenants, and tests/claims.test.ts maps every claim fixture through better-supabase's createServer.
  • Supabase: the claims, helpers and middleware this entry builds on.
  • Supabase token hook: the one hook and supabase.hook.claims.
  • RLS adapter: the SQL helper contract the provider's templates call.

Last updated on

On this page