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
authorizationprovider, a bucket or topic takes anaccesspolicy, 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 waypermdock/better-authfills 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 --outalready writespermdock.manifest.jsonwith the helper schema, the scopes, the membership tables and the hook's claims.authorizationProvidermaps that file to the contract, so better-supabase's SQL and doctor follow the helperspermdock rls generatewrote without reading a PermDock file themselves. - The slot types come from
better-supabase/contract, the types-only entry better-supabase versions withContractApiVersion. The entry never imports a runtime entry such asbetter-supabase/configorbetter-supabase/mcpfor 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.truncatedClaimfor itspermissionsreaders andbudget.truncatedClaimfor doctor's budget check, and its conformance kit requires them to agree. PermDock's hook writes onlymemberships_truncated, so the provider names it in both: a token whose memberships were cut makespermissionsOfask the database, which fails closed. permdock/supabasestays plain Supabase. It names no better-supabase identifier, and an app on@supabase/supabase-jsor@supabase/serveralone never loads this entry.
Who owns what
| Concern | Owner |
|---|---|
Token verification (@supabase/server), sessions, refresh and the AuthSession shape | better-supabase |
| Typed clients, repositories and typegen | better-supabase |
Storage and Realtime plumbing (defineBucket, defineTopic), jobs and webhooks | better-supabase |
MCP protected-resource metadata and the scope guards (createMcp, createMcpAuth) | better-supabase |
| Token lifetime, refresh-token reuse, signing keys, splinter and claim size lints | better-supabase |
The claim contract: user_role, roles, memberships, the active-tenant claim, attrs, authz_ver, memberships_truncated | PermDock |
The one token hook (permdock supabase hook generate) | PermDock |
role_permissions, authorize(), the SQL helpers and the table policies | PermDock |
Building each access request from the verified context, and the permission option of routes, actions and tools | better-supabase |
Deciding each request (authorizer), and tool and route authorization | PermDock |
| Share-link rows: creating, hashing, expiring and revoking them | better-supabase |
The guest subject a share link becomes, and its reads under RLS (subjectFromShareLink) | PermDock |
| Approval delegation (out-of-office covers) when both are installed | PermDock |
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'sAuthorizationProvider(apiVersion: 1,name: "PermDock").manifestispermdock.manifest.json, parsed or as JSON text;catalogispermissions.catalog.json. Without a catalog the provider lists no permissions, so better-supabase refuses every key a bucket, topic or module checks, andproblemsasks for it.scopenames the tenant scope and defaults to the manifest's one root scope.- Its
functionscallpermitted_<scope>_ids_by_permission,member_<scope>_ids,permdock_has_permissionand their_forforms inrls.schema. These take a permission key and subtract the instances a deny of it reaches, so a permission split into#ngrant keys still matches.permissionsForcallspermitted_<scope>_permission_keys_for, so better-supabase'smember_permissionslists a member's keys; like the other_fortemplates it is set only when the manifest lists the helper, whichrls.mode: 'database'writes. canAssignandcanAssignForcallpermdock_can_assignandpermdock_can_assign_for. When the manifest'srls.customRolesis set and the tenant scope is a root scope, they callpermdock_can_assign_anyandpermdock_can_assign_any_forat the tenant scope instead, so better-supabase'scan_assignandcan_assign_asalso answer for a custom role.roleSourcesread each membership's role through its roles table withtenantset torls.customRoleWrites.roles.tenant. When that table has ascopecolumn,whereis{row}.<scope> = '<membership scope>'; without one, it is the catalog's roles at that scope or any row with a tenant.platformRolescomes fromrls.roles:canAssignandcanAssignForaskpermdock_can_assign_anyat the'global'scope with no tenant, andthrough.whereis{row}.<scope> = '<globalScope>'whenrls.customRoleWrites.rolessetsscopeandglobalScope. better-supabase then fillsblocks.memberships.options.roleThroughandblocks.invitations.options.platformRolesfrom them, and doctor PD094 reports a copy left in the config.- With
roleIn: true,roleInispermdock_role_in({role}, {tenant})when the manifest lists it (rls.customRolesindatabasemode) and the tenant scope is a root scope. Withblocks.memberships.options.roles.many, better-supabase's trigger onmembership_rolesthen refuses a role that is neither declared nor a custom role of the row's tenant, such as another organization's custom role, with SQLSTATE23514andMEMBERSHIP_ROLE_SCOPE. It is off by default so a provider built from an older manifest keeps its output;problemsreportsroleIn: truewithout the helper. holdersOfispermitted_<scope>_users(permission, tenant), the user ids holding a permission in a tenant, for a notification's audience.actorMayWriteispermdock_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 inrequires.teamIdsOfismember_<scope>_ids_of(user)for a scope namedteamorteams. Withblocks.permissions.model: 'provider', better-supabase'steam_ids_of()and the team-sharing policies ofsaved-viewsandcollectionscall 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 withTEAM_FORBIDDEN; the service role and direct database sessions still pass through. It is set when the manifest lists the helper.permdock rls generatewrites it for a team scope with membership sources; without one,permdock supabase hook generatewritesmember_team_ids_offromsupabase.hook.teams(teams). With neither, a scope directly within the tenant scope whose memberships name noviais the team scope when it is the only one, read through the caller-boundmember_<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. Otherwiseteam_ids_of()reads the teams block, and doctor reportsBS417.permittedanswers better-supabase'spermitted(resource, id, permission): for a resource that names a scope, whetheridis amongpermitted_<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 marksrowConditions: false; a key with row conditions isfalsethere, so its table policies decide.operationslists each catalog operation as better-supabase tools: a name without a dot becomesai.tool.<name>andmcp.tool.<name>, and a dotted name is used as written.risk: 'critical'maps tohigh, and the effectssendandspendtoexternal. A permission whose code allows require an approval (the catalog'sapprovals) adds<resource>:<action>, the name better-supabase's approvals block reads as an approval floor, withapproval.steps:byis one step and each ofstagesone step,quorumisrequired(default 1), andcombine: 'sequential'setsmode: 'sequential'. A step's approvers areuser()ids, oneholder()permission, one role at the tenant scope and a one-levelmanager(), alone or inanyOf().ttl,escalation,staleOnandmodehave no counterpart and are left out. A"human"approval sets no floor; anallOflist, a relation approver, a role at another scope, or several different approvals on one permission set none either, andproblemsnames the permission.blocks.approvals.options.policiesentries still win.actionKeysmaps each block, record type, bucket and topic action to the permission whosemeta.answersnames it (answers), soblocks.<name>.permissionsinbetter-supabase.config.tscan go. An action two permissions answer is left out, andproblemsnames both keys. Doctor PD123 lists the installed actions no catalog key answers.delegation.scopesmaps each catalog permission's.scopeto its key, so an OAuth client or agent token grantedinvoice:readgetsinvoice.read. Each coarse scope in the catalog'soauthScopesmaps to the keys it covers (OAuth scopes). Keys are sorted by code point. A scope the catalog does not list grants nothing.delegation.interactiveOnlylists the catalog keys whose meta setsinteractiveOnly: true, sorted. better-supabase'scap_allowsrefuses them to an API key, an OAuth client and anactchain whatever their scopes, and nodelegation.scopesentry maps to them (interactive-only permissions).approveris a permission. It becomes the'ai-tool'entry ofapproversunlessapproversnames one. A key the catalog lacks is a problem.- In a project with a readable
better-supabase.config.*object export, found from the directory ofpermdock.config.tsup to the workspace root (nearest first), the CLI defaults the hook's active source toapp_metadata.<claim>, where the claim is better-supabase'sauth.tenant.claim(orclaims.tenantin a flat config), thenrls.tenantClaim, thentenant_id. An explicitsupabase.hook.activeFromor--active-fromwins. Plain Supabase keepsapp_metadata.active_<first scope>. Abetter-supabase.config.*that throws while loading, for example because it reads apermdock.manifest.jsonthat 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. activeTenantis better-supabase'sblocks.permissions.activeTenant. When the token hook reads the active tenant from another place than better-supabase writes it,problemsnames thesupabase.hook.activeFromto set:app_metadata.<tenant claim>for"claim", or the profile column for{ profileColumn }. Doctor reports the same as PD078.rowHelpers: truefills better-supabase'srowsWithandrowsWithForfrom thepermitted_<resource>_rowshelpers thatrls.rowHelperswrites and the manifest names. A better-supabase record type whose action inrecordTypes.<type>.permissionsnamesrows: "<resource SQL name>"with akeythen checks the rows the caller holds that key on, through the candidate formpermitted_<resource>_rows(permission, ids)with better-supabase's text ids cast to the manifest'sidType(uuidwhen 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 throughpermitted_<resource>_rows_for. Without row helpers in the manifest,problemsnames the step to run.tokenHook.activeOrganizationFromnames where the token hook reads the active tenant, from the manifest'shook.activeFrom:"claim"forapp_metadata.<tenant claim>, or{ profileColumn, key? }for a profile column. better-supabase's doctor BS409 warns when it differs fromblocks.permissions.activeTenant. It is"resolver"when the manifest'shook.activeTenantis"request"(supabase.hook.activeTenant), so BS409 needs noblocks.permissions.activeTenantentry andproblemsreports no mismatch. It stays unset for anapp_metadatakey other than the tenant claim, which better-supabase has no name for, and whenactiveTenantis"resolver", where the tenant comes from the request.approversmaps each better-supabase request kind touser(),holder()oranyOf()approvers and fillsisApprover, which better-supabase asks for every request that waits on an approval (Approvers). It needspermdock_is_approver, whichrls.approvalswrites; without itisApproveris unset andproblemsnames the helper. The provider never setscanApprove.portalPartiescomes from a scope directly within the tenant scope whose memberships all namevia, such as customer contacts: each(tenant, '<scope>', id)amongmember_<scope>_ids(), with the tenant read from the membership row'swithincolumn.portalParties: falseleaves it out.portalSubjects: truefillsportalSubjectsfrom the same scope: the ids thatpermitted_<scope>_ids_by_permission('<scope>.' || {action})also returns, so a guest reaches aread,commentoruploadonly 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'scustomer.readwould read every comment and internal note on their customer, unless theinboxblock hides notes. A guest source with no tenant column inwithinis left out and named inproblems, as is a missingpermitted_<scope>_idshelper. better-supabase'sguestsblock adds its own grants.versionsis<hook schema>.authz_version_forwhen the hook keeps the authorization version (supabase.hook.version, default on), so better-supabase'ssessionsblock reads PermDock's version instead of keeping its own. It answersnullfor an unknown or suspended user. The provider does not checksupabase.hook.broadcast; withbroadcast: false, noauthz:<uid>message reaches better-supabase's clients.doctor.commandis["permdock", "doctor", "--format", "findings"], so onebetter-supabase doctorrun also runs PermDock's checks and reports their findings as BS705, under one baseline.doctor: { timeoutMs }passes through asdoctor.timeoutMs; better-supabase stops the run after 60,000 ms by default. AtimeoutMsthat is not a positive whole number is left out and named inproblems. Thepermdockbin must resolve from the project root.wildcardsis'none'with a catalog whose keys hold no*: PermDock grants name exact keys, so better-supabase'spermission_matchestreats a stray*row as the literal key.scopescarry each scope'sidType:uuid,text,bigintorinteger, withint8,intandint4normalised. Any other id type is a problem.requireslists each helper with the role that must execute it;memberships,suspensionandroleSourcescome fromrls;tokenHooknames the hook function, the claims it owns and thegrantsCommandthat restores the hook's grants for the manifest'shook.schemas:permdock supabase hook generate && supabase db schema declarative sync -f permdock_hookunder pg-delta, the--grants-outcommand under migra. A manifest written withoutsupabase.hook(rls.authorize: 'database') has nohooksection, sotokenHookis absent. A manifest that cannot fill a field is recorded inproblems, which better-supabase's doctor reports, and an invalid manifest throws aTypeError.authorizer({ policy, permdockFor?, subject?, operations?, memberships?, version?, versions?, instances?, intent?, store?, onError?, options? })returns better-supabase'sAuthorizer(apiVersion: 1,name: "PermDock") for itsauthorizerserver option. It decides everypermissiona 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 vocabularyV, for absb.getClaims()snapshot, absb.bootstrap()orbsb.getAccess()result, a session or aSubject. Itssources(versions?)returns the frozen options to spread intocreatePermDockfrompermdock/next,permdock/orpcorpermdock/mcp(One instance per version).bucketPolicy(access, options)andtopicPolicy(access, options)return theaccesspolicy fordefineBucketanddefineTopic.accessmaps the operations (read,list,write,deletefor a bucket;receive,sendfor a topic) to permissions, andoptionsis{ manifest, catalog, scope, segment? }or{ policy, schema?, scope, segment? }. Withpolicy, thedefinePolicyresult 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, andschemanames the helper schema (rls.schema, defaultpermdock). The checks below are the same either way. They callpermitted_<scope>_ids_by_permissionandpermdock_has_permission, which check role and scope only and subtract denies, so a permission the catalog marksrowConditions: true(or a conditioned grant inpolicy), or does not grant atscope, throws.scope: "platform"checks a permission granted globally.apiKeyVerifier({ keys, manifest?, serviceRoles?, allPermissions? })is aCredentialVerifierover better-supabase'screateApiKeys(), forsubjectFromApiKey. A personal key is ausercredential acting as its user, a tenant key aservicecredential holdingserviceRolesin its tenant, and the key's scopes are the credential's permissions.serviceRolesdefaults to the manifest'srls.apiKeys.serviceRoles. A rotated key in its grace period verifies, and its credential'sexpiresAtis 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 tonull.apiKeyClaimOptions(manifest)returns theclaimandtenantClaimoptions of better-supabase'sapiKeyClaims()andapiKeyResolver(), from the manifest'srls.apiKeys, so a key's token carries the scopes ceiling, tenant and roles the helpers read. It throws when the manifest has norls.apiKeys.subjectFromBetterSupabase(session, options?)issubjectFromSupabaseSessionwith better-supabase's defaults:membershipsfor the memberships and the entitlements module'sfeaturesclaim forprincipal.plans. Ausersession maps throughsubjectFromSupabase. WithapiKeys: { permissions, manifest?, serviceRoles? }, anapiKeysession maps likeapiKeyVerifier's credential; without it, and foranon,serviceandinvalidsessions, the subject is anonymous.plans: { claim?, keys? }decodes the short codesentitlements.claim.keyswrites 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 theauthorizeandvisiblehooks ofcreateMcpfor tools whosemetais a permission (MCP tools).credentialGuard(provider, { permdock, use, revoke? })wraps aCredentialProviderso PermDock decides each token use (Credentials).hookCan(permdock)andhandlerCan({ getPermDock })return thecanoptions ofauthorizeHookandprotectWebHandlerinbetter-supabase/workflow-sdk;workflowResource(subject, types)maps a run'sRecordRefto theresourceofworkflow.start(Workflows).supportPolicy({ policy, subject?, options?, writable?, approval?, approved? })returns theauthorizeoption ofsupportSessions(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 aPrincipalSourceover the claims better-supabase mints (Principals).principalFromMemberships(userId, rows, { scope?, tenant? })builds a frozenPrincipalfrom rows of themembershipsblock'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'sAuthorizationHooksforcreateServer(betterSupabase, { authorization })(Authorization hooks).roleOrderFromCatalog(catalog, { scope?, owner? })returns the catalog's role keys highest first, for the SSO block'sroleOrder(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 collectThat 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:
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:
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:
- Create the memberships table in the app's own schema file, one row per member:
(organization_id, user_id, role). - 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 itsbsb_policies and triggers. - 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. - Point PermDock's sources at the same table with
blockMembershipSource.
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:
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:
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:
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.
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
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:
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
subjectFromBetterSupabaseoversubject.properties.claims, the verified access-token claims. Auseror a delegatedagentsubject maps through them.anon,service, a missingclaimsand anything else is the anonymous subject, so every check denies. context.tenantselects the active tenant only among the memberships the claims hold. A tenant with no membership is no tenant.resource.propertiesis the row, anddecidetreats it as untrusted data: aclaimsormembershipskey in it changes nothing. A row better-supabase loaded itself (source: "loaded") skips schema validation; a row from the request (source: "input", or nosource) is validated against the resource schema.resource.changeis a write. A create ({ next }) decides on the new values. An update ({ current, next }) decides on the stored row and on the stored row withnextover 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 outcome | better-supabase outcome |
|---|---|
granted | granted |
denied | denied with the permission key and the first denial reason as the reason |
approval-required | approval-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
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:
| Check | Intent |
|---|---|
The intent option is set | its answer |
better-supabase sets context.intent (read or write) | context.intent |
A write whose context.enforcement is rls | database-write |
evaluations: list filtering and per-row checks | read |
evaluate of a permission whose action is read, list or view | read |
Every other evaluate: actions, mutations, route guards | write |
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:
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
forbiddenerror carryingapproval.id. The approver decides it throughapprovalsHandler. - The client retries with
PermDock-Approval: <approval.id>. better-supabase passes the header ascontext.approval, andevaluategrants 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.
evaluationsnever 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:
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:
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 callsversions.evict(userId), so the next PermDock instance reads the version live.authorizationHookssetssessionTags(userId)to[snapshotTag(userId)], so it also clears the user's cached PermDock snapshots, as sign-out andrefreshSessionCachedo.- better-supabase passes
authorizera request-scopememo, and the checks of one scope share one PermDock instance per claims, tenant and intent. Withinstances, requests share it too. bsb.getClaims()verifies the token once per request and returns aSessionSnapshot.subjectFromBetterSupabase(snapshot)maps it like the user session of its claims, withiatasSubject.issuedAtandauthz_verasprincipal.authzVersion. A snapshot whoseclaims.subis not itsuserIdmaps 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:
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:
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.
async function QuotesIsland({ orgId }: { orgId: string }) {
"use cache: private";
const access = await permdock(await bsb.getClaims(), { tenant: orgId });
// …
}| Input | Subject | Version |
|---|---|---|
bsb.getClaims() snapshot or a session | subjectFromBetterSupabase(input, subject) | The token's authz_ver, checked through versions |
bsb.bootstrap() result | Its session; anonymous when sessionActive is false | authzVersion as version.known, no read |
bsb.getAccess() result | Its session, in its tenant | authzVersion as version.known, no read |
Subject | As given | Through 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:
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:
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:
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 itshookMetadatanames isgrantedthere.handlerCanreturnsundefined, which better-supabase answers with 401, when the request has no signed-in principal orgetPermDockthrows. Otherwise it decides in the request's active tenant, and a denial is 403.- An unknown key,
approval-requiredand a throw arefalse. - Without
data, a permission with a row condition denies.hookCan(permdock, { data: (tenant, key) => row })andhandlerCan(source, { data: (request, key) => row })load the row first, so the condition decides on it; a throwingdataisfalse.
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.idis refused. - A read-only start gets every
readOnlyHintpermission the admin can use.readOnly: falseis refused unlesswritablelists the session's permissions. metadata.referencebecomes the request'sreference, for settings that require a ticket.- An
approval-requiredstart passes onceapproved(input, pending)returns{ approvedBy }forpending.token, anddecideSupportSessionrefuses 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: falseskips approval. denied, a missing approval and a throw arefalse.
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:
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),
},
});isApproveris onecaseover the kind. Each branch callspermdock_is_approverwith that kind's approvers and the request's tenant. A kindapproversdoes not name answersfalse.- better-supabase refuses the requester before it asks, so nobody approves their own request.
- For tool calls and support sessions,
isApproverreplaces the module's default approver. Leave'support-session'out and only the service role can approve a support session. permdock_is_approverchecksuser()by id andholder()throughpermitted_<root scope>_ids_by_permissionin the tenant, andmanager()withrls.approvals.managers. A role, relation or other grantee approver matches nobody in SQL and is a problem, as ismanager()withoutrls.approvals.managers. So is aholder()key the catalog lacks, and a tenant scope that is not the root scope.- With
rls.approvals.delegations, the manifest lists the four-argumentpermdock_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: truealso passes better-supabase's{approvers}, the approvers of the request's current step, to the five-argumentpermdock_is_approver, and a kindapproversdoes not name calls it too (covers for policy approvers). It needsrls.approvals.delegationsorrls.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:
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 generatewritespermdock_manages(p_requester, p_levels), a recursive walk uptablefrom the requester's row. It stops afterlevelssteps, 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 decidesmanagerleaves throughpermdock_managesand every other leaf as the two-argument form does. Alevelsoutside 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_managesis a SQL function whose body Postgres checks on create. Its rows are read as the function owner, so the table needs no policy forauthenticated. - Rerun
permdock supabase inspect --out.authorizationProviderseespermdock_managesin the manifest and passes{requester}. - With
delegations: trueas well, the caller's own check includesmanager(), and a cover passes amanager()leaf when the delegator manages the requester withinlevels, throughpermdock_manages_for(p_user, p_requester, p_levels). No client role may execute it. authorizationHooks({ approvers })decidesmanager()in process through therelationssource in itsoptionsor itspermdockFor, readingmanageron the requester'suserrecord asmanager()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:
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:
| Helper | Answers |
|---|---|
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:
export default {
permissions: "./permissions.ts",
policy: "./policy.ts",
rls: {
dialect: "supabase",
authorize: "database",
approvals: { delegations: true },
},
};rls.approvals.delegationswritesapproval_delegationsin the helper schema. Each row is a cover: a delegator, a delegate, an optionaltenant, optionalresources, and a requiredfromanduntilwindow. 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.authorizationProvidersees 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 })frompermdock/supabasereads the same rows asapprovalDelegationsforapprovalsHandler, 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 needsrls.authorize: "database", wherepermdock_has_permission_forandpermitted_<scope>_ids_by_permission_forexist. Injwtmode onlyuser()approvers pass through a cover. A cover withpermissionsset matches only inapprovalsHandler, 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 notenant,resourcesorpermissions; callpermdock_approver_for_ids(p_tenant, p_resource)in a policy to follow the covers of one tenant and resource (a nullp_resourcetakes 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: falsewithtableor 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:
authorizationProvider({ manifest, catalog, requestApprovers: true });- Every kind, including one
approversdoes not name, calls the five-argument form withpg_catalog.split_part({kind}, '.', 1)as the resource. A step'sroleandteammatch nobody through a cover. - The cover rules stay: an active window, the cover's
tenantandresources, 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
requestApproversonly with a better-supabase release whoseisApproverfills{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"] },
}),
),
});blockApprovalStorefiles eachapproval-requireddecision as a blockrequeston the resource, under the permission's action, with the PermDock request inpayload.permdockand itsfingerprint.consumecalls the block'sconsume, which refuses a second use and another fingerprint.get,getByIdandlistread the block's latest 2,000 requests in its tenant; acancelledrequest reads asrejected.- With
tenantless: true, a request whose subject has no tenant is filed withrequest(..., { tenantless: true }), andget,getByIdandlistalso read the latest 2,000 requests without one. The resource's type must be in the block'soptions.tenantless. resolvechecks the verdict against the PermDock request as any store does, then calls the block'sapproveorrejectwithdecidedByset to the approver, soapprovalsHandlerworks over a service-role client and the block records the user who decided. The block still refuses the requester. A client withoutapproveandrejectmakesresolvethrow.blockApprovalPolicySourcereadslistPolicies, and withplatform: truealsolistPolicies({ platform: true }), and maps each enabled policy toApprovalPolicyentries. 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 inroleScope, defaulttenant),usersandmanager(manager());requiredis the stage quorum, andrequired: "all"overusersalone needs each of them.confirmwithselfApprovalbecomesmode: "confirm", andexpiresInin seconds, minutes, hours, days or weeks becomesttl. conditionsbecome acheckover the call's input, or the row without one. Each rule reads one top-level field;is,is_not,eq,neq,is_any_ofandis_none_ofmatch a number and its text alike, as the block does, andgt,gte,lt,lte,between,not_between,contains,not_contains,has_any_of,has_all_of,has_none_of,emptyandnot_emptymap 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 itseffect, so it applies to every call of the permission. A*subject type or action with an effect PermDock knows (a PermDock operation effect, or oneeffectsmaps) matches every operation call with that effect. Without one,*expands overpermissions: 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
teamapprover,required: "all"over anything butusers, another interval format or a failed read makes the source fail, and every call an allow would grant denies. approvalFingerprintfrompermdockreturns 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.
Share links
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:
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 });linksmaps 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 issubject: { 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'sexpiresAt. Revoking the row stops new subjects at once; a token already exchanged lasts until itsttl. - 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 alinkPolicythat 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'sversions.getShared(token).onAuthreceives each denial withsource: "share-link". linkPolicyapplies link rules to the capability. The row carries no issue time, so amaxLifetimerule always refuses.- better-supabase resolves the token in its own
security definerfunction, which reads only the share-link table. The guest's reads of the quote itself still go through the exchanged token and RLS.
Feeds and calendar links
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.
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-storekeeps 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
organizationargument. A revoked member moves to thedemoteTorole withupdate_member_rolewhen no allow grant inpolicygives that role the permission at the tenant scope. Otherwise, or withoutdemoteTo,remove_memberremoves 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 withrevoke_invitation. - Pass the reviewer's client, so the blocks' own
updateRole,removeMemberand 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 asORGANIZATION_ROLE_CEILINGor the owner invariant, leaves the item unapplied infailedwith 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. schemanames the blocks' schema and defaults tobetter_supabase.scopedefaults 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`eventsmaps an event type to the permission a subscriber needs: an exact type first, then the longestprefix.*, then*. A type with no entry reaches no one.- The row is
event.payload, validated against the resource schema, or whatrow(event)returns. - The sender is
event.actorId, or whatsender(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 withsubjectFromBetterSupabase. Claims for another user andnullclaims arenull, so a deleted or suspended user reaches nothing.principalByIdentityexists only withidentities. A{ user }link loads that user, and a{ contact }link is accepted only for a principal withkind: "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:
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.mayPublishlets a user publish an automation only with every key it uses granted to them in its tenant.automation.runAsloads the publisher's current claims, orservice(tenant)for an organization-owned automation, checks every key again, and adds the automation's keys asbsb_permission_cap. A deleted or suspended publisher, a key they lost and a missingservicerun as no one.delegationis set only withdelegation: trueordelegation: { permissions };authorizationHooks({ policy })returns{ apiVersion, name, sessionTags, shareKey }. An app that relied on the implicit hook addsdelegation: true. The object form replaces the scope mapping withpermissions(ref), and a throw or rejection grants nothing.delegation.permissionsmaps a token's OAuth scopes to the keys whose.scopethey are or were renamed from, and to the keys a policyoauthScopesentry covers. It reads noauthorization_details.approverOfexists withapprovers. It refuses the requester and claims whosesubis not the approver, then matchesuser()by id andholder()withdecidein the request's tenant.identities.principalByIdentityexists whenprincipalshasprincipalByIdentity; a contact maps to{ kind: "contact" }.delivery.subscribersanddelivery.audiencearesubscriberPolicyand exist withprincipalsandevents.support.authorizeissupportPolicyand exists withsupport.tickets.subjectexists withtickets. 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
claimsloads, never from the request, and fails closed: a throw, an unknown key andapproval-requiredrefuse.
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:
definePolicy(permissions, {
oauthScopes: {
"mcp:read": [permissions.task.read],
"mcp:write": [permissions.task.read, permissions.task.update],
},
// ...
});"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:
| Claim | better-supabase | PermDock |
|---|---|---|
act.read_only | actor_may_write() guards module tables and its own security-definer writes | permdock_actor_may_write() guards app tables under rls.readOnlyActors; in process, readOnly denies a permission without readOnlyHint |
act.tools | assertToolDelegated in better-supabase/ai-sdk/agents throws AGENT_TOOL_NOT_DELEGATED before a tool runs | subjectFromSupabase maps it to actor.tools; the agent kernel and adapters deny any other tool with agent-tool-not-delegated |
team_ids | not read; module checks call team_ids_of(auth.uid()), which calls teamIdsOf | the hook writes it from supabase.hook.teams; conditions read principal.claims.team_ids in process; generated RLS does not read it |
- Read-only agents.
authorizationProvidersetsfunctions.actorMayWritetopermdock_actor_may_write()when the manifest lists it, so both libraries answer the same for module tables. App tables followact.read_onlyonly whenrls.readOnlyActorsis set: each write policy then gets a restrictive<table>_<verb>_read_only_actorstwin. Without it, a read-only agent token still writes every app table its user may write, because the generated policies do not readact. - 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_idsis a PermDock claim, and only process-side conditions read it; RLS on team rows joins the membership table instead.authorizationProviderfillsteamIdsOfwithmember_team_ids_of(user): from the membership sources of ateamscope, or else fromsupabase.hook.teams. With a team scope, keepsupabase.hook.teamson the same membership table, soteam_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 act | quotes.read | quotes.update tool | update public.quotes as the token |
|---|---|---|---|
read_only: true, tools: ["quotes.read"] | rows | agent-tool-not-delegated | 0 rows |
read_only: true, both tools | rows | denied | 0 rows |
read_only: false, both tools | rows | approved, the row changes | every 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:
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 field | permdock | better-supabase | Notes |
|---|---|---|---|
memberships[].disabledAt | 0.25.0 | 0.53.0 | Filled from the membership source's disabledAt column. |
platformRoles | 0.25.0 | 0.53.0 | Filled from rls.roles when the manifest lists permdock_can_assign_any; platformRoles: false leaves it out. |
functions.subject | 0.25.0 | 0.53.0 | Names permdock_subject(); subject: false leaves it out. |
functions.memberIdsFor | 0.25.0 | 0.53.0 | Names 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.0 | 0.58.0 | Sent as written, with one fixtureRoles entry per role the manifest's fixtureRoles lists; permdock supabase inspect writes that list. |
functions.subjectForTenant | 0.26.0 | 0.58.0 | Names permdock_subject(p_tenant), which answers null for a tenant the caller is no member of; subject: false leaves it out. |
functions.bootstrapPermissions | 0.26.0 | 0.58.0 | Names permdock_bootstrap_permissions(p_tenant), the compact BootstrapPermissionsWire. |
functions.canIn | 0.26.0 | 0.58.0 | The set form over permitted_<scope>_ids_by_permission, so an access policy makes no per-row call. |
functions.approverFor | 0.26.0 | 0.58.0 | Never 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.managedUsers | 0.26.0 | 0.58.0 | Names permdock_managed_user_ids({tenant}) when the manifest lists it; better-supabase fills {tenant}. |
permissions[].levels | 0.26.0 | 0.58.0 | Filled from the catalog's levels. |
tokenHook.teamIdsTruncatedClaim | 0.26.0 | 0.58.0 | Set when the hook writes team_ids. |
functions.roleIn | 0.29.0 | 0.77.0 | roleIn: true names permdock_role_in({role}, {tenant}) when the manifest lists it. Off by default. |
roleSources[].role.through.tenant, platformRoles.through.where | 0.31.0 | 0.84.0 | From rls.customRoleWrites.roles tenant, scope and globalScope; canAssign asks at 'global'. |
functions.portalSubjects, functions.portalParties | 0.31.0 | 0.84.0 | portalParties from a child scope whose memberships name via; portalSubjects only with portalSubjects: true. |
versions | 0.31.0 | 0.84.0 | The hook's authz_version_for when authzVersion is on. |
wildcards | 0.31.0 | 0.84.0 | 'none' with a catalog whose keys hold no *. |
operations[].approval | 0.31.0 | 0.84.0 | <resource>:<action> floors from the catalog's approvals. |
doctor | 0.31.0 | 0.84.0 | permdock doctor --format findings, with timeoutMs from the doctor option. |
actionKeys | 0.31.0 | 0.84.0 | Filled 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 inauth.sessions. Call it before a sensitive action and pass the result asliveSession(live sessions). - A support session and
actingAswriteactwithkind: "support"or"impersonation", so the subject's actor has that kind and every call denies withno-delegationuntil the policy names the actor in a delegation (support and impersonation actors). - The
scopesguard answers 403insufficient_scopebefore PermDock runs; PermDock's delegation narrowing still applies after it. - Only
allow: ["anonymous"]admits asignInAnonymously()user past a guard. Pair the defaultallow: ["user"]withanonymousSignIns: "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.tspassesauthorizationProviderthe example'spermdock.manifest.jsonandpermissions.catalog.jsonwithtables,widenedandsharedFunctions, setsblocks.permissions.model: "provider", and setscanAssigntofalsebecause its membership tables are service-only.src/lib/supabase/server.tspassesauthorizer({ policy, memberships, version, intent }),authorizationHooks({ policy, widened })and the sharedversionscache tocreateNext.membershipscomes from the generated source factory,versionisauthzVersion({ query }), andintentmakes aread,listorviewpermissionreadand every other checkwrite.src/proxy.tscallsbsb.proxyandmayAccess.src/lib/supabase/index.tsvalidates sessions withsupabaseClaims().extend(appClaims). Bearer routes map the verified token withsubjectFromBetterSupabaseorsubjectFromJwt.supabase/schemas/public/functions/feature_claims.sqladdspublic.feature_claims(user_id), which readsorganization_featuresfor the organizationspermdock.member_organization_ids_for(user_id)returns.permdock.config.tsregisters it as thefeaturesclaim.- The share-links block requires better-supabase's
membershipsblock.blocks.membershipsmaps onto the app'spublic.organization_membershipstable, andsrc/sources.tsreads the same table withblockMembershipSource, so the block and the token hook share one set of rows. The example installs no organizations block, so it sets noassignmentGuard. src/app/[locale]/share/[token]/page.tsxis the guest quote page.src/lib/share.tsresolves the token withsubjectFromShareLink, checksquotes.readfor the link-onlyguestrole and reads the quote under RLS with theexchangeCapabilityclaims (rls.capabilities). The seed's link opens at/en/share/acme-initech-rollout.rls.approvals.delegationswritesapproval_delegations, and the seed gives Mason a 30-day cover for Olivia's Acme approvals.supabase/testsholds pgTAP tests over the seeded tenants, andtests/claims.test.tsmaps every claim fixture through better-supabase'screateServer.
Related
- 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
Supabase token hook
permdock supabase hook generate compiles the app's membership sources into one custom_access_token_hook, with the active scope first, a size budget, an authorization version for sensitive permissions, and protection for memberships the identity provider owns.
Better Auth
The permdock/better-auth provider builds a PermDock subject from Better Auth sessions and organization roles, including dynamic database roles, so PermDock's conditions, snapshots and adapters layer on top of Better Auth access control.