Block SQL
The SQL a block installs into your declarative schema. The files are idempotent, and you commit them with the app.
better-supabase add writes a block's SQL into supabase/schemas, and
supabase db schema declarative sync turns them into a migration. The files are plain SQL that
you can read and commit, so nothing runs behind your back. Every module can be
re-run safely, and it keeps everything it creates in the better_supabase
schema. add renders the new modules next to the ones blocks
already lists, so a module sees what is installed (billing's foreign key to
the organizations table, for example), and writes only the named modules and
the ones they need.
add also lists the new modules in blocks of your config file, in
the form it already uses: tags: {} in an object, "tags" in a list. It
edits the object literal you pass to defineConfig() and leaves the rest of
the file as it is. When blocks is not a literal it can follow, such as
a variable or a spread, it changes nothing and prints the entries to add
instead. --dry-run says what it would add.
better-supabase add audit queue pgtap
supabase db schema declarative sync -f better_supabase_block
better-supabase add --adopt
better-supabase blocks list --installedAfter the SQL, add wires the clients of blocks that have one into
lib/blocks.ts and prints the registry command for your framework's glue.
The extensions a module's schema file creates (pgmq for queue,
pg_jsonschema for jsonb-schemas, vector for vector-search) have to
exist before the schema migration applies, because objects in it use them: a
check constraint on jsonb_matches_schema, a pgmq queue. A schema diff can
leave them out of its migration, so add and upgrade
write the ones no migration creates yet into
supabase/migrations/<stamp>_better_supabase_extensions.sql, stamped before
the schema migration you create next. A migration you wrote yourself that
creates the extension counts too, so the CLI writes nothing for it.
add --adopt refuses to write the data migration while a module extension is
missing from every earlier migration; run upgrade, then create the schema
migration again after the extensions migration.
A schema diff only captures objects, so each module's rows and settings (its
better_supabase.blocks row, the reserved slugs, the rate-limit role
setting) go to a second file in supabase/better-supabase-data/, outside the schema folder:
pg-delta loads every file under supabase/schemas, nested folders included,
and refuses a table that has rows afterwards. When database.sql.dir is a folder
inside the schema folder (supabase/schemas/block), the data files still go
next to the schema folder, and declarative_schema_path in
supabase/config.toml moves both. better-supabase add --adopt writes those files into one
migration, stamped after the newest one so it runs after the schema migration.
Its statements are idempotent keyed upserts. It compares them with the
statements of the data migrations already in the folder and writes only the
ones no migration holds, so a block upgrade adds one small migration instead of
repeating every row. It writes nothing when every statement is already there,
and --check exits with 1 when one is missing. add and upgrade say when to
run it. The memberships backfill of membership_roles (with
roles.many) lives in this file too, not in the schema file.
Your own reference data stays yours: upgrade never writes rows into
supabase/seeds, and a block never seeds a table your seed files write to
(doctor BS358). An insert in a data file that has no
on conflict or not exists key fails BS357, and a
seed_<name>_defaults function without a p_locale parameter fails
BS359.
Event triggers belong to no schema, so a diff limited to some schemas
(supabase db schema declarative sync -s public,better_supabase) leaves
them out of its migration. Run the sync without -s when you use audit
(bsb_audit_forget_dropped) or rls-guard (bsb_ensure_rls). Their data
files repeat the event triggers (drop event trigger if exists, then
create event trigger), so the add --adopt migration creates them even when
the schema migration lacks them, and
doctor BS323 reports a module event trigger that
the database, or every migration, lacks.
upgrade writes every event trigger, and every trigger on an auth table (the
profile, SSO and waitlist triggers), to one file,
900_better_supabase_999_unscoped.sql, so the statements no schema filter
covers sit in one place. The module files keep the functions they call. The
migrations workflow keeps each statement in its module, because it applies them
in file order.
Commands
| Command | What it does | Side effects |
|---|---|---|
add <block...> | Writes the module files and config entries, and wires the clients | Writes files. |
add --adopt | Writes the data statements no data migration holds yet | Writes files. |
upgrade | Writes the upgrade steps, then every module file again | Writes files. |
remove <block...> | Takes blocks out of the config and deletes their module files | Writes files. |
blocks list --installed | Lists the installed blocks with their versions | None. |
blocks view <block> --sql | Prints the SQL add would write for one block | None. |
init describes add, remove and upgrade and
their flags.
Workflows
database.sql.workflow says how the modules reach a migration. There are three:
| Workflow | What add and upgrade write | How the migration is made |
|---|---|---|
pg-delta | Module files in supabase/schemas (the default) | supabase db schema declarative sync -f <name> |
migra | Module files in supabase/schemas | supabase db diff -f <name>, with the stack stopped |
migrations | One migration, <stamp>_better_supabase_modules.sql | The CLI writes it; apply it with supabase migration up |
export default defineConfig({
database: { sql: { workflow: "migrations" } },
blocks: ["audit", "queue"],
});When database.sql.workflow is unset, the CLI reads supabase/config.toml: pg-delta
when [experimental.pgdelta] enabled = true, migra when that key is false,
when [db.migrations] schema_paths is set or when supabase/schemas already
holds files without pg-delta, and pg-delta otherwise. migrations is never
detected, so an app picks it in the config.
better-supabase init --workflow <name> writes the key.
pg-delta (Declarative Schemas 2.0)
pg-delta is the Supabase CLI's diff engine (2.119 or later) and the default
for projects that supabase init creates (config.jsonc since CLI 3.4). It orders the schema files by
dependency and carries grants, comments and security_invoker on views into
the migration. It needs [experimental.pgdelta] enabled = true in
the Supabase config (config.toml, config.json or config.jsonc);
better-supabase init, add and upgrade add it to an existing config under this workflow.
migra (Declarative Schemas 1.0)
The tables your earlier migrations create count as yours, as they do under
migrations, so the module files that upgrade writes into supabase/schemas
never create them again.
The legacy engine reads supabase/schemas while the stack is stopped. The
CLI and doctor name its command, supabase db diff -f better_supabase_block.
When supabase/config.toml lists [db.migrations] schema_paths, migra reads
only the files those entries match, so add names any module file no
entry matches and prints the lines to add before the schemas that call their
functions. Without workflow: "migra" in the config,
doctor reports BS316. Supabase's
switch guide
lists the steps to move to pg-delta.
Migrations only
This workflow is for an app without declarative schemas. add and upgrade
write nothing to database.sql.dir. add and upgrade write one migration that
holds, in order, the extensions, the upgrade steps, each module's schema with
its @bsb-block line, the realtime topic policies and the data statements.
Every statement can run again, so each new migration carries all the modules,
not only the changes. A command writes a new one only when the statements
differ from the newest *_better_supabase_modules.sql.
upgrade --checkand doctor BS304 compare against that newest migration.blocks list --installed,upgradeand doctor read the installed versions from its@bsb-blocklines.add --adoptwrites nothing, because the rows are already in the migration.genwrites the read-sets module into<stamp>_better_supabase_read_sets.sql.- The pgTAP files still go to
database.sql.testsDir.
Columns your files add to a block table
A column you add to a block's table with alter table ... add column in one of
your own schema files is a field of that block: its functions read it and write
it through fields, and the block never adds or drops it. Put the statement in
the file that already alters the table, beside its checks and comments, or in
<table>.ext.sql next to your schema files when none does. upgrade never
rewrites a file without a @bsb-block line, and the CLI reads the type text
after the column name, so text not null default 'en' gives the field its
default. The extraColumns options this replaces were removed:
better-supabase codemod extra-columns moves them into your files. On a table you create yourself and map a block over, the columns the block
takes as fields are the ones its table comment lists: comment on table ... is '@bsb fields plan, seats'.
Migration names
Every migration the CLI writes is named <stamp>_better_supabase_<name>_<hash>.sql.
The stamp is later than the newest name in the migrations folder, whichever tool
wrote it, so an authorization library's generator never shares a version with
upgrade. The hash is the first 8 hex digits of the statements without their
comments. A command that would write statements an existing migration already
holds leaves the folder alone, and --force writes them again as a new
migration. Names without a hash, from earlier releases, are still read.
Modules
| Module | What it adds |
|---|---|
updated-at | track_updated_at(table) keeps an updated_at column current |
created-by | track_actor(table) fills created_by and updated_by from auth.uid(); impersonated_by => 'column' also stamps an impersonating admin; token_scope_allows(scope) checks a delegated token's OAuth scope in a policy |
audit | audit(table, ignore => '{updated_at}') records inserts, updates and deletes in audit_events, keyed by the primary key, with the changed columns, the tenant column from auth.tenant.column and any impersonating admin |
memberships | memberships, current_tenant_id(), member_organization_ids(roles) and has_organization_role(organization, roles) for RLS policies, and membership_claims(user) for the access token hook |
permissions | can(scope, id, permission), tenant_ids_with(permission) and is_platform(permission) over roles, your own tables, an authorization provider or your functions. See Access contract |
invitations | invite_member(tenant, email, role) returns a single-use token, and only its hash is stored; accept_invitation(token) checks the signed-in user's confirmed email. See Organizations |
reserved-slugs | track_slug(table) rejects reserved words (admin, api, ...) and malformed slugs, also for service_role writes; options.minLength and options.maxLength (1 and 63 by default) bound the length, and options.slugs adds the app's own words, such as its route names, to the data file |
queue | Jobs on Supabase Queues (pgmq) or a table: leases, retries with backoff, dead letters, dedupe keys and schedules (pg_cron or the drain route), and with httpTick a pg_cron job that calls the drain or schedules route. Used by better-supabase/blocks/queue |
idempotency | Stores Idempotency-Key results so retried requests replay the first response |
webhook-inbox | Stores verified webhooks once and hands them to a worker; it can run over your own table |
realtime-tables | Payload-free change broadcasts for live queries, registered from database.realtime.tables, and broadcast_topic() for topic triggers |
jsonb-schemas | pg_jsonschema check constraints for jsonb columns with a schema in the json config (see below) |
pgtap | Test helpers for supabase test db. See Testing |
grants | The complete Data API privileges of the tables and functions in expose, for anon, authenticated and service_role, or grants derived from your policies with options.fromPolicies. See Data API grants |
read-sets | One stable, security invoker function per read set in readSets, written by gen. See Read sets |
mfa | mfa_satisfied() for restrictive policies that require aal2 once a user has a verified factor. See MFA and SSO |
sessions | session_active() for restrictive policies that reject tokens whose session was signed out or expired, or whose user was banned or deleted; options.policies writes the policy on every table (options.exclude skips some), last_sign_ins(user_ids) reads many users' last sign-in at once for the service role, and list_my_sessions() and end_my_session(id) list and end the caller's own sessions. See Ended sessions |
entitlements | tenant_entitlements(tenant), has_entitlement(tenant, key) and feature_claims(user) over the Stripe Sync Engine. See Entitlements |
vector-search | search_<table>(query, k) per table in vectorSearch, for db.$search. See Vector search |
rate-limit | set_rate_limit(scope, max, period) and check_request(), a pgrst.db_pre_request hook that answers writes over the limit with 429. See below |
impersonation | Support sessions: start_support_session(target, reason) checks is_platform and a second admin's approval, records the session and audits it, for the support mode |
organizations | create_organization(attrs), member roles, ownership transfer, switch_organization(organization), list_my_organizations(), list_members(organization) and an owner check on commit. See Organizations |
profiles | A profile per user from sign-up metadata, with a unique username, an email mirror, my_profile(), update_my_profile(attrs), column grants and service-owned columns. See Profiles |
outbox | emit_event(type, payload) in the writing transaction, named consumers with their own cursor, backoff and dead letters, track_events(table) and a relay to any EventSink. Other modules emit to it once it's installed. See Outbox |
notifications | notify(jsonb) as a security definer sender, per-recipient read, dismissed and resolved state, subject subscriptions, channel preferences, email and push deliveries, and a private realtime topic. See Notifications |
inbox | Shared inboxes per organization: contacts with channel identities, conversations with assignment, teams, status, snoozing and bot handoff, messages and internal notes, read state, deliveries, a webhook event store, attachments in a private bucket and private realtime topics. See Inbox |
messaging | Conversations, members, threaded messages with edits, pins and resolution, mentions, read markers, typing over Realtime, scheduled sends through jobs, and files and reactions on messages, for channels, direct messages and record conversations. See Messaging |
channels | Named channels on messaging: public ones the whole tenant can browse and join, private ones for their members, a topic, a purpose and an optional linked record. See Channels |
chat-sdk-state | The Chat SDK state tables: subscriptions, token-checked locks, a TTL cache, lists and per-thread queues, behind service-only functions, and purge_chat_state. See Chat SDK state |
webhooks | Customer webhook destinations with event subscriptions, Vault secrets with rotation, a delivery log with leases, retries, redelivery and auto-disable, and publish_webhook_event as a service-only fan-out. See Outgoing webhooks |
incoming-webhooks | Per-tenant trigger URLs with hashed tokens, optional Standard Webhooks or HMAC verification with secrets in Vault, a body limit, receive counters and a rate limit; deliveries go to the webhook inbox or a jobs queue, and it can run over your endpoints table. See |
streams | Durable streams: ordered chunks with idempotent appends, a cancel flag the writer reads on its next append, owner reads through RLS, a payload-free Realtime ping per stream and purge_streams. See Durable streams |
credentials | credential_get, credential_set and credential_delete over Supabase Vault, for service_role only, behind vaultCredentials(); it can run over your secrets table. See Credentials |
ai-chat | Chats, projects and a branching message tree in the canonical AI message format, runs with a compare-and-set stream claim and step progress, tool approvals and policies, pending inputs, cited sources, feedback, hashed share links, a model catalog per plan, moderation events, experimental harness sessions, the ai_sandboxes registry of chat and harness sandboxes with a service-only idle stop, and private Realtime topics. See AI chat |
ai-files | Files for AI chats in a private bucket whose policies only accept a reserved upload, provider file references with expiry, versioned documents with suggested edits, and a purge for stale uploads and the files of deleted chats. See AI files |
knowledge | Documents and chunks for retrieval, each chunk with an embedding and a tsvector, scoped to an organization, agent, project, chat or user; hybrid search with reciprocal rank fusion, chunks that keep their embedding when unchanged, and an embed job per document when jobs is installed. See Knowledge |
memory | Core memory files under /memories edited with the memory tool commands, archival facts with embeddings, one embedding per chat message for recall, namespaces per user, agent, chat or organization, and versioned documents for agent runtimes. See Memory |
agents | Saved assistants with instructions, a model, tools, connectors, knowledge scopes and starters; private, organization or public visibility, installs, ratings and skill references. See Agents |
connectors | MCP servers per organization, one OAuth grant per user behind a credential_ref that is revoked with the grant, MCP sessions per chat, and tool list fingerprints an admin approves. See Connectors |
ai-schedules | Prompts scheduled on a cron in a time zone, a service-only tick that queues due runs to the ai_task_run queue, and a run log. See AI tasks |
push | push_devices per user with RLS, register_push_device and unregister_push_device for the user, and push_tokens_for and prune_push_tokens for service_role. With notifications, push_tickets keeps Expo's tickets per delivery for the receipt check. See Push notifications |
ai-cache | Model responses cached under a key the app derives from the request, with a TTL capped by maxTtl, an entry size cap (maxBytes), hit counts and a purge of expired entries; only the service role reads and writes it. See AI cache |
ai-keys | Per-tenant provider keys stored as credential_refs, and the ai_batches registry of provider batch jobs with their stored results. See AI providers |
api-keys | api_keys with only the SHA-256 of each secret, create_api_key, rotate_api_key, revoke_api_key, verify_api_key(public_id, secret_hash) for the server and has_scope(scope) for policies. See API keys |
document-templates | Templates per legal entity and language for invoices, credit notes, quotes, orders, dunning letters, delivery notes and statements, reusable text blocks, render_document(tenant, type, id, language) with a snapshot frozen when an invoice is issued. See Document templates |
legal-entities | Several legal entities inside one organization with one default, their VAT, chamber and bank details, resolve_setting(tenant, key, legal_entity) that falls back to the organization, and an optional legal_entity_id on other blocks' tables. See Legal entities |
settings | Per-user and per-organization settings with defaults, get_user_settings(), set_organization_setting(tenant, key, value) and the reset functions. See Settings |
usage | Usage counters per tenant, meter and period, record_usage with idempotency keys, quotas per tenant or plan, and within_quota(tenant, meter) and consume_quota for RLS and RPCs. See Usage and quotas |
billing | Stripe customers per tenant, billing_status(tenant), billing_seat_count(tenant) and link_billing_customer. See Billing |
flags | Flags with targeting rules, overrides and percentage rollouts, and flag_enabled(key) and tenant_ids_with_flag(key) for policies, bucketed the same way as the TypeScript provider. See Feature flags |
comments | Threaded comments on any record as its messaging conversation, with mentions, resolve, pins and tasks, create_comment and list_comments. See Comments |
timeline | An activity feed built from outbox events, joined with a subject's audit entries, notification deliveries and workflow runs, record_activity and list_activity. See Activity |
attachments | Attachment records linked to Storage objects, tenant-scoped Storage policies, and a scan status that gates downloads. See Attachments |
data-lifecycle | Data exports per user or organization, request_organization_deletion(tenant) with a grace period, cancel_organization_deletion and purge_organization. See Data lifecycle |
sso | Verified organization domains with auto-join, SAML providers per organization, SSO enforcement in the access token hook and the SCIM user and group functions. See SSO and SCIM |
onboarding | Checklists per user or organization run as enrollment programs, complete_onboarding_step(checklist, step, tenant) and a trigger that completes steps from outbox events. See Onboarding |
waitlist | join_waitlist(email), approvals, hashed invite codes with use limits and an optional organization, and a trigger that redeems the code on sign-up. See Waitlist and invite codes |
announcements | Announcements with audiences, a time window and severity, active_announcements(tenant), dismiss_announcement(id) and a broadcast on a Realtime topic. See Announcements |
workflows | workflow_runs for any engine, read through RLS, with a Realtime ping per status change and outbox events when a run ends; cron schedules, counting semaphores, admission control for starts and purge_workflow_runs. See Workflows |
workflow-sdk | The Workflow SDK World's tables in a workflow schema only the service role reads, a trigger that copies each run into workflow_runs, and dispatch_workflow_deliveries() for pg_net delivery on a pg_cron schedule. See Workflow SDK |
workflow-editor | Graph workflows per tenant: definitions, numbered versions checked and published in SQL, webhook, schedule and event triggers, credentials by credential_ref, the step library, node-level run status with a Realtime ping, and alerts on failed or slow runs as outbox events. See Workflow builder |
numbering | Gapless numbers per tenant, entity and period. See Number sequences. |
teams | Teams and members. The inbox assigns conversations here. See Teams. |
tags | Tag definitions and per-subject applications. See Tags. |
state-machine | Allowed status transitions, history and status.changed. See State machine. |
custom-fields | Definitions and typed values, with a permission check for sensitive values. See Custom fields. |
share-links | Hashed share links, views and per-user state. See Share links. |
reminders | RFC 5545 recurrence and reminder delivery. See Reminders. |
imports | CSV import runs. See Imports. |
subjects | The app-wide subject registry from config.recordTypes: subject_title, subject_url, subject_titles, can_subject and can_subject_for. See Subject registry and Subjects. |
rank | Fractional rank keys for subjects with a rank column: rank_between, move and the rank.rebalance job. See Rank. |
saved-views | Named list views per user, team or organization, with a default per slot and rank order. See Saved views. |
relations | Typed links between subjects with inverse names, cycle checks, one-target kinds, ancestors, descendants and rollups. See Relations. |
bulk | One action over many rows with a result per row, and background runs on the jobs queue as the user who started them. See Bulk actions. |
search | A search_documents index kept up by triggers from each search entry in config.recordTypes; search(q) as the caller with websearch, prefix and trigram matching and can_subject, search_page for browsing and cursor paging with facet filters, hybrid ranking with embeddings, and recents and favorites from share-links. See Search. |
metrics | Metrics declared with defineMetric: metric_points rollups per grain and time zone, metric_series and metric_value checked against a permission in the tenant, and a metrics.rollup job. See Metrics. |
calendar | Calendars, events with RFC 5545 recurrence, overrides and attendees, an iCalendar import and an iCal feed through a share link. See Calendar. |
bookings | Bookable resources with weekly hours and exceptions, services with buffers, available_slots in SQL, holds that expire, an exclusion constraint against double bookings (needs btree_gist) and public booking through a share link. With recurring, a weekly or daily rule books a series one occurrence at a time. See Bookings. |
versions | Numbered snapshots of a subject's content with JSON Patch diffs, restore, auto and frozen snapshots, and retention. See Versions. |
trash | Soft delete through each subject's deletedAt column, with children trashed in one batch, restore with unique checks and purge after a retention period. See Trash. |
reactions | Emoji reactions and up or down votes on any subject, comments and inbox messages, with a vote score per subject, custom emoji per organization and a realtime topic per organization. See Reactions. |
approvals | Approval requests with steps per subject type and action, approvers by permission, role, team or user, delegation, expiry and reminders; the final approval runs a state-machine transition or a job. See Approvals. |
access-requests | Members ask for a role or for access to one record, for a set time if they like; the request goes through approvals, the final approval grants it, and the grant ends early or when it expires. See Access requests. |
documents | Yjs documents on any subject: an update log, a compacted snapshot and a private Realtime topic per document for edits and presence; better-supabase/yjs connects a Y.Doc. See Documents. |
catalog | Products, options, variants, prices in bigint minor units per currency and price list, categories, collections and an opt-in public storefront. See Catalog. |
inventory | Locations, stock levels per variant and location posted to the ledger, reservations with expiry, transfers and purchase orders with partial receiving, over catalog variants. See Inventory. |
rfqs | Requests for quotation numbered RFQ-1 with lines, invited suppliers, quotes that revise in place, a comparison with the cheapest marked, and an award that creates a draft purchase order. See Requests for quotation. |
tills | Cash drawers with shifts that open on a float, cash sales, refunds and cash in and out, an end-of-day count that books its variance in accounting, and deposits that reconcile against banking transactions. See Tills. |
deadlines | Platform-owned rule sets per jurisdiction and kind, approved once and frozen with a content hash, and the deadlines computed from a subject's facts per group: due on a date, unknown with the missing facts named, or the reason there is none. See Deadlines. |
periods | Dated periods per kind with open, locked and closed states, a lookup by date and a close protocol where accounting fiscal periods and leave years add blockers and a closing step. See Periods. |
commissions | Commission plans (flat or marginal tiers) per seller, commissions accrued on the ledger from sold records or paid invoices, statements per period with payout, and the lines payroll adds. See Commissions. |
referrals | Referral codes per member, attribution at signup or invitation acceptance, and a reward posted once to the ledger when the referral qualifies. See Referrals. |
agent-checkout | Checkout sessions over an orders cart for ACP and UCP agents, and signed AP2 mandates that cap what an agent may spend. See Agent checkout. |
clinical-decision-support | Rules over medication orders that raise dose range, duplicate therapy and interaction alerts, a port for external engines, and alerts that a member acknowledges or overrides with a reason. See Clinical decision support. |
e-prescribing | Prescriptions over medication orders with the states draft, signed, sent, dispensed and cancelled, a signature only the prescriber can give, and delivery through a PrescriptionGateway port that carries a FHIR R4 MedicationRequest. See E-prescribing. |
manufacturing | Versioned bills of materials with routings on work centers, production orders numbered MO-2026-0001 that consume components and receive the output through inventory, lot genealogy and recall, and material requirements. See Manufacturing. |
banking | Bank accounts with imported CAMT.053, MT940 and feed statements, matches of each transaction to invoices, expense reports and accounting entries with suggestions from RF and Dutch payment references, bank rules that book or set aside what they match, and a reconciliation status per account against the ledger. See Banking. |
funding | Funding products with a rate per unit, awards that grant a person a number of units per period from a funder, deliveries registered by hand or from time entries, and claims a funder answers line by line, sent through a format and a channel. See Funding. |
drive | Folders and files per organization, with grants to users, teams or roles inherited down the tree, a name-conflict policy for moves and renames, grants from approved access requests, ownership transfer, and the SQL hooks and events around them. It renders ahead of comments, so drive_node can be a subject. See Drive. |
drive-files | The part of drive that needs attachments: uploads and revisions through versions, restrictive policies on the attachment rows and storage.objects, the bin through trash, stars and recent items through share-links' user state, folder links and the purge. Installed with drive. |
orders | Shipping rates, carts owned by the signed-in (or anonymous) user, orders with lines, payments, fulfillments, returns and refunds over catalog variants; checkout reserves inventory and numbers orders and invoices. With kitchen, lines move through preparation states at stations and broadcast each change. See Orders. |
promotions | Percentage, fixed and free-shipping promotions, automatic or by code, scoped to the order, products, categories or collections, with usage and per-customer limits, stacking and priority; orders prices them into carts and redeems them at checkout. See Promotions. |
forms | Forms with numbered versions (steps and show or skip logic), a JSON Schema 2020-12 per version that pg_jsonschema checks on every submission, drafts, public links through share-links with a rate limit and a bot-check hook, and handlers that turn a submission into a record. See Forms. |
signatures | Simple electronic signatures on a frozen version from the versions module: click, typed or drawn signatures in parallel or in order, a hash that detects edits after signing, and an approval step a signer can decide. See Signatures. |
time-entries | Timers and logged time on any record with one running timer per member and no overlaps, weekly timesheets approved through approvals, and weeks that lock while pending or approved. See Time tracking. |
identities | Links an email address or a chat user to an app user or a contact, through a one-time code or a confirmed address. See Identities. |
service-accounts | Organization members that aren't people: auth.users rows that can't sign in, with a role through a membership. Organization-owned workflow versions and service webhook endpoints run as the default one. See Service principals. |
signing-keys | Ed25519 and ES256 keys per owner, private keys in Vault, one active key per owner, retired keys published until their tokens expire, and a JWK Set per owner. See Signing keys. |
security-events | OpenID Shared Signals streams per receiver, push delivery through a webhooks endpoint with format set, a poll queue, SETs held while a stream is paused, and the receiver replay table. See Shared signals. |
oauth-server | OAuth client registry with hashed secrets and registration tokens, authorization codes bound to an S256 PKCE challenge, device codes, grants per user and client, and a revocation list keyed by jti and grant. It stores and verifies; your authorization server signs the tokens. See OAuth server. |
domains | Hostnames per organization: custom domains verified by a DNS TXT record, subdomains of platformDomain verified when added, one primary per organization, and resolve_hostname for the proxy. See Custom domains. |
reviews | Ratings and reviews of catalog products and registered subjects: one per user and subject, a verified flag from paid orders, moderation before or after publishing through the moderation module, the organization's reply and a per-subject aggregate public storefronts can read. See Reviews. |
moderation | Reports on any subject for configured reasons, a review queue, decisions (approve, hide, remove, restore, ban) with a log, user bans and an automatic hide threshold. Hides and removes messages, comments included, and reviews moderate through it. See Moderation. |
enrollments | Programs of ordered steps per organization and enrollments of any subject in them, with a step snapshot, completed steps, completion and cancel. Onboarding checklists run on it. See Enrollments. |
courses | Courses of modules and lessons in rank order, quiz lessons graded by forms, per-lesson progress, completion and certificates. Each course runs as an enrollment program, so learners enroll through enrollments. See Courses. |
leave | Leave types in days or hours, requests that go through approvals, and balances per member and year on the ledger with grants, accruals, adjustments and a year-end carryover. See Leave. |
automations | Tenant-editable rules on a subject type: a filter tree over a field catalog the app syncs, tested in rank order when a trigger event happens, { kind, config } actions the app runs, saved versions, an evaluation log and rule_evaluate, which gives the same answer as evaluateFilterQuery. See Rules. |
vercel-marketplace | Marketplace installations per configuration id with their access token sealed in Vault, provisioned resources with their tenant and secret refs, plans, invoices kept by event time and the meter totals reported to Vercel per period. Service role only. See Vercel Marketplace. |
ledger | Double-entry accounts per organization in a currency or a custom unit, append-only transactions whose entries sum to zero per unit, running balances and holds. Credits, loyalty points, gift cards and trust balances are account kinds; inventory, leave and invoices post to it. See Ledger. |
accounting | Double-entry books in money: a chart of accounts with account roles, journals, fiscal years of periods, balanced entries numbered per journal and year, dimensions, exchange rates, tax codes, the trial balance, profit and loss, balance sheet and general ledger, and the period and year-end close. |
assets | A location hierarchy (site, building, unit) and an asset registry with tags, status, coordinates and assignment to members or records. Optional PostGIS stores points and areas as geography; booking resources and work items can name an asset. See Assets and locations. |
scores | Tenant-editable scoring models on a subject type: rules from the rules field catalog worth points, weighted metrics from number fields or vote scores, bands, saved versions, and the current score and history per record with a breakdown. Lead and health scoring are models. See Scores. |
guests | People outside the organization, invited by email, who read, comment on and upload to the records they are granted, and see the invoices and bookings of the party they act for. Guests are never members; comments, attachments, invoices and bookings let them in through ctx.scope.guest. See Guests. |
passes | Admission passes on QR codes and NFC tags, signed with the signing-keys block: a ticket for a booking or a pass with a number of uses for a resource. Every scan is logged, and drop-ins count against the resource's capacity with its bookings. With credits, a pass pays for class bookings and refunds the credit on an early cancellation. See Passes. |
billable-time | An hourly rate card per organization, member and record, a preview of unbilled time, and invoice_from_time, which bills it as lines on a draft invoice. Billed entries lock until the invoice is voided. See Billable time. |
leases | Units from the assets block let to parties, with rent per period posted on the ledger once (a charge row and a ledger key per period), deposits held through ledger holds until termination, renewals, and maintenance requests on the unit. See Leases. |
expenses | Expense reports with lines in categories, receipts as attachments on the lines, spend policies (a limit per category and a receipt threshold) checked on submit, approval through the approvals block, and the approved total and its reimbursement posted on the ledger. See Expenses. |
donations | Gifts from donors to funds and campaigns posted on the ledger, pledges charged once per period through a payments provider, and numbered tax receipts per gift or per donor and year. See Donations. |
dispatch | Field service work orders at asset locations, scheduled into technicians' slots without overlaps, worked from scheduled through en route and on site to done, with day routes of ordered stops and the parts each job used. See Dispatch. |
shipments | Shipments with packages and addresses, labels bought through a versioned carrier interface, and a tracking timeline that records each carrier event once; the status follows the latest event. See Shipments. |
contracts | Contracts with a registered counterparty from draft through review and signature (frozen as a version and signed with the signatures block) to active, expired or terminated. Values are bigint minor units; renewal terms schedule the owner's reminder before the notice deadline, and run_contract_renewals renews or expires contracts past their end date. Obligations carry due dates and owners. |
compliance | Compliance frameworks and controls, evidence (attachments or notes) with a validity date, recurring evidence tasks with an assignee and an overdue state, a computed control status and a rollup per framework, and policies published as versions that members acknowledge. |
consents | Consent purposes with a lawful basis and a version, and a granted or refused decision per record and purpose with who decided, the evidence (a signature, a form submission or an attachment), withdrawal and expiry. See Consents. |
incidents | Incidents with a severity, a status timeline, affected components and a postmortem. Component status follows the open incidents and keeps an uptime history. public_status_page(slug) is the one function anon may call: it returns only the public components, incidents and updates of a published page. |
risks | A risk register: risks scored on a likelihood by impact matrix before and after controls, an assessment history frozen as versions, treatments, scheduled reviews, barriers linked through relations and a heatmap per matrix cell. |
observations | Coded measurements of any record against definitions with a UCUM unit, a code (LOINC for the shipped vital signs) and valid, reference and critical ranges: a computed flag, critical alerts to the record team's leads, amendments and entered-in-error corrections, idempotent device ingest, series and latest values, and observations mapped from form submissions. |
care-plans | Care plans per client subject: coded problems, goals with a measure and the actions that reach them, evaluations over time, one active plan per client published as a version, agreement through a signature, and restrictive measures that start only once approved. See Care plans. |
cases | Cases of tenant-editable kinds (nonconformities, complaints, incidents, near misses and more), numbered per kind, each kind on its own pipeline, with a root cause, actions as work items, an effectiveness check, intake through forms and a close guard. |
meetings | Meetings with an agenda, attendees and roles, minutes per agenda item, decisions the attendees vote on, and action items that become tasks. See Meetings. |
payroll-export | Payroll runs that add up approved time, leave and scheduled shifts per person and lock behind an exported file, rendered by a versioned export format. See Payroll export. |
maintenance | Preventive maintenance plans by time, meter or calendar rule that open dispatch work orders with their spare parts, plus meter readings and calibrations. See Maintenance. |
dam | Renditions of drive files made through the drive's preview renderers, and usage rights with a territory, a channel and an expiry date that send a reminder before they end. See Digital asset management. |
lims | Laboratory samples numbered SMP-1, methods with specification limits, results from qualified instruments, and a nonconformity case for each result out of specification. See Laboratory samples. |
appraisals | Review cycles with self, peer and manager reviews, calibration sessions, goals and sign-off through approvals. See Appraisals. |
warehouse | Pick waves and pick lists made from stock allocations with confirmed bins, lots and serial numbers, picking work items, and cycle count plans that hold large variances for review. See Warehouse. |
inspections | Audit programmes, inspections numbered AUD-2026-001 with a team and a checklist form, findings typed as nonconformities, observations or opportunities, and cases opened from nonconformities before an inspection closes. See Audits and inspections. |
templates | Versioned templates of a type that create records, system starters kept by key and forked per organization, a default per type and language, the applications each template made, and the workflow-editor workflows each new record starts. See Templates. |
pipelines | Tenant-editable pipelines for registered subjects: ordered stages whose categories map to open, success or failure, a stage history with time in stage, board totals per currency, and a status column set from the stage. See Pipelines. |
contacts | Companies and people an organization works with: lifecycle stages, owners, who works where with a role and a primary contact, domain and email dedupe, merges and keyset-paged search. See Parties. |
activities | Calls, emails, meetings, notes and tasks logged on one or more registered records, with an owner, a due time and an outcome, a record's timeline, its next step and a member's open tasks. With recordings, calls and meetings keep recordings and transcripts with speaker segments, and with bookings, confirmed bookings become meetings. See Activities. |
mail-sync | Gmail, Outlook and custom mailboxes synced per member through their own OAuth grant: threads and messages matched to the people and companies they name, logged as email activities, private or shared mailboxes, and the mail members send. See Mail sync. |
segments | Saved filter trees over one registered record type whose matching records are kept in Postgres, refreshed on demand or on a schedule, with an event for each record that enters or leaves. See Segments. |
assignment | Queues that pick an owner for a new record by round robin or weighted round robin among their members, within a territory filter, with a log of every pick. See Assignment. |
enrichment | Company and person profiles from People Data Labs or a custom provider, stored per record and provider, filling only empty columns, with a backlog of records never or long ago enriched. See Enrichment. |
sequences | Multi-step outreach: email, wait and task steps that run per recipient on an enrollment program, sent from the recipient's mailbox through mail-sync, with a reply ending the run, retries for failed sends and counts per sequence. See Sequences. |
lead-scoring | Scores people, and optionally companies, under a score model whose rules read the record, its segments, its mail activity and its enrichment, and rescores the records that changed. See Lead scoring. |
posts | Forum and feedback boards: posts with up and down votes, roadmap statuses, pins, locks and merged duplicates, replies through comments, and reports, hiding and bans through moderation. See Posts. |
content | Content entries per organization: typed pages and posts with slugs, locales and translation groups, scheduled publishing on a block timer, publishing gated by approvals, and a public read by slug for anon. See Content. |
qualifications | Qualification types (certifications, licences, skills) with a validity in months and optional evidence, requirements naming who must hold them, holdings of members, companies and assets that expire, a gap report, the holders qualified on a date, expiry notifications, and holdings granted from course certificates. |
shifts | Shift templates that generate shifts on weekdays, shifts planned in draft and published per team and location, assignments checked for overlap, approved leave, required qualifications and rest time, open shift requests, swaps between members, availability, a roster, planned hours against contract hours, and time entries from worked shifts. |
medications | A medication list per organization, orders on any registered record with a dose, route, schedule and an as-needed maximum per day, orders imported from a pharmacy, planned doses, doses recorded as given, refused, skipped or missed with a second check for high-risk medication, and a chart per record. See Medications. |
forecasts | Forecast snapshots per period and currency, with a copy of the deals behind each number and a deal-by-deal comparison of two snapshots. See Forecasts. |
field-history | A trigger per tracked table that records the column, old and new value, author and time of each change, read with the record's permission. See Field history. |
collections | Favorites (a member's ranked stars on any registered record) and lists (named, static collections of one record type for a user, a team or the organization), whose entries stay hidden unless the caller can read the record. See Collections. |
deals | Deals on pipelines: amounts in minor units, a company and contacts, a deal team, line items, forecast calls with attainment, close-date slips, a next step, locking and batched edits with per-change rejections. See Deals. |
tasks | Issues and tasks on pipelines: identifiers, parents without cycles, several assignees, priority 0 to 4, estimates, start, end and due dates, locking, projects, iterations, batched edits and a progress tree. See Work items. |
quotes | Quotes with line items and totals, a revision chain, a public link the customer accepts, rejects or asks changes through, expiry, and quotes from deals. See Quotes. |
invoices | Invoices an organization sends its own customers: drafts with lines, a gapless number on issue, payments recorded on the ledger, credit notes, void and write-off, overdue and aging per currency, and invoices from accepted quotes. See Invoices. |
sla | Service levels on any registered record: first response, next response and resolution clocks from a policy per type and priority, business hours, pauses while the record waits, and warnings and breaches a job records. See Service levels. |
goals | Goals per period for a member, a team or the organization, with progress the database computes for won deals, completed work items and paid invoices, or a value the app keeps. See Targets. |
hiring | Jobs and applications on a pipeline per job, candidates from config.recordTypes, scorecards per stage, interviews, and hire, reject and withdraw events for the app to act on. See Hiring. |
employees | Employees with or without an account, a manager, team, job title, employment type and status, an org chart that refuses cycles, offboarding, employees from hired applications, and private details and a contract history behind employees.view_sensitive. See Employees. |
field-encryption | Per-owner data keys in Vault that app table columns and custom fields encrypt with, drop_field_key to shred an owner's values, and no searchable equality. See Field encryption. |
rls-guard | An event trigger that enables row level security on every new table outside the Supabase-managed schemas. Install it as postgres, which supautils lets create event triggers. See below |
invitations and organizations need memberships and access, so adding one
pulls those in as well. They read the active tenant from the source in
blocks.permissions.activeTenant: by default the tenant the server resolved for the
request, then the claim named by auth.tenant.claim (tenant_id by default).
The roles come from blocks.permissions.roles. Change modules through blocks (see
below) rather than by editing
the files: upgrade rewrites them, and doctor reports a hand edit.
When the config's authorization provider
has a token hook that owns the memberships claim (tokenHook.ownedClaims),
add tenant stops, because two hooks would write that claim. Pass
--allow-hook-overlap to write it anyway,
for example to keep the helpers while you migrate. Modules that need tenant,
such as invitations, are written without --allow-hook-overlap, with tenant as a
dependency and a note: its memberships table backs has_organization_role(), and no
hook should call membership_claims(). entitlements needs tenant only
with auth.entitlements.memberships: "tenant": with a provider, it reads the
provider's memberIds functions instead. See
entitlements with an authorization provider.
select better_supabase.track_updated_at('public.customers');
select better_supabase.track_actor('public.customers');
select better_supabase.audit('public.customers', ignore => '{updated_at}');
create policy "admins update" on public.customers for update to authenticated
using (organization_id in (select better_supabase.member_organization_ids('{owner,admin}')))
with check (organization_id in (select better_supabase.member_organization_ids('{owner,admin}')));member_organization_ids() returns the user's organizations as a set, so Postgres runs
it once per statement and compares each row against the result. Calling
has_organization_role(organization_id) in a policy runs it once per row instead; keep
that one for functions and single checks. with check stops an update from
moving a row into an organization the user can't manage.
Admins can invite members, viewers and other admins. Only an owner, or the
service role, can invite an owner, and the invitee has to confirm their email
address before accept_invitation adds them.
Module tables use gen_random_uuid() keys. Postgres 18's uuidv7() gives
time-ordered keys that keep indexes compact, and the modules move to it once
hosted Supabase runs Postgres 18
(supabase/postgres#2051).
Errors raised by the modules carry a stable code in the hint field, for example
SLUG_RESERVED, SLUG_INVALID, INVITATION_INVALID, INVITATION_EXPIRED,
INVITATION_ROLE_FORBIDDEN or INVITATION_EMAIL_UNCONFIRMED. They come back as
typed DbErrors through the repository.
Scope and naming
A block's rows belong to a tenant by default. database.sql.owner sets that for
every block, and blocks.<name>.scope for one block.
| Scope | Rows belong to | Checks |
|---|---|---|
tenant (default) | a tenant, through the memberships module | the access contract: can, tenant_ids_with, is_platform |
user | the signed-in user, whose id the scope column holds | the scope column is the caller's id |
none | one shared space | any signed-in user |
export default defineConfig({
database: { sql: { owner: "user" } },
blocks: { tags: {}, comments: {}, notifications: {} },
});Outside tenant scope a block needs neither the memberships module nor the
access contract, so add leaves them out, and its scope column is
nullable: a user's id by default (default auth.uid()) in user scope, null
in none scope. The block's functions take the same arguments in every
scope. In user scope they replace the scope id a signed-in caller passes
with the caller's own id, and in none scope with null, so one user can't
write into another's rows. none scope admits accounts that signed up and
refuses anonymous sign-ins (the is_anonymous claim). Blocks that need tenants (organizations,
invitations, billing and most business blocks) run only in tenant scope,
and add refuses them in another one; set their scope to tenant to
keep them per tenant while the rest of the app runs per user.
memberships and access always run in tenant scope.
| Runs in | Blocks |
|---|---|
| every scope | tags, comments, and the blocks without tenant data (notifications, profiles, queue, outbox, audit, ...) |
tenant only | every other block that requires memberships or access, and the blocks that require one of them |
In tenant scope each table a client can reach also gets a restrictive
bsb_tenant_scope policy, and so does each tenant table in tables. It
keeps rows to the caller's organizations and to what the block's own
policies grant (an invitee's invitation, a guest's granted invoice, a
user's own rows). Postgres combines permissive policies with or, so a
policy you add to a block table, even using (true), can widen access
within the caller's organizations but never to another organization's
rows.
blocks.memberships.names.organization renames the tenant concept in the SQL
the blocks write:
workspace turns the organizations table into workspaces,
organization_id into workspace_id, create_organization into
create_workspace and member_organization_ids into member_workspace_ids.
export default defineConfig({
blocks: {
memberships: { names: { organization: "workspace" } },
organizations: {},
},
});blocks.<name>.functions renames single functions next to tables and
columns. Its keys are the default names, or the names after the tenant
rename; an unknown function is an error.
blocks: {
tags: { functions: { create_tag: "make_tag" } },
},blocks.<name>.names renames a block's own entities. A string is the new
singular noun; an object takes it as name, plus plural when the English
plural is wrong, url for the page of one row and subject: false to keep
the entity out of the subject registry. A subject registers for search with
its title column and the body columns its block declares; search replaces
them with { title, body } columns of the entity's table, or false keeps the
subject out of search. A bare string for entities renames
the block's primary entity. task: "ticket" turns the tasks table into
tickets, task_assignees into ticket_assignees, create_task into
create_ticket and the subject type task into ticket:
blocks: {
tasks: { entities: { task: { name: "ticket", url: "/tickets/{id}" } } },
contacts: { entities: { company: "account" } },
},An entity rename reaches the TypeScript side too: method names, argument and result keys, event types and the generated types. See Typed blocks.
Every block that owns tables names its nouns this way, from quotes
(quote) and orders (order, cart) to ai-chat (chat, project) and
hiring (job, application, interview). Quotes, invoices, orders,
bookings and forms are also record types, so comments, attachments, tags and
activity can point at them. Chats, AI documents and knowledge documents stay
plain entities: only their owner or scope reads them, and a record type would
open them to every member with the block's read permission. JSON payload keys
the clients read (orderId, promotionId), the /memories path and ledger
account keys stored in rows (invoices:cash:<code>) keep their names.
You can rename the entities of a block you already installed. Change
blocks.<name>.names, then run better-supabase upgrade. It reads the
names from each file's @bsb-names line, compares the old and new module
SQL and writes guarded alter ... rename statements for the tables, columns,
indexes, policies, triggers and functions, so the rows stay where they are.
It also moves the permission keys in a role and permission catalog and the
stored subject_type values (comments, attachments, activity) to the new
names. Each statement checks that the old name still exists, so running it
twice changes nothing. Three things don't move: number sequence keys, outbox
events already recorded and your own hook functions (before_work_item_create),
so rename those yourself. When the two versions of a module don't pair up
object by object, upgrade stops with config_invalid and names the
module.
Some names stay as they are, so the TypeScript clients and event consumers work under any tenant name:
- Function parameters, such as
organizationinlist_members. - Event types and payload keys (
organization.created,organizationId) and permission keys. - The access contract (
can,tenant_ids_with,is_platform).blocks.permissions.functionskeeps its meaning: the templates of thecustommodel. - Tables and columns of your own that a block maps by name.
A tenant name that would rename a table or column to a name a block already
uses is refused. team, for example, can't run with teams, profiles or the
other blocks with a team_id column.
better-supabase gen writes the names to blocks.generated.ts, and
defineBlocks makes the block clients call the renamed functions; see
renamed blocks.
Existing tables: managed and custom
Each module has a contract: the functions policies, other modules and the
TypeScript side call. blocks.<module>.ownership decides what stands behind it.
| Ownership | The module writes |
|---|---|
managed (default) | its tables, policies and functions, and over a table your schema already has, only the columns it lacks |
custom | nothing: you write the contract functions, and doctor checks them |
better-supabase blocks list --installed marks custom modules, and blocks view --sql <module> shows
the signatures a custom module must provide. Not every module supports
custom; memberships and access do.
Over your own tables
A managed block decides per table whether to create it. The CLI reads the
tables your app already has: your declarative schema files, or the schema
snapshot or live database for an app on migrations. When one of them is at the
block's default name, or at the name blocks.<name>.tables maps, the block
skips its create table for it. It adds only the columns it needs that your
table lacks, with add column if not exists (nullable unless the column has a
default), and writes its functions, policies, triggers and indexes over your
table. Tables the app doesn't have are created as usual. Most block tables can
run this way, and an optional column can still map to null to turn its
feature off.
There is no setting for this. An ownership: "adopt" left from an older
version fails config validation until you delete it or run
better-supabase codemod. The block's policies and
triggers on your table are named bsb_<table>_<command> and bsb_<name>,
and it never recreates your table or revokes your grants.
Your own schemas explains what the CLI detects,
the names, the doctor findings and how block files are protected.
The other keys rename what the module reads and writes, so an app keeps its own names:
export default defineConfig({
blocks: {
memberships: {
tables: { memberships: "public.organization_users" },
columns: { memberships: { tenant: "organization_id", lastUsedAt: null } },
options: { claimFormat: "map" },
},
invitations: { permissions: { invite: "organization.members.invite" } },
},
});| Key | What it sets |
|---|---|
ownership | managed or custom |
schema | the schema of the module's functions and managed tables (database.sql.schema, then better_supabase); queue takes none, and access keeps its functions in better_supabase |
tables | logical table to table or schema.table; null for an optional table you don't have |
columns | logical table to logical column to column name; null for an optional column; { column, required: true } for an optional column the table must have (a bare name equal to the default does nothing) |
idType | the tenant id type: uuid (default), text, bigint or integer |
permissions | block action to permission key, checked through the access contract |
options | module options, listed on each module's page |
hooks | where the module looks for the app's SQL hooks |
events | false stops the module writing its events to the outbox |
audit | false stops the module writing its actions to the audit log |
api | a schema for the Data API that gets entry points for the module's functions (database.sql.api by default; see below), or false for none |
ownTablePolicies | block (default) or app: whether the module adds its bsb_ policies, permissive and restrictive, on your tables (database.sql.ownTablePolicies by default; see keeping your own policies) |
indexes.skip | create index names the module should not create, when one of your indexes already covers them (for example invoices_tenant_status_idx). A name the module does not create is an error. BS390 reports an index that is a prefix of another. |
better-supabase add --adopt <block> --tables <schema.table>
proposes the tables and columns of a block entry from the tables in
the database and reports what can't map, and
add --preset <code> --adopt
does the same for every block of a preset that has tables under its default
names.
A column of your table keeps the type the module writes, which is text for
names, kinds and subject types. A few of those may be an enum or a domain
instead, because the module casts what it writes through
better_supabase.as_column_type and compares as text: status columns, the
tags kind and subjectType, the numbering entity and the profiles
locale. Any other text
column the module writes a parameter or computed value into must take a text
value: upgrade and add --adopt refuse an enum there when the schema files
declare it, and doctor reports it as BS342. A
column the module only writes string literals into may be an enum whose
labels include those literals.
organizations and profiles also read the columns your own schema files add
to their managed table: the module copies them on writes and returns them from its reads. A name the module
already uses is refused. A not null column without a default is required on
input; one with a default (such as risk text not null default 'low') may
be left out and the database fills it, and it is still required on output.
Extending blocks
shows how to type them in TypeScript.
Calling a module over the Data API
The module schema holds tables and helpers that policies call, so it never
belongs in [api] schemas (doctor reports it as
BS312). To call a module from a browser or an
isolate without a Postgres connection, give it an API schema:
blocks: {
settings: { api: "api" },
notifications: {
api: { schema: "api", functions: ["list_notifications", "notification_counts"] },
},
},To give every module the same API schema, set database.sql.api once. A module that
sets its own api keeps it, and api: false leaves a module without entry
points. database.sql.schema works the same way for the module schema.
sql: {
api: "api",
},
blocks: {
settings: {},
notifications: {},
queue: { api: false },
},add then writes a security invoker function in api for each module
function that anon, authenticated or service_role may execute, or only
those listed in functions, with the same name and arguments, granted to the
same of those roles. A list in functions adds to the functions the block's
TypeScript client calls, which always get a wrapper: with
functions: ["check_rate_limit"], rate-limit still writes
check_rate_limits for checkAll and purge_rate_limits for purge. The wrapper runs as the caller, so the module's own
permission checks and RLS still apply, and a service function such as
flag_definitions stays callable by service_role only. Each wrapper
revokes execute from public and from every API role it isn't meant for,
so alter default privileges in schema api grant execute on functions to anon (a common setup for an exposed schema) doesn't let anon call a
member or service function. Helpers that a
module grants to authenticated only so its own policies and triggers can
call them get no entry point, and functions refuses them:
guard_membership_role (organizations), invitation_tenant_ids and
platform_invitations_readable (invitations), comment_subject_readable
(comments), the attachment_* and object_clean policy helpers
(attachments), incoming_webhook_tenant_ids and
incoming_webhook_subject_readable (incoming-webhooks), data_export_object_allowed
(data-lifecycle), mfa_satisfied (mfa) and session_active (sessions). A
wrapper an earlier upgrade wrote for one of them is dropped. Add the
schema to [api] schemas in config.toml and pass it to the transport:
const client = createSettings({
settings,
transport: rpcTransport(supabase, { schema: "api" }),
});An app server that reaches the database only through PostgREST uses the same wrappers with a service-role client, for example for feature flags and announcements:
const transport = rpcTransport(serviceClient, { schema: "api" });
const flags = createFlagsProvider({ transport });
const announcements = createAnnouncements({ transport });
const outbox = createOutbox({ transport, source: "https://app.example.com" });An unknown table, column or module, or an ownership a module doesn't support, stops
add and upgrade with the valid names. Each file's header records the
module version and mode (-- @bsb-block tenant@2 managed), and the data migration
records them in better_supabase.blocks. An option a module doesn't read
stops add as well, so a misspelled option can't fall back to its default
without notice. Only blocks.permissions takes the access keys (model, roles,
functions, activeTenant and the rest).
Audit log
audit(table) records every insert, update and delete of a table. The other
parameters name and filter what it writes:
select better_supabase.audit(
'public.customers',
ignore => '{updated_at}',
redact => '{tax_id}',
category => 'billing',
event_prefix => 'customer',
target_type => 'customer'
);audit() keeps these settings on the table's bsb_audit trigger, as the
JSON argument of audit_row_change, and writes no rows. So a call in a
schema file leaves nothing a schema diff refuses (pg-delta rejects a table
that has rows after loading the schema), and the generated migration carries
the trigger with its settings; no data migration is needed. You can also
write the trigger yourself, which pg-delta orders after the table:
create trigger bsb_audit after insert or update or delete on public.customers
for each row execute function better_supabase.audit_row_change(
'{"ignore": ["updated_at"], "redact": ["tax_id"], "event_prefix": "customer"}'
);The argument takes ignore, redact, key_columns (the primary key by
default), category, event_prefix, target_type, tenant_column and
label_column, tenant_path, tenant_function, archive_column and
archive_value. audit_settings(table) returns a table's settings.
archive_column names a soft-delete or status column. An update that sets it
is recorded as <event_prefix>.archived and one that clears it as
<event_prefix>.restored, instead of .updated. A column counts as set when
it isn't null and isn't false, such as archived_at or deleted_at; with
archive_value it counts as set when it equals that value, for a status
column:
select better_supabase.audit('public.projects', archive_column => 'archived_at');
select better_supabase.audit('public.orders', archive_column => 'status', archive_value => 'archived');Keep the column out of ignore and redact, which the trigger reads it
through. Block tables with an archivedAt column pass it on their row audit
trigger.
Writes the secret key makes for a member
server.admin({}, { as: userId }) sends the x-bsb-actor header on every
request. better_supabase.acting_member() returns that user for a service
caller (the service_role key or a direct admin connection) and null for
anyone else, so a signed-in user cannot name another user by sending the
header. The audit trigger and audit_event() record the acting member as the
actor when auth.uid() is null, and track_actor() uses it for created_by
and updated_by. The audit entry's actor_kind is user, like a write the
member made, and actor_role keeps service_role. Only service_role may
execute acting_member(); the audit and actor triggers run as their owner, so
they call it for every writer. Your own function that calls it must be
security definer too. server.admin({}, { as: userId, headers }) sends
headers on every request as well, such as the request id and client address
the audit log reads, so the entry keeps them.
A child table without a tenant column can still record its tenant.
tenant_path => 'group_id -> directory_groups.organization_id' reads
organization_id from the directory_groups row that group_id references;
each further -> table.column continues from there. audit() resolves every
hop through a single-column foreign key and fails when a hop has none.
tenant_function => 'public.tenant_of(jsonb)'::regprocedure instead names a
function that receives the row as jsonb and returns the tenant. The trigger
tries the row's own tenant column first, then the path, then the function.
When ignore is not empty, audit() installs two triggers: bsb_audit for
inserts and deletes, and bsb_audit_update with a WHEN clause that skips an
update where only ignored columns changed, so a write such as last_run_at
never starts the trigger. Calling audit() again without ignore, or
unaudit(), removes bsb_audit_update.
Each audit() call replaces every setting on the trigger: the last call
wins, and arguments it leaves out go back to their defaults. A second
audit('public.customers') therefore clears the app's ignore and
redact. Code that registers a table the app may already audit, such as another
package's migration, reads audit_settings(table) first
and passes the app's ignore and redact back in, or leaves the call to the
app. The pgTAP file upgrade writes for each audited table checks the
settings of the last call in the schema files and migrations, so it fails
when a function or seed replaces them at run time. A later call in a
migration changes what that file expects, so review the generated test in
the diff.
Tables
registered before this release keep their rows in audited_tables, and the
trigger reads them while it has no argument; calling audit() again moves
them onto the trigger.
redact columns are stored as [redacted] in the old and new records. The
event type is <event_prefix>.created, .updated or .deleted (the table
name without a prefix), and tenant_column overrides the tenant column for
this table. Events that are not row changes, like a sign-in or an export, go
through audit_event. It returns the entry id, and a repeated
idempotency_key returns the first entry instead of writing a second:
select better_supabase.audit_event(
event_type => 'invoice.exported',
category => 'billing',
tenant => '6d1f...',
metadata => '{"format":"csv"}',
idempotency_key => 'export-42'
);A job, a webhook handler or an admin tool that records an event as the
service role can say who acted and from where: actor_id, actor_kind
(such as job or api-key), actor_label, request_id (the request it
handled), scope (an adopted log's own value, or memberships and platform),
and, with the restricted table, ip, user_agent and session_id. The function takes these only from the
service role and direct admin connections; for any other caller it uses
auth.uid(), the request's JWT and headers, so a user can't record an event
in someone else's name. For the service role these three come only from
the arguments, never from the request, so a server that calls
audit_event over the Data API doesn't store its own address and user
agent as the user's. An event whose restricted, ip, user_agent and
session_id are all empty writes no restricted row. Without the restricted
table, passing ip, user_agent or session_id fails with 22023, as
restricted does:
select better_supabase.audit_event(
event_type => 'export.finished',
actor_kind => 'job',
actor_label => 'Nightly export',
ip => '198.51.100.7',
user_agent => 'export-worker/1.0',
restricted => '{}'
);The impersonation columns come from the caller's act claim. An event
about impersonation that the admin's own token records, such as a support
session starting or ending, passes them as support_session,
impersonated_by and impersonation_reason. The service role may pass any
values; another caller only itself as impersonated_by, and only from a
token without an act claim, whose values win otherwise:
select better_supabase.audit_event(
event_type => 'support_session.started',
category => 'security',
support_session => session_id,
impersonated_by => auth.uid(),
impersonation_reason => reason
);An app's own security definer function that acts for a client, such as a
role editor saving permissions, runs as its owner but still carries the
client's JWT, so audit_event would replace its actor context with the
client's. Such a function calls better_supabase.audit_event_trusted
instead: it takes the same arguments and honours actor_id, actor_kind,
actor_label, scope and the request details from its caller, with
actor_id defaulting to auth.uid(). Only its owner, the service role and
the roles in trustedRoles may execute it, so a client can't call it to
forge an actor, and the module writes no Data API entry point for it:
create function public.save_role_permissions(role_id uuid, keys text[])
returns void language plpgsql security definer set search_path = '' as $$
begin
-- write the permissions, then:
perform better_supabase.audit_event_trusted(
event_type => 'role.permissions_saved',
record_id => role_id::text,
actor_kind => case when better_supabase.is_platform('roles.manage') then 'support' else 'user' end,
scope => 'platform'
);
end;
$$;The module options (blocks.audit.options):
| Option | Default | What it does |
|---|---|---|
tenantColumn | auth.tenant.column | the tenant column of audited tables |
appendOnly | true when managed | triggers reject updates, deletes and truncate; only purge_audit_log, running as its owner, deletes |
readPolicy | false | members read their tenants' entries with the read permission, platform staff all of them with readAll (needs access) |
impersonators | show | hide keeps the impersonation columns from authenticated |
restricted | false | old and new records, IP address, user agent and metadata go to a separate audit_events_restricted table that only service_role reads; without it, audit_event(restricted => ...) fails with 22023 |
eventRoles | ['service_role'] | the roles that can call audit_event |
trustedRoles | [] | roles besides the owner and service_role that can call audit_event_trusted, such as the owner role of your definer functions when it isn't the module's owner |
eventCategory | system | the category of an audit_event call without one |
eventSource | app | the source of an audit_event call without one |
exempt | [] | schema.table globs (public.*_archive) that doctor BS315 doesn't expect an audit trigger on |
tenantLabel | the organizations module | schema.table.column that tenant_label copies, matched on tenantLabelKey (id by default), for apps without the organizations module |
values | none | only over a log of your own: its values for scope, actorKind, outcome, source and category, see below |
metadataColumns | none | only over a log of your own: its own columns that audit_event fills from a key of its metadata, such as { ticket_id: "ticketId" }; the value is converted to the column's type, a missing key leaves the column to its default, and list_audit_events returns the columns under columns |
keepMappedMetadata | false | keeps the keys metadataColumns maps in the stored metadata too; by default they are removed, since the columns hold them |
requestIdHeader | x-request-id | the Data API header request_id is read from when the better_supabase.request_id setting is empty |
correlationIdHeader | x-correlation-id | the Data API header correlation_id is read from when the better_supabase.correlation_id setting is empty |
add and upgrade read the audit(...) calls and bsb_audit triggers in
your schema files and migrations, and write one pgTAP file for all audited tables to database.sql.testsDir
(supabase/tests/900_better_supabase_audit_tables.test.sql). It
checks that the table has the bsb_audit trigger and is registered with the
same ignore and redact lists, then runs an insert, an update and a delete
on a copy of the table and checks the entries: one per change, without the
ignored columns, with the redacted values masked. supabase test db runs it
with your other tests, and upgrade --check fails when a registration changed
and the file is stale. A later unaudit(...) call or drop table removes
the table's checks from the file on the next upgrade. Calls with computed arguments, such
as audit(format(...)), are skipped.
Dropping an audited table also drops its registration: the module installs
a sql_drop event trigger (bsb_audit_forget_dropped) that deletes the
table's row from better_supabase.audited_tables, so install the module as
postgres, which supautils lets create event triggers. unaudit takes the
table name as text, so a migration can still call
select better_supabase.unaudit('public.old_notes') after the table is
gone; it then clears the registrations of tables that no longer exist.
Tables dropped before the event trigger existed keep their rows; the
module's data file deletes them, so the next add --adopt migration cleans
them up, and doctor BS322 reports any that remain
on a database.
An app with its own audit table keeps it: map blocks.audit.tables.log and
columns.log to your names, and null the columns you don't want (the row
snapshots or supportSession, for example). The module then writes into your
table and never creates it; it adds the columns it needs that your table
lacks.
When your log uses its own words for the same values, map them with
options.values: the module's value to yours, per column. Writes store your
values, and list_audit_events (and so createAudit) reads them back as
the module's, so exports and OCSF mapping keep working. Doctor reports the
option as migration-only (BS314).
export default defineConfig({
blocks: {
audit: {
tables: { log: "public.activity_log" },
columns: {
log: {
tenant: "workspace_id",
actorKind: "actor_type",
tenantLabel: "workspace_name",
},
},
options: {
values: {
scope: { tenant: "workspace", platform: "global" },
actorKind: { user: "member", service: "api" },
outcome: { success: "ok", failure: "error" },
source: { database: "db" },
category: { data: "record", system: "platform" },
},
tenantLabel: "public.workspaces.title",
tenantLabelKey: "workspace_id",
},
},
},
});source covers row changes (database) and audit_event calls alike, and
category maps the defaults (data for row changes, eventCategory for
events) and any category a registration or an audit_event call names.
Values without a mapping are stored as they are. Two module values can't map
to the same stored value, because reads couldn't tell them apart.
Context columns
Every entry also records what an audit page shows, as it was at the time:
| Column | What it holds |
|---|---|
actor_kind | user, service, support, agent, impersonation, oauth-client or system, from the claims |
actor_label | the actor's full_name metadata or email |
tenant_label | the organization's name, with the organizations module or options.tenantLabel |
target_label | the value of the table's label_column (audit(..., label_column => 'title')), or audit_event's |
summary | audit_event(summary => ...) |
request_id | the request id, see below |
correlation_id | audit_event(correlation_id => ...), or the request's correlation id, see below |
scope | tenant, or platform for entries without a tenant |
With restricted, the restricted table also keeps the session_id claim and
changed_values: { column: { old, new } } for each changed column (every
column on insert and delete), redacted like the records and cut at 1000
characters, so one change can be revealed without the whole rows. A managed
log has all of these columns; on a log of your own the module writes the
ones that columns.log and columns.restricted don't map to null.
Request and correlation ids
Row changes and audit_event calls record the request id and the correlation
id of the request that made them, so an audit page can show one user action
as the event plus the rows it changed. Each id comes from the first of:
- the
audit_eventargument (request_idcounts only for the service role and direct admin connections, like the other actor details), - the transaction-local setting
better_supabase.request_idorbetter_supabase.correlation_id, which a server sets over direct Postgres withset_config(..., true), - the Data API request header,
x-request-idorx-correlation-idunless therequestIdHeaderandcorrelationIdHeaderoptions name others.
better_supabase.request_id_or_null(value) keeps an id of 1 to 128
characters from A-Z, a-z, 0-9 and . _ : ; , @ / + = - and turns
anything else into null, so an invalid value falls through to the next
source. The ids are metadata a client can set; never use them for access
decisions. createServer
sends both on every request without configuration.
A managed log indexes correlation_id. Group an action's entries with the
for_correlation_ids filter, or in SQL:
select occurred_at, op, event_type, table_name, record_id, changed
from better_supabase.audit_events
where correlation_id = 'checkout/42'
order by occurred_at, id;From TypeScript, audit.list({ correlationId: ctx.correlationId }) returns
the same entries.
Registering many tables
A project with a hundred tenant tables doesn't write a hundred audit(...)
lines by hand. audit_schema_calls prints them for every table in a schema
with the tenant column, minus exempt name patterns:
select better_supabase.audit_schema_calls('public', 'organization_id', '{audit_%,%_archive}');Paste the output into a schema file, and override single tables with their
own audit(...) call after it. Static calls keep their place in a pg-delta
diff; a loop over the catalog in a schema file runs before the tables exist
(doctor BS318). For a migration or a one-off script,
audit_schema(schema, tenant_column, exempt) registers the tables that aren't
registered yet and returns how many. Doctor BS315
flags any table left out.
The audit block reads the log from TypeScript: a list
query, NDJSON and OCSF exports, and retention per tenant. In SQL,
list_audit_events lists the entries the caller can read, and
reveal_audit_entry(entry) returns an entry's restricted details and records
the read as audit.revealed. reveal_audit_entries(entries) does the same
for a list of entry ids, such as one page of an export: it returns the
details of the entries the caller may reveal, skips the rest, and records
one audit.revealed entry per tenant with the ids in metadata.entries.
Retention
The audit log, the webhook inbox and delivery log, the rate-limit counters
and the job archives only grow. Each module has a purge function that deletes
rows older than an interval, at most batch rows per call (10,000 by
default), and returns how many it deleted. Only service_role can call them.
| Function | TypeScript | Deletes |
|---|---|---|
purge_audit_log(older_than => '1 year') | purgeAuditLog(source, options) | audit_events entries older than older_than, or than the tenant's own interval |
purge_webhooks(older_than => '30 days') | inbox.purge(), purgeWebhookInbox(source) | processed messages; include_dead => true also deletes dead ones |
purge_job_archive(queue, older_than => '7 days', dead_older_than => '30 days') | jobs.purge() | completed jobs, and dead jobs after their own retention (pgmq.a_<queue>, or job_messages on the table backend) |
purge_idempotency_keys() | idempotency.purge() | expired idempotency keys |
purge_webhook_deliveries(older_than => '30 days') | webhooks.purge() | succeeded and canceled outgoing deliveries; include_dead => true also deletes dead ones |
purge_rate_limits() | rateLimit.purge() | counters whose window has ended or whose rule was removed |
purge_usage_history(older_than => '400 days') | usage.purgeHistory() | usage history entries |
purge_usage_events(older_than => '30 days') | usage.purgeEvents() | idempotency keys of recorded usage |
Schedule them with pg_cron at a quiet
hour. Enable the extension once (create extension pg_cron with schema pg_catalog), then:
select cron.schedule('purge-audit-log', '15 3 * * *', $$select better_supabase.purge_audit_log()$$);
select cron.schedule('purge-webhooks', '30 3 * * *', $$select better_supabase.purge_webhooks()$$);
select cron.schedule('purge-emails-archive', '45 3 * * *', $$select better_supabase.purge_job_archive('emails')$$);
select cron.schedule('purge-idempotency-keys', '0 4 * * *', $$select better_supabase.purge_idempotency_keys()$$);
select cron.schedule('purge-webhook-deliveries', '45 3 * * *', $$select better_supabase.purge_webhook_deliveries()$$);
select cron.schedule('purge-rate-limits', '*/15 * * * *', $$select better_supabase.purge_rate_limits()$$);Tenants can keep entries for different periods, a plan's retention for
example. Write an audit_retention(tenant) function that returns an interval
(or null for the default) in the schema blocks.audit.callbacks points at, and
purge_audit_log uses it for every entry. Like every SQL hook, it is
optional: the module calls hooks through dynamic SQL, so supabase db lint
passes without them. To decide in TypeScript instead,
call purgeAuditLog from better-supabase/blocks/audit in a scheduled job:
import { purgeAuditLog } from "better-supabase/blocks/audit";
await purgeAuditLog(postgres.admin, {
olderThan: "1 year",
retention: async (tenant) =>
tenant ? await plans.auditDays(tenant) : undefined,
});Each TypeScript method takes the same options in camel case (olderThan in
seconds or as an interval, includeDead, batch) and returns how many rows
it deleted as a Result. Each object also has a purgeJob(options) that
returns a job handler, so the purges can run on the jobs
scheduler instead of pg_cron. They work over a service SQL connection or a
service-role transport, so an app without a direct connection can schedule
them too:
const jobs = createQueue({
sql: postgres.admin,
queues: { purge: v.object({}) },
});
await jobs.schedule("retention", "0 4 * * *", "purge", {}).orThrow();
await jobs.work("purge", async (payload, job, signal) => {
await idempotency.purgeJob()(payload, job, signal);
await jobs.purgeJob({ deadOlderThan: "90 days" })(payload, job, signal);
});When a table holds more old rows than one batch, the next run picks up the
rest; run the job more often, or raise batch, until it keeps up. Keep the
webhook retention above your senders' retry window: a retried message whose id
was purged is stored and processed again.
Support sessions
impersonation records who viewed the app as whom, for
support mode. It needs permissions and audit.
start_support_session(target, reason, ttl, read_only, metadata, tenant)
checks is_platform('impersonation.start') for the caller, ends the caller's
previous session, writes support_session.started to the audit log and returns the
session as jsonb. An admin has one active session (a unique index). It refuses
a target with platform permissions and a writable session unless the options
below allow them. Under the provider access model, a target holds platform
permissions when a row in invitations.options.platformRoles.table names them,
and, with platformRoles.through.where, only when that row's role matches the
condition, so a roles table that also holds tenant roles counts only its
platform ones. end_support_session(session_id) ends it for its admin
(ended_by is admin), a caller with impersonation.revoke (revoked) or the
service role, which alone passes ended_by. expire_support_sessions(),
for the service role only, ends every running session past its expiry with
ended_by set to expired and returns them, so each one gets its
support_session.ended entry. active_support_session called
as the admin checks impersonation.start again. Errors carry IMPERSONATION_FORBIDDEN,
IMPERSONATION_SELF, IMPERSONATION_TARGET_MISSING, IMPERSONATION_TARGET_PLATFORM,
IMPERSONATION_WRITES_DISABLED, IMPERSONATION_TTL, IMPERSONATION_REASON_REQUIRED or
IMPERSONATION_APPROVAL_REQUIRED in the hint.
A start needs a second admin by default (options.approval: "distinct").
The admin asks with request_support_session(target, reason, read_only, metadata, tenant), which runs the same checks as a start and stores a row in
support_requests. Another admin approves it with
approve_support_request(request_id). start_support_session then uses the
newest approved, unused request for the same admin, target and tenant (a
read-only approval never starts a writable session) and records its id and
approver in the support_session.started audit entry. A request is open for
approvalTtl and starts one session.
The requester never approves their own request: approve_support_request
refuses it with IMPERSONATION_SELF_APPROVAL, and the
support_requests_distinct_approver check constraint refuses the row even
for the service role. Clients can read their own requests but can't insert
or update the table. Without an authorization provider, an approver needs
is_platform('impersonation.start') (rename it with
blocks["impersonation"].permissions.approve). With one that sets
isApprover, the module
calls it with {kind} 'support-session' and {subject} the request id
instead. The service role may pass admin_id, approved_by and
approver_id for decisions the server already made; approved_by still
can't be the admin. support_request(request_id) returns a request to the
service role, its requester and its approvers, and
approved_support_request(target, tenant, read_only) the request a start
would use. Errors carry IMPERSONATION_REQUEST_MISSING, IMPERSONATION_REQUEST_DECIDED
(another admin approved it) or IMPERSONATION_REQUEST_CLOSED (expired or used).
A read-only session (read_only true, the default) is refused by every
security definer write granted to authenticated or anon, with
ACTOR_READ_ONLY and SQLSTATE 42501. The same refusal covers a support
act unless read_only is false, an agent act with read_only: true,
an impersonation act or one of another kind, and an act that has
session_id and no kind. Reads are unchanged.
These functions stay callable so the session can be opened and closed:
start_support_session, end_support_session and expire_support_sessions.
check_request stays callable too: it counts the request for the rate limit
and runs before reads.
With an authorization provider, set authorization.functions.actorMayWrite
and the writes call that instead of the built-in check.
| Option | Default | What it does |
|---|---|---|
maxTtl | 4 hours | the longest session start_support_session accepts |
requireReason | true | refuses a start or request with an empty or blank reason |
approval | distinct | none starts without a second admin's approval |
approvalTtl | 1 hour | how long a request stays open for approval and a start |
allowWrites | false | accepts read_only => false |
allowPlatformTargets | false | lets a session target platform staff |
auditCategory | support | the audit log category of support_session.started and support_session.ended |
claimsHook | provider's tokenHook.function, else none | schema.function of your access token hook, for support_target_claims |
The permission keys are impersonation.start, impersonation.read and impersonation.revoke;
rename them with blocks["impersonation"].permissions. The hooks
before_support_start(admin, target, reason, metadata),
after_support_start(session_id) and after_support_end(session_id) run in
the schema hooks.schema names. The module runs over an existing sessions
table: the memberships, readOnly, endedBy and metadata columns are
optional. It still creates support_requests unless tables.requests names
your own table; tables.requests: null needs options.approval: "none".
blocks: {
"impersonation": {
tables: { sessions: "public.impersonation_sessions" },
columns: { sessions: { admin: "impersonator_id", metadata: null } },
permissions: { start: "system.users.impersonate" },
options: { claimsHook: "public.custom_access_token_hook" },
},
},Rate limiting writes
Auth rate-limits sign-ins, but the Data API has no limit of its own: a signed-in
user can call insert or an RPC as often as they like. The rate-limit module
counts writes in PostgREST's
pre-request hook,
before the query runs:
better-supabase add rate-limit-- 5 invites per user per minute, 300 writes per user per minute overall.
select better_supabase.set_rate_limit('/rpc/send_invite', 5, interval '1 minute');
select better_supabase.set_rate_limit('*', 300, interval '1 minute');
-- Per tenant instead of per user: count by the tenant_id claim.
select better_supabase.set_rate_limit('/customers', 1000, interval '1 hour', key_claim => 'tenant_id');
-- Remove a rule.
select better_supabase.set_rate_limit('/customers', null);- A scope is
*, a table path (/customers) or an RPC path (/rpc/send_invite). Every matching rule counts, so*and a path rule both apply. - Only
POST,PATCH,PUTandDELETEcount. GET and HEAD run read-only and may be served by a read replica. APOSTto/rpcfor astableorimmutablefunction also runs in a read-only transaction, socheck_request()skips it instead of failing the call. - Callers without the claim (anonymous) are counted by the right-most
x-forwarded-forhop, the one the API gateway appends; clients can forge the hops before it. The service role is never limited. - Counters live in an unlogged table: fast, and reset after a crash.
- A write over the limit fails with HTTP 429 and a
Retry-Afterheader. The repository returns it as arate_limitedDbErrorwithretryAfterin seconds, andproblemResponse()passes the header on.
The module's data file sets pgrst.db_pre_request on the authenticator
role, and only if no other pre-request function is set. Neither diff engine
captures role settings, so the setting ships in the migration add --adopt
writes. Doctor warns (BS313) when a live database has no pre-request hook, or
one that doesn't call check_request(). If you already have a pre-request
function, keep it and call the check from it. Put it in a schema the Data API doesn't expose, so clients
can't call it through /rpc. Set options.preRequest: false to leave the
setting to your own function: the data file then removes a setting that
still points at check_request() instead of adding one.
export default defineConfig({
blocks: { "rate-limit": { options: { preRequest: false } } },
});create schema if not exists private;
create or replace function private.pre_request() returns void language plpgsql as $$
begin
perform better_supabase.check_request();
-- your checks
end $$;The hook runs only for the Data API. Queries through
better-supabase/postgres and ctx.sql aren't limited.
Limits in route handlers
Public endpoints often limit by something other than a claim: a token in the
URL, an organization, an AI chat thread. hit_rate_limit(scope, key) counts
one hit of key with the same rules and counters, and createRateLimit from
better-supabase/rate-limit calls it from a route handler. rateLimited()
answers a refused hit with a problem+json 429 and Retry-After:
import { createRateLimit, rateLimited } from "better-supabase/rate-limit";
const limits = createRateLimit({ sql: postgres.admin });
export async function POST(
request: Request,
{ params }: { params: { token: string } },
) {
const hit = await limits.check("public-webhook", params.token).orThrow();
if (!hit.allowed)
return rateLimited(hit, { instance: new URL(request.url).pathname });
// handle the request
}Apps that reach the database over the Data API instead of a direct
connection pass a service-role BlockTransport, like the other blocks:
createRateLimit({ transport: rpcTransport(adminClient) }). It calls
check_rate_limit(scope, key, max_requests, period), which returns the same
decision as JSON; with blocks.rate-limit.api set, pass the API schema
as rpcTransport(adminClient, { schema: "api" }). The hooks option runs
around check and purge, and the purgeJob handler calls purge through
them. createBlocks builds it from its shared transport, like the other
blocks.
The limit is the scope's rule from set_rate_limit, or one given per call
(check("chat", threadId, { max: 20, period: "1 minute" })). A scope with
neither fails with RATE_LIMIT_UNKNOWN. Counters are shared by every
instance, unlike an in-memory map on serverless functions.
purge_rate_limits() removes counters without a rule after a day, so keep a
per-call period under a day or define the rule.
Several limits at once
A sign-in route often limits per user, per IP and per organization.
checkAll counts one hit against several limits in one database round trip
(check_rate_limits(hits)), and the hit counts only when every limit allows
it, so a refused attempt leaves all counters as they were. Each limit takes
its own scope and key; two windows on the same key take two scopes, such as
login:minute and login:day:
const hit = await limits
.checkAll([
{ scope: "login:user", key: email, rule: { max: 5, period: "15 minutes" } },
{ scope: "login:ip", key: ip, rule: { max: 50, period: "1 hour" } },
])
.orThrow();
if (!hit.allowed) return rateLimited(hit);blocked names the first limit over its maximum (index, scope, key),
retryAfter is the longest wait of the refusing limits, remaining the
lowest of all, and results holds one decision per limit. The counters are
locked in a fixed order, so concurrent calls over the same keys never
deadlock. A list that names one scope and key twice fails with
RATE_LIMIT_HITS, a scope without a rule or a per-call one with
RATE_LIMIT_UNKNOWN.
Limits as middleware
The Hono and
oRPC adapters wrap check in a
rateLimit() middleware. Responses then carry the RateLimit field of
draft-ietf-httpapi-ratelimit-headers (SPEC_PINS.ratelimitHeaders), and
RateLimit-Policy when the route gives a rule. A refused request gets a
429 with Retry-After. Elsewhere, rateLimitHeader() and
rateLimitPolicyHeader() from better-supabase/server/rate-limit build the two fields.
Enforcing jsonb shapes
Give a json entry a schema and better-supabase add jsonb-schemas adds a
pg_jsonschema
check constraint, so the database rejects rows the generated types would
reject. schema takes a JSON Schema object, or any Standard JSON Schema value
(zod 4, valibot, arktype):
import { toStandardJsonSchema } from "@valibot/to-json-schema";
import * as v from "valibot";
export const CustomerMetadata = toStandardJsonSchema(
v.object({
source: v.string(),
tier: v.optional(v.picklist(["free", "pro"])),
}),
);
export default defineConfig({
gen: {
json: {
"customers.metadata": {
import: "./lib/metadata.ts#CustomerMetadata",
schema: CustomerMetadata,
},
},
},
blocks: ["jsonb-schemas"],
});Each constraint is added not valid and then validated in its own
statement, so existing rows that don't match make the migration fail. Fix
those rows first. On a large table, move the validate constraint statement
to a later migration: adding a not valid check blocks writes only briefly,
and validating takes a lock that lets writes continue. Re-run add after
you change a schema.
Next to each constraint, a before insert or update trigger of the same name
calls pg_jsonschema's jsonschema_validation_errors. A row that fails raises
SQLSTATE 23514 with the hint JSON_SCHEMA_INVALID and the errors as a JSON
array in DETAIL, so the repository returns a validation error with one
issue per schema error, at the column's database name:
// metadata came from a request body as { source: "web", tier: "gold" }
const result = await db.customers.update(id, { metadata });
if (!result.ok && result.error.kind === "validation") {
result.error.issues;
// [{ message: '"gold" is not one of ["free","pro"]', path: ["metadata"] }]
}The check constraint stays for rows written while triggers are off, such as a
restore with session_replication_role = replica; its failures also map to
validation, with one issue for the whole value.
Subject registry
Tags, comments, attachments, reminders and the other modules that attach to
your rows take the record types they attach to from on. Declare the types
once in config.recordTypes, and every block that you don't give its own on
uses the registry.
A record type is lowercase letters, digits, hyphens and underscores, starting
with a letter, such as purchase_order or purchase-order, so a type your
rows already store with hyphens can be registered as it is. Blocks write it
as a string value; a trigger or function named after it takes underscores in
place of hyphens (bsb_field_history_purchase_order), so two types that
differ only there, such as purchase-order and purchase_order, are refused.
import { defineConfig } from "better-supabase/config";
export default defineConfig({
records: {
task: {
table: "public.tasks",
idType: "uuid",
title: "title",
url: "/projects/{project_id}/tasks/{id}",
permissions: { read: "tasks.read", update: "tasks.update" },
rank: { column: "rank", group: "status" },
},
customer: { table: "public.customers", title: "name" },
},
blocks: ["memberships", "permissions", "subjects", "tags", "comments"],
});| Key | Default | What it sets |
|---|---|---|
table | required | The table, as table or schema.table |
id | id | The id column |
idType | compared as text | The id column's type (uuid, bigint), so lookups use its index |
tenant | organization_id | The tenant column, false for a subject without one, or the id column for the tenant table itself |
title | none | The column subject_title returns |
url | none | A path template whose {column} placeholders subject_url fills from the row |
permissions | none | Action to permission key, or to { key, rows, owner, also, check } (see below); read is the key modules check before they attach to the row |
scope | none | A record scope to check the keys in, for subjects without a tenant |
cascade | none | Delete a module's rows when the subject row is deleted |
deletedAt | none | A soft-delete column; rows where it is set count as gone |
search | none | title and body columns for search, plus description, exclude, from and watch (Search) |
rank | none | The rank column and an optional group column (such as status) that move uses |
readAccess | tenant | record makes custom-fields show a value only to members who can read the record, through the read entry |
team | none | { actions }: the actions a record team grants on each row (Record teams) |
auditReads | false | Log each read through the blocks' read functions in the audit log (Record read log) |
The tenant table can be a record type too. Set tenant to its id column, so
every row is its own tenant and a block keyed on the record writes the row
into that organization only:
recordTypes: {
organization: {
table: "public.organizations",
idType: "uuid",
tenant: "id",
title: "name",
},
},A block's on works three ways:
- unset: the block uses every registered type. Blocks that need a tenant
skip the types with
tenant: false. - a list of names,
on: ["task"]: the block uses those registered types, and an unknown name failsgen(doctor reports it as BS346). - an object: each entry merges onto the registered one, and the block's
keys win, so an entry for a registered type can leave out
tableandidType.add,upgrade,genand doctor read the merged entry. A type the registry lacks needs its owntable.
incoming-webhooks never falls back to the registry, because its subjects are the
tables that inbound events write to.
Subject types are lowercase letters, digits and underscores. The
notifications block's own on keys may also contain hyphens
(time-off-request), because its subject_type column takes any text.
The subjects module installs four functions in the better_supabase
schema. Each runs as the caller, so the subject table's own policies decide
what is visible:
| Function | Returns |
|---|---|
subject_types() | The registered types |
subject_title(subject_type, id) | The title column, or null when the row is hidden, deleted or the type has no title |
subject_url(subject_type, id) | The url template filled from the row, or null |
subject_titles(refs) | A jsonb array of { type, id, title, url } for up to 500 { type, id } refs, as the caller; hidden, deleted and unknown refs are left out (Subjects) |
can_subject(subject_type, id, action) | True when the caller can see the row and holds the action's key from permissions in the row's tenant |
can_subject_for(user, subject_type, id, action) | The same for another user, service role only: the row exists and can_user grants the action's key; false for an action without a key or a provider that can't answer for others, and a share link never counts |
An action without a key in permissions checks only that the caller can see
the row. The service role passes every key check.
Actions granted per row
An action can be granted in more ways than a tenant key. Give it an object instead of a key:
export default defineConfig({
records: {
file: {
table: "public.files",
idType: "uuid",
permissions: {
read: { key: "file.read", rows: "file" },
share: { key: "file.update", rows: "file" },
},
},
thread: {
table: "public.threads",
permissions: { share: { owner: "owner_id" } },
},
},
});| Key | Grants the action when |
|---|---|
key | the caller holds the key in the row's tenant, or on the record through scope, as a plain key does |
rows | the authorization provider lists the row among the rows of that resource the caller holds key on (needs key) |
owner | the uuid column it names holds the caller's id |
also | never alone: the caller must also hold this key in the row's tenant (or on scope) |
check | the SQL function it names, (subject_id <idType>) returns boolean, returns true for the row and the caller |
Any one of key, rows and owner grants the action. With also, the
caller needs that key too, so { key: "file.read", rows: "file", also: "files.access" } asks for a row grant (or the key) and the tenant key both.
rows is the resource as the provider
names it in SQL (file_node); it needs blocks.permissions.model: "provider"
and a provider with the rowsWith template (see
Authorization providers). For
can_subject_for, row grants count only when the provider also has
rowsWithFor, and owner compares the column with the given user.
Blocks that check a record action in their own policies run the same grants on
the record's row. The attachments upload and manage checks, and the
deadlines read check when blocks.deadlines.permissions.read is the record
type's read key, let in a member whose key covers only their own or their
team's records: register upload: { key: "jobs.update", rows: "jobs" }, and
an own-level grant attaches files to that member's jobs only. A plain key is
still checked in the tenant (ADR 1094).
check names a schema-qualified function, such as
better_supabase.drive_node_writable, that answers for the caller
(auth.uid()). Use it when the grants live in your own tables, as the drive's
per-node grants do. Alone it decides the action; next to key, rows or
owner the function must return true as well, so
{ key: "drive.read", check: "better_supabase.drive_node_readable" } asks
for the key and a grant on the node. A null result counts as false.
can_subject still requires that the caller can see the row.
can_subject_for can't run the function for another user, so it returns
false for that action. The function runs inside every check, so keep it a
cheap stable lookup.
Blocks that act on a record ask can_subject for the action when the record
type declares it, on top of their own key: tags checks tag before it
puts a tag on a record or takes it off, custom-fields checks fields before
it sets or deletes a value, share-links checks share before it creates,
lists or revokes a link, and comments follows read, comment and
moderate. A record type that declares none of them keeps the block's own
checks.
A block that checks whether the caller may read a record (tags, attachments,
share links, versions, relations and the others that take on) reads the
same read entry: with rows or owner, the key, the provider's row grants
and the owner column each grant the read, as in can_subject. An on entry
that sets its own permission keeps that key.
Record teams
Give a record type a team to put people on one record: a patient's care
team, the account team on a customer, the investigators on a case. Members of
the record's team get the listed actions on that row, on top of what their
tenant role grants.
export default defineConfig({
records: {
patient: {
table: "public.patients",
title: "name",
permissions: { read: "patients.read" },
team: { actions: ["read", "write"] },
},
customer: {
table: "public.customers",
title: "name",
permissions: { read: "customers.read", write: "customers.update" },
team: { actions: ["read", "write"] },
},
case: {
table: "public.cases",
title: "title",
team: { actions: ["read"] },
},
},
blocks: ["memberships", "permissions", "teams", "subjects"],
});An action with a permissions entry stays open to holders of that key, and
the team grants it too, so a care team reads its patients without
patients.read. An action that only team lists, such as write on
patient, is granted to the team alone. A type with a team needs a tenant
column, because each membership row belongs to the record's tenant.
A type a block registers, such as person from
contacts, takes team and
auditReads on its entity in blocks.<name>.names. Setting either on an
entity that isn't a subject, or that sets subject: false, fails when the
config loads.
The subjects block stores the members in subject_members. A row names a
user or a team from the teams block, a role and the
days it counts (starts_on and ends_on, both included). A membership
counts from starts_on through ends_on, so access stops the day after a
membership ends, without a job to revoke it. A row the
access-requests block grants
also has ends_at, the exact time it stops counting, and emergency for
emergency access; the client
reads it as endsAt.
| Function | What it does |
|---|---|
create_subject_member(subject_type, subject_id, user_id, team_id, role, starts_on, ends_on) | Puts a user or a team on the record, or reopens their membership in that role with the new dates |
end_subject_member(member_id, ends_on) | Ends a membership; it counts through ends_on, today by default |
list_subject_members(subject_type, subject_id) | The record's team, current and past, for a caller who can read the record |
my_subjects(tenant, subject_type, page_size, cursor) | The records whose team the caller is on today, with their roles, title and URL, up to 200 a page |
has_subject_role(subject_type, subject_id, roles) | Whether the caller is on the record's team today in one of roles, for a rule only some roles pass |
Adding and ending a membership needs subjects.manage in the record's tenant
(the admin role has subjects.*), or can_subject(..., 'manage') on a type
that declares a manage action. The service role may always call them. With an
authorization provider, list
subjects.manage among its permissions or set
blocks.subjects.permissions.manage to a key it has. Roles
are lead and member unless you set
blocks.subjects.options.recordTeam.roles. The functions fail with these
hints:
| Hint | When |
|---|---|
SUBJECT_MEMBER_INVALID | The type has no team, both or neither of user and team are set, an unknown role, or bad dates or ids |
SUBJECT_MEMBER_NOT_FOUND | The record or the membership doesn't exist |
SUBJECT_MEMBER_FORBIDDEN | The caller may not manage the record's team |
A caller reads their own membership rows, those of their teams, every row in
a tenant where they hold subjects.manage, and the team of any record they
can read. add and end emit subject_member.added and
subject_member.ended when the outbox is installed, and the audit log
records them under access.
The team counts in can_subject, can_subject_for and the blocks that call
them. Blocks that check a record's read entry inline (tags, attachments
and the others that take on) still check only the key. The represents
relation kind from contacts accepts only targets of a type with a team,
when one is declared.
Record read log
Set auditReads: true on a type to log who reads its records. It needs the
audit block and a tenant column.
export default defineConfig({
recordTypes: {
patient: {
table: "public.patients",
title: "name",
permissions: { read: "patients.read" },
team: { actions: ["read"] },
auditReads: true,
},
},
blocks: ["memberships", "permissions", "audit", "subjects", "comments"],
});The read functions of the blocks then call record_subject_read after their
own access check, for a record the caller may read: record_summary
(subjects), list_comments (comments), list_activity with a subject
(timeline), list_status_history (state-machine) and get_field_values
(custom-fields) when it returns values. Each read writes a subject.accessed
entry under the read category (Read logging).
A function that runs as plain SQL, such as list_attachments or
activities_of, doesn't log; call reads.log from the screen that shows it.
| Function | What it does |
|---|---|
record_subject_read(subject_type, subject_id, purpose) | Logs that the caller read the record, with an optional purpose of 500 characters |
subject_access_log(subject_type, subject_id, since timestamptz, max_rows int) | Who read the record and when, newest first, up to 500 entries |
record_subject_read logs nothing for a type without auditReads, a missing
record, a record the caller can't read or a call without a user, so the
service role's reads aren't logged. A second read of the same record by the
same member within blocks.subjects.options.reads.collapseSeconds (60 by
default, 0 logs every read) writes no new entry, unless it gives another
purpose or only one of the two was under
emergency access.
Under a read-only support session a logged
read fails with ACTOR_READ_ONLY, as every audited read does.
subject_access_log is for the holders of audit.read in the record's
tenant, the leads on the record's team today, the record's own
guest and a guest who represents it with act
authority. It fails with these hints:
| Hint | When |
|---|---|
SUBJECT_READ_INVALID | The type doesn't log reads, or the purpose is too long |
SUBJECT_READ_NOT_FOUND | The record doesn't exist |
SUBJECT_READ_FORBIDDEN | The caller may not see who read the record |
A plain select over the Data API is not logged: PostgREST runs it without
calling a function. To make every read go through the logging functions,
revoke select on the record's table from authenticated and read it
through the blocks' functions or your own security definer function that
calls record_subject_read.
With a registry, gen also emits the types in database.types.ts:
import {
type RecordRef,
type SubjectType,
subjectTypes,
} from "./lib/supabase/schema";
const ref: RecordRef<SubjectType> = { type: "task", id: taskId };Doctor reports a registered table or column the database lacks (BS331) and a registered table without row level security (BS332).
Merging subject records
When two rows of a subject table are merged, one call moves every module's rows from the dropped record to the kept one:
perform better_supabase.merge_subject_refs('public.customers', keep::text, drop::text);Each module that stores rows per subject installs a handler, and
merge_subject_refs runs them all:
| Module | What moves |
|---|---|
comments | Comments; the activity feed stays on the dropped record |
attachments | Attachments |
reactions | Reactions, except one the same person already left on the kept record with the same emoji |
tags | Taggings, except a tag the kept record already has |
relations | Links on either end; a link that becomes a self-link or a duplicate is deleted |
guests | Guest grants, except a grant the guest already has on the kept record |
passes | Passes issued for the record |
billable-time | Rates on the record, except a rate the kept record already has for the same member and day |
leases | Leases of the party |
donations | Gifts, pledges and receipts of the donor |
dispatch | Work orders opened for the record |
shipments | Shipments sent for the record |
contracts | Contracts with the record as their counterparty |
The function isn't granted to any API role. Call it from your own security definer function that has already checked the caller, as the parties
merge_companies and merge_people functions do. Merging doesn't re-check a
relation kind's single or acyclic rule.
To move your own tables in the same call, add a function with the signature
(subject_table text, keep text, drop text), owned by the role that owns the
migrations, and give it the comment better-supabase:subject-merge. The
dispatcher skips marked functions another role owns.
create function app.deals_subject_merge(subject_table text, keep text, drop text)
returns void language plpgsql security definer set search_path = '' as $$
begin
if subject_table = 'better_supabase.companies' then
update app.deals set company_id = keep::uuid where company_id = drop::uuid;
end if;
end;
$$;
revoke execute on function app.deals_subject_merge(text, text, text) from public, anon, authenticated;
comment on function app.deals_subject_merge(text, text, text) is 'better-supabase:subject-merge';RLS on every new table
better-supabase add rls-guard installs an event trigger that enables row level
security on every table created with create table, create table as or
select into, so a table never reaches the Data API without RLS. The trigger
also fires after alter table, so disable row level security is undone right
away. Tables in
the Supabase-managed schemas (auth, storage, realtime, extensions
and the others) and in pg_* schemas are skipped.
create table public.notes (id bigint primary key, body text);
-- relrowsecurity is now true; add policies before granting access.A table with RLS and no policies denies every API role, so add its policies
in the same migration. Apply the migration as postgres: event triggers
need a superuser, and on Supabase the supautils extension lets postgres
create them. Tables that already exist keep their setting.
Keeping files current
Every file starts with a header that marks it as managed. Its number comes from the module's position in the registry, so its path stays the same when you add other modules. List the modules you use in the config:
export default defineConfig({
database: { sql: { testsDir: "supabase/tests" } },
blocks: ["audit", "queue", "invitations"],
});better-supabase upgrade rewrites those files after an upgrade, and
upgrade --check fails in CI when a file is out of date. Use
blocks view --sql <module> to copy a module into a hand-written migration instead.
add, upgrade and add --adopt take --dry-run to show what they would write, and
--tests-dir <dir> overrides database.sql.testsDir for the pgTAP module.
| Option | Default |
|---|---|
database.sql.workflow | detected from supabase/config.toml (Workflows) |
database.sql.dir | supabase/schemas |
database.sql.prefix | 900_better_supabase |
database.sql.testsDir | supabase/tests |
database.sql.schema | better_supabase, for every module that sets no schema |
database.sql.api | unset; the Data API schema for every module that sets no api |
database.sql.ownTablePolicies | block; app keeps every module's policies off your tables unless it sets its own ownTablePolicies |
blocks | [] |
Upgrading modules
When a release changes a module in a way the schema diff can't follow (a renamed column, a backfill that must run before a new constraint), the module's version goes up and the release ships a forward step. Run the upgrade after you update the package:
better-supabase upgradeIt reads the version from each file's @bsb-block line (a file without one,
written before the line existed, counts as version 1). It then writes the
forward steps into a migration in the migrations folder next to your
config.toml and rewrites the module files. Under pg-delta that migration is
<timestamp>_better_supabase_reviewed_upgrade_<hash>.sql, marked
-- destructive: reviewed: it holds only what a schema diff can't express
(renames, backfills, expression changes), and the module files hold every other
statement, so upgrade never writes a schema migration. Under the other
workflows it is <timestamp>_better_supabase_block_upgrade_<hash>.sql. Review
the migration, then create the schema migration afterwards, so the steps run
first. upgrade --check exits with 1 when a module is behind, a
file is stale or a data statement is in no data migration, and --dry-run lists the steps without writing. The pgTAP
files a module writes for your tables (the audit tests, say) carry no module
version; upgrade --check keeps them current, and upgrade leaves them
out.
A renamed function, table or claim keeps working for at least one minor
version. The module file keeps a wrapper under the old name (a view for a
table), marked -- Deprecated since, and doctor reports code that still uses
it (BS309). A renamed column has no wrapper: upgrade renames it, and
doctor reports the old name in your SQL before you upgrade. A module declares
these moves in NAMES.migrations (the version, the table, its old name and
the old column names), and upgrade renders them after your table and
entity renames, so the step renames the right table under any config. The
stability page lists
what each module guarantees.
Existing triggers
track_updated_at() and audit() warn when the table already has a trigger
that does the same work (a moddatetime or touch_updated_at trigger, or
another audit trigger), because both would run on every write. Pass
replace_trigger => true to drop the existing trigger in the same call:
select better_supabase.track_updated_at('public.customers', replace_trigger => true);
select better_supabase.audit('public.customers', replace_trigger => true);Doctor reports a table that still has both (BS310).
Rendering modules in code
better-supabase/sql exports what add and upgrade use, for build scripts
and tests that write the files themselves. moduleLayout(config) returns the
paths, renderBlocks returns the files with their managed headers (dependencies
included), and resolveBlocks lists the modules a set of names pulls in.
import { resolveConfig } from "better-supabase/config";
import { moduleLayout, renderBlocks, resolveBlocks } from "better-supabase/sql";
import config from "../better-supabase.config.ts";
const layout = moduleLayout(resolveConfig(config, process.cwd()));
const modules = resolveBlocks(["audit", "queue"], layout).map((m) => m.name);
const files = renderBlocks(["audit", "queue"], layout);compileReadSets turns the read sets in generated.ts into the SQL views and
functions that better-supabase gen writes. moduleBody(name, layout)
returns one module's SQL without its header, customContracts the functions
custom-mode modules must provide, and moduleFileVersion(contents) the version
and mode in a file's header.
moduleFilePaths(names, layout) maps each module a set of names pulls in to its
schema and test paths without rendering it. modulePermissionKeys(blocks, names)
lists the permission keys those modules check, with the action, the key after
blocks.<module>.permissions and whether a tenant or a platform check asks for
it. Under blocks.permissions.model: 'provider', add and doctor (BS411) check
each key against the provider's permissions; a script can do the same:
import { resolveConfig } from "better-supabase/config";
import { modulePermissionKeys } from "better-supabase/sql";
import config from "../better-supabase.config.ts";
const { sql, authorization } = resolveConfig(config, process.cwd());
const scopeOnly = new Set(
(authorization?.permissions ?? [])
.filter((entry) => entry.sqlComplete === true)
.map((entry) => entry.key),
);
for (const { module, action, key } of modulePermissionKeys(
blocks,
blockNames,
)) {
if (!scopeOnly.has(key)) console.error(`${module}.${action}: ${key}`);
}Functions only the service role may call
better_supabase.is_service_role() is true for the service_role key and for
a direct admin connection (postgres or supabase_admin without a token),
and false for anon and authenticated. Use it as the guard of your own
functions that only a server, a cron job or a migration may call, instead of
copying auth.jwt() ->> 'role' = 'service_role' into each one:
create or replace function private.reset_counters(tenant uuid)
returns void
language plpgsql
security definer
set search_path = ''
as $$
begin
if not better_supabase.is_service_role() then
raise exception 'only the service role may reset counters'
using errcode = '42501', hint = 'COUNTERS_FORBIDDEN';
end if;
update private.counters c set value = 0 where c.organization_id = reset_counters.tenant;
end;
$$;Most block functions check the same condition inline; a few, such as the
invoices block, accept only a service_role token. The prelude file that
every module install writes defines the function.
Forbidden or not found
better_supabase.row_visible(rel, column, value) says whether the calling API
role sees the row of rel whose column equals value through the table's
select policies. A security definer function runs past row security, so use
it to answer a refused action with "forbidden" for a caller who can see the
row and "not found" for anyone else, without revealing the row. The invoice
functions decide their refusals this way (ADR 1088). It isn't granted to the
API roles, so call it from a security definer function:
if not found_with_permission then
if better_supabase.row_visible('public.projects', 'id', archive_project.project_id) then
raise exception 'not allowed' using errcode = '42501', hint = 'PROJECT_FORBIDDEN';
end if;
raise exception 'no such project' using errcode = 'P0002', hint = 'PROJECT_NOT_FOUND';
end if;Sub-queries inside a policy run with the function owner's rights, and an error answers false.
The check reads the token's role claim and falls back to session_user. A
pgTAP test that runs set role authenticated without setting
request.jwt.claims still connects as postgres, so the function returns
true there. Set the claims ({"role":"authenticated"}) to test a client.
Memoize a value for one transaction
better_supabase.memo_get(key) and better_supabase.memo_set(key, value) keep
a text value for the rest of the transaction, over set_config(..., true).
PostgREST runs one request in one transaction, so a policy helper that is
expensive and security definer can compute its answer once and every later call
in the statement, or in the request's other statements, reads it back:
create or replace function private.visible_organization_ids()
returns uuid[]
language plpgsql
security definer
set search_path = ''
as $$
declare
cached text := better_supabase.memo_get('visible_organization_ids');
begin
if cached is not null then
return cached::uuid[];
end if;
return (
select (better_supabase.memo_set('visible_organization_ids', ids::text))::uuid[]
from (select array_agg(organization_id) as ids from private.memberships
where user_id = auth.uid()) m
);
end;
$$;The empty string reads as unset. Key names are yours; use a prefix for the
library that owns them (acme. for a helper of the library acme), so two helpers
never share a key. A memo lives only as long as the transaction, so a pooler
that reuses the connection never leaks it to another request. Combine it with
the cost 1000 on can and can_subject and the visible-rows pruning of the
messaging policies: those keep Postgres from calling a helper per row, the
memo keeps one call per transaction cheap. The functions ship with the
updated-at module. Doctor BS206 and
BS243 point at the memo.
Policies
better-supabase/sql builds, renders and reads row level security policies.
policy() makes a typed Policy, renderPolicy() writes the create policy
statement, and getPolicies() and getGrants() read them back from a script
without being fooled by comments, strings or dollar-quoted bodies.
import { policy, renderPolicy } from "better-supabase/sql";
renderPolicy(
policy({
table: "app.notes",
name: "bsb_notes_read",
command: "select",
roles: ["authenticated"],
using: "better_supabase.is_member(tenant_id)",
}),
);renderPolicy writes the create policy statement only. A schema diff drops a
policy the files no longer declare, so the statement needs no drop policy if exists before it.
Every policy a block module generates is named bsb_<name>, shortened with a
hash when the name passes 63 bytes. bsbPolicyName() returns the name a
generated policy carries for the name a module wrote, and codemod naming
uses it to write one alter policy ... rename to for each policy of an
installed block, so no row moves.
Checks follow the same rule. A check a block adds is named
bsb_<table>_<column>_check (bsb_<table>_check when it reads several
columns), and codemod naming renames the checks of an installed block with
one loop over the catalog.
The rule DSL
A Rule is a small tree: public, owner, member, can, compare,
null, and, or and not. rulePolicy() renders it into a policy that
calls only better_supabase.is_member, better_supabase.can, better_supabase.owns and better_supabase.uid, and
renderRulePolicy() puts the tree in a -- @bsb rule comment above the
statement. getRulePolicies() recovers the tree and reports inSync: false
once someone edits the SQL by hand, so a UI knows to show the SQL instead of
the tree.
policyFunctionsSql() returns the better_supabase schema functions uid, owns, is_member and can.
uid() and owns() are fixed. is_member() and can() delegate to the
functions you name, so your own tables or an authorization library answer
them. A hand written policy is kept as it is; disallowedPolicyCalls() lists
the calls in it that are not one of the four functions, which is how you check
it against the same rule.
Table tags
A table you own carries its better-supabase features as @bsb tags in the table comment (ADR 0102). Free text and tags share the comment, and only the block that starts at @bsb is parsed. Tags are separated by ;, and a tag takes key=value pairs.
import {
parseBsbComment,
setBsbTag,
commentOnTableSql,
} from "better-supabase/sql";
const comment = "Invoices. @bsb subject title=number; realtime";
parseBsbComment(comment);
// { text: "Invoices.", tags: [{ name: "subject", args: { title: "number" } }, { name: "realtime", args: {} }] }
const next = setBsbTag(comment, "audit", { name: "audit", args: {} });
commentOnTableSql("public.invoices", next);
// comment on table public.invoices is 'Invoices. @bsb subject title=number; realtime; audit';setBsbTag with undefined removes a tag and keeps the text.
Last updated on
Typed blocks
Rename a block's entities once in the config, and get typed config keys, renamed clients, subjects, name constants and input schemas from better-supabase gen.
Your own schemas
Keep your own declarative schema files next to the block files. The CLI detects your tables, and each block runs over the ones you already have and creates the rest.