# better-supabase blocks

> 185 SQL modules with typed clients. Install one with `npx better-supabase add <name>`.

## Identity & access

- [Actor stamping](https://bettersupabase.com/blocks/created-by.md): Sets created_by on insert and updated_by on every write from auth.uid(); an update keeps created_by and the impersonation stamp. Service writes keep the values they send.
- [Data API grants](https://bettersupabase.com/blocks/grants.md): Writes the complete Data API privileges of the tables and functions in the `expose` config for anon, authenticated and service_role, or derives table grants from the policies. A project with default privileges turned off grants new tables to no Data API role.
- [MFA enforcement](https://bettersupabase.com/blocks/mfa.md): mfa_satisfied() for restrictive policies: true when the caller has no verified factor, or verified one in this session (aal2).
- [Access contract](https://bettersupabase.com/blocks/permissions.md): can(), tenant_ids_with() and is_platform(): one permission contract for policies and SQL modules, over a roles list, a role and permission catalog, an authorization provider or the app's own functions (blocks.permissions.model).
- [Session revocation](https://bettersupabase.com/blocks/sessions.md): session_active() for restrictive policies: false once the caller's session was signed out or expired, or the user was banned or deleted, so revoked access tokens stop working before they expire. options.policies writes the policy on every table.
- [SSO and SCIM](https://bettersupabase.com/blocks/sso.md): Verified email domains with auto-join and SSO enforcement, SAML providers per organization registered with Supabase Auth, and SCIM 2.0 users and groups that provision memberships and map groups to roles.
- [Subjects](https://bettersupabase.com/blocks/subjects.md): The app-wide subject registry from config.recordTypes: subject_title, subject_url, subject_titles, can_subject, can_subject_for and record_summary for every registered type, my_work across the installed blocks, record teams (subject_members, create_subject_member, end_subject_member, list_subject_members, my_subjects) that grant subjects.<type>.team actions, read logging for types with subjects.<type>.auditReads (record_subject_read, subject_access_log), and Realtime presence on presence:<type>:<id> for readers of the subject.
- [Access requests](https://bettersupabase.com/blocks/access-requests.md): 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 on request or when it expires. Emergency access opens a record at once and waits for a review.
- [Identities](https://bettersupabase.com/blocks/identities.md): Links an email address or a chat user to an app user or a contact. Rows come only from a one-time code the signed-in user issues and the service redeems, or from a confirmed address in auth.users.

## Tenancy & accounts

- [Tenant memberships and permission helper](https://bettersupabase.com/blocks/memberships.md): Memberships with roles, member_organization_ids() and has_organization_role() for RLS policies, and membership_claims() for the access token hook. Adopt an existing memberships table through blocks.memberships.
- [Invitations](https://bettersupabase.com/blocks/invitations.md): invite_member(tenant, email, role) returns a single-use token whose hash is stored; accept_invitation(token) checks the signed-in user's confirmed email and, again, the inviter's authority. Roles follow the access model; a null tenant invites to a platform role, stored in platform_invitations.
- [Reserved slugs](https://bettersupabase.com/blocks/reserved-slugs.md): A slug format and length check and a list of reserved words (admin, api, www, ...), enforced by a trigger.
- [Organizations](https://bettersupabase.com/blocks/organizations.md): create_organization(attrs) with slug rules and an after-create hook, a deferred owner check, an assignment ceiling, and member functions (role change, remove, leave, transfer ownership) on the access contract.
- [Profiles](https://bettersupabase.com/blocks/profiles.md): A profile per user, created on sign-up from auth metadata with a unique username, an email mirror, column-level update grants and a guard on columns the service owns.
- [Settings](https://bettersupabase.com/blocks/settings.md): Per-user, per-organization and platform-wide settings as key-value jsonb rows. Users read and write their own; organization settings check settings.read and settings.update; platform settings check a platform permission per key. Keys with a JSON Schema in options.schemas get a pg_jsonschema check.
- [Teams](https://bettersupabase.com/blocks/teams.md): Tenant teams and their members. Inbox assignment uses these rows instead of its own team tables.
- [Custom domains](https://bettersupabase.com/blocks/domains.md): Hostnames an organization serves its app on: custom domains verified by a DNS TXT record, subdomains of the platform domain, one primary per organization, and resolve_hostname() for the proxy.
- [Legal entities](https://bettersupabase.com/blocks/legal-entities.md): Several legal entities inside one organization, each with its VAT and chamber numbers, bank account, logo and fiscal settings and one default per organization. Settings resolve from the legal entity to the organization to the code default, and options.on adds a nullable legal_entity_id to invoices, quotes, orders, numbering, accounting, inventory locations and settings; null means the default entity.
- [Document templates](https://bettersupabase.com/blocks/document-templates.md): Templates for invoices, credit notes, quotes, orders, dunning letters, delivery notes and statements per legal entity and language, reusable text blocks, one versioned variable contract per document type, and render_document, which returns the variables, the chosen template and its texts. An issued invoice or credit note is frozen with the template version it used, so rendering it again never changes it.
- [Seeds](https://bettersupabase.com/blocks/seeds.md): seed_tenant_defaults(tenant, variants, locale) applies the defaults every installed block declares, in install order. The organizations block calls it when an organization is created.

## Collaboration

- [Comments](https://bettersupabase.com/blocks/comments.md): Comments on any record as its conversation on the messaging core: whoever reads the record reads them, with replies, mentions and mention groups, anchors, files, edits with history, pins, resolved threads and read markers. The author and the mentioned follow the record and its followers hear of new comments (with notifications), and a comment becomes a work item (with tasks).
- [Attachments](https://bettersupabase.com/blocks/attachments.md): Files linked to records in a tenant: a record per file, a private bucket whose policies only accept an upload a pending record expects, and reads only for scanned files. confirm_attachment() emits attachment.uploaded for the app's scan job. options.publicBuckets serves chosen buckets by public URL, for media such as product images.
- [Share links](https://bettersupabase.com/blocks/share-links.md): Hashed share links, view counts and per-user state. The token is returned once. Resolving a link hashes the token the caller presents, so a stored plaintext token keeps working after it is hashed. A link can take a password, checked with bcrypt and rate-limited per link, and turn off downloads.
- [Reactions](https://bettersupabase.com/blocks/reactions.md): Emoji reactions and up or down votes on any subject and on messages, with per-tenant custom emoji, counts and a vote score per subject under the subject's own read rules and a realtime topic per tenant.
- [Moderation](https://bettersupabase.com/blocks/moderation.md): Reports on any subject, a review queue, decisions (approve, hide, remove, restore, ban) with a log, user bans and an automatic hide threshold. Reviews moderate through it, and it hides and removes messages, comments included.
- [Guests](https://bettersupabase.com/blocks/guests.md): People outside the organization (clients, contractors) 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. Never members, never through an authorization library.
- [Messaging](https://bettersupabase.com/blocks/messaging.md): Conversations and messages shared by channels, record discussions and the inbox: channels, direct and group messages, one conversation per record, members with read markers and notification levels, threads, mentions, edits with history, pins, resolved threads, scheduled sends, files and reactions. Members, the tenant or the record's readers read a conversation; Realtime pings carry ids only.
- [Channels](https://bettersupabase.com/blocks/channels.md): Named conversations on the messaging core: public channels anyone in the tenant reads and joins, private ones for their members, each with a topic, a purpose and an optional linked record. Create, rename, join, leave and browse; messages, threads, typing and read markers come from messaging.
- [Activity feed](https://bettersupabase.com/blocks/timeline.md): A timeline_entries feed that activitySink() fills from outbox events, filtered by can_subject and joined with the subject's audit entries, notification deliveries and workflow runs when subjects, audit, notifications and workflows are installed.
- [Posts](https://bettersupabase.com/blocks/posts.md): Forum threads and feedback posts on boards. Replies are comments on the messaging core, votes are reactions, and each post is a moderation item members can report. Feedback posts move through a status from open to done.
- [Acknowledgements](https://bettersupabase.com/blocks/acknowledgements.md): Members confirm they read the current version of a record: assignments to a member, a team or a role, a due date per assignment, a click or a completed signature, and a reminder once a version is overdue.
- [Meetings](https://bettersupabase.com/blocks/meetings.md): Meetings with an agenda, attendees and roles, minutes per agenda item, decisions the attendees vote on, and action items that become tasks.

## Notifications & messaging

- [Notifications](https://bettersupabase.com/blocks/notifications.md): In-app notifications sent through a security definer notify(): one event per change, per-recipient read, dismissed and resolved state, per-channel deliveries, subject subscriptions, preferences with a tenant override, and realtime on a private topic.
- [Chat SDK state](https://bettersupabase.com/blocks/chat-sdk-state.md): The Chat SDK StateAdapter in Postgres for better-supabase/chat-sdk: thread subscriptions, token locks, a TTL cache, capped lists and per-thread queues under a key prefix, plus the bot installations per workspace with a credential_ref instead of the token. Service role only.
- [Shared inbox](https://bettersupabase.com/blocks/inbox.md): Conversations with contacts across the in-app widget and chat channels, on the messaging core: inboxes, members and teams, contacts who are people of the contacts block, messages and internal notes with scanned files, mentions, assignment, bot hand-off, read state, delivery status, stored webhook events, message templates, scheduled replies and reply drafts, including ai drafts staff review. Staff read with inbox.read; contacts read their own conversations without the notes; Realtime pings carry ids only.
- [Push devices](https://bettersupabase.com/blocks/push.md): The push tokens of each user's devices (Expo, FCM, APNs or Web Push) with RLS, behind register_push_device and unregister_push_device for the user and push_tokens_for and prune_push_tokens for the service role. With notifications, push_tickets keeps Expo's tickets per delivery for the receipt check. better-supabase/blocks/push registers Expo devices and sends through the Expo Push API.

## Growth & engagement

- [Feature flags](https://bettersupabase.com/blocks/flags.md): Feature flags with variants, targeting rules over tenant, user, plan, role, custom contexts such as brand and shared segments, overrides, and a scheduled percentage rollout split across weighted variants, bucketed by SHA-256. Every save records a revision you can restore. flag_enabled() goes in policies; createFlagsProvider() evaluates the same way for OpenFeature and the Flags SDK.
- [Onboarding](https://bettersupabase.com/blocks/onboarding.md): Onboarding checklists per user or organization, run as enrollment programs: the completed steps, completed by hand or by an outbox event type. Organization checklists check onboarding.read and onboarding.complete.
- [Waitlist and invite codes](https://bettersupabase.com/blocks/waitlist.md): A waitlist with positions and approvals, and hashed invite codes with a use limit, an expiry and an optional organization and role. waitlist_admit() backs a before-user-created hook that only lets approved addresses or valid codes sign up.
- [Announcements](https://bettersupabase.com/blocks/announcements.md): In-app announcements for everyone, tenants, roles or plans within a time window, with per-user dismissals and a Realtime broadcast when they change. Staff manage them with announcements.manage on the platform.
- [Scores](https://bettersupabase.com/blocks/scores.md): Tenant-editable scoring models: rules (a filter tree over the rules field catalog worth points) and metrics (a number times a weight, or a record's vote score) that write versioned scores with bands to any subject. Lead scoring and health scoring are models.

## CRM & sales

- [Parties](https://bettersupabase.com/blocks/contacts.md): Companies and people an organization works with: lifecycle stages, owners, party roles (customer, supplier and so on), payment terms with early-payment discounts and credit restrictions, credit limits with a soft or hard block, a language, delivery preferences per document type and a supplier status, who works where with a role and a primary contact, each person's addresses on channels (the inbox's contacts), domain and email dedupe, merges and keyset-paged search.
- [Activities](https://bettersupabase.com/blocks/activities.md): 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.
- [Deals](https://bettersupabase.com/blocks/deals.md): 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.
- [Quotes](https://bettersupabase.com/blocks/quotes.md): Quotes with sections, optional lines, discounts, prices with or without tax, tax per rate and a deposit; published versions; a public link or the signed-in portal the customer accepts, rejects or asks changes through; expiry; and quotes from deals. With catalog, a line that names a product variant takes its price and title.
- [Targets](https://bettersupabase.com/blocks/goals.md): 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.
- [Contracts](https://bettersupabase.com/blocks/contracts.md): Contracts with counterparties from draft through review and signature to active, expired or terminated, built on signatures, versions and reminders. Values are bigint minor units; renewal terms (auto-renew, renewal period, notice days) schedule a reminder before the notice deadline; obligations carry due dates and owners.
- [Mail sync](https://bettersupabase.com/blocks/mail-sync.md): Gmail, Outlook and other mailboxes synced per member through their own OAuth grant: threads and messages linked to the people and companies they involve, logged as email activities, and a record of the mail members send, with opens and clicks per message and per template version.
- [Segments](https://bettersupabase.com/blocks/segments.md): Saved filters over a subject type, such as companies in a region or deals over a size: the matching records materialized as members, refreshed on demand or from a cron, with an event when a record enters or leaves.
- [Enrichment](https://bettersupabase.com/blocks/enrichment.md): Company and person data from an enrichment provider, such as a company's industry and size or a person's title: one result per provider, the empty columns a match fills, and a list of the records due for a cron.
- [Forecasts](https://bettersupabase.com/blocks/forecasts.md): Snapshots of the deals forecast call over time: the totals by category and every deal they counted, a list per period, and what changed between two snapshots (added, removed, won, lost, moved).
- [Sequences](https://bettersupabase.com/blocks/sequences.md): Multi-step outreach sequences whose steps send email through mail-sync, create work items or wait. Each sequence runs as an enrollment program, and a reply on the thread or from the recipient's address ends their run.
- [Lead scoring](https://bettersupabase.com/blocks/lead-scoring.md): Scores people, and optionally companies, under a tenant-editable score model. Each record's columns, enrichment status, segments and mail opens, clicks and replies feed the model, and the record is scored again when any of them change.

## Work management

- [Tags](https://bettersupabase.com/blocks/tags.md): Tenant tags with a kind, and a link from a tag to a subject. Over the app's tables it can use one link table per subject.
- [State machine](https://bettersupabase.com/blocks/state-machine.md): Allowed status transitions as the caller, a history row and a status.changed event. A machine can also write a stages timeline and keep a lifecycle row (pause, flags, pinned version). Each machine is a subject table named in options.machines, or a config.recordTypes type.
- [Custom fields](https://bettersupabase.com/blocks/custom-fields.md): Field definitions, options and typed values. A sensitive value is readable only with the field's permission. Inline layout stores the definition on the value row.
- [Saved views](https://bettersupabase.com/blocks/saved-views.md): Named, ranked list states (filters, sort, columns, grouping, density) for one user, a team or the whole tenant.
- [Relations](https://bettersupabase.com/blocks/relations.md): Typed links between subjects (blocks, parent, relates, or your own kinds), with inverse names, cycle checks, one-target kinds, walks and rollups.
- [BulkActions actions](https://bettersupabase.com/blocks/bulk-actions.md): One action over many rows: up to a limit in one call with a result per row, and larger sets as a background run on the jobs queue that runs as the user who started it.
- [Search](https://bettersupabase.com/blocks/search.md): A search_documents index kept up by triggers from each config.recordTypes search entry, with search(q) as the caller (websearch, trigram prefixes, can_subject, hybrid with embeddings), search_page for browsing and cursor paging with facet filters, and recents and favorites from the share-links user state.
- [Approvals](https://bettersupabase.com/blocks/approvals.md): Approval requests with steps per subject type and action: approvers by permission, role, team, user or the requester's manager, a required count, delegation, expiry and reminders. Tenants tighten the configured policies with conditions and a confirm or authorize mode, and an approval is consumed once against a request fingerprint. The final approval runs a state-machine transition or a job.
- [Pipelines](https://bettersupabase.com/blocks/pipelines.md): Tenant-editable pipelines for any registered subject: ordered stages whose categories map to open, success or failure, a stage history with time in stage, board totals per currency and a status mapping that runs through state-machine.
- [Work items](https://bettersupabase.com/blocks/tasks.md): 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.
- [Service levels](https://bettersupabase.com/blocks/sla.md): 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.
- [Collections](https://bettersupabase.com/blocks/collections.md): Favorites (a member's ranked stars on any registered record), lists (named, static collections of one subject type owned by a user, a team or the organization) and saved items (a member's records to come back to, with a note and a reminder), with entries hidden unless the caller can read their record.
- [Assets and locations](https://bettersupabase.com/blocks/assets.md): 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; bookings resources and work items can name an asset.
- [Dispatch](https://bettersupabase.com/blocks/dispatch.md): Field service work orders at asset locations: a schedule board of technicians' slots, a status lifecycle from scheduled to done, day routes with ordered stops, and the parts each job used, linked to assets or inventory when those blocks are installed.
- [Incidents](https://bettersupabase.com/blocks/incidents.md): Incidents with a severity, a status timeline of updates, the components they affect and a postmortem, plus a public status page: component status, public incident updates and uptime history, readable anonymously through one function that returns only the fields marked public.
- [Assignment](https://bettersupabase.com/blocks/assignment.md): Queues of members that pick an owner for new leads, deals or tickets: round robin or weighted, within a territory written as rule conditions, with a log of every pick.
- [Risks](https://bettersupabase.com/blocks/risks.md): A risk register per organization: risks numbered RSK-0001, scored on a configurable likelihood by impact matrix before and after controls, with an assessment history snapshotted in versions, treatment, scheduled reviews, barriers linked through relations, and a heatmap.
- [Cases](https://bettersupabase.com/blocks/cases.md): Cases per organization: nonconformities, complaints, incidents, near misses, observations, improvements, change requests and audit findings of tenant-editable kinds, numbered per kind, each kind on its own pipeline, with a root cause, containment and corrective actions as work items, an effectiveness check, public intake through forms, and a close guard that refuses to close while a blocker remains.
- [Audits and inspections](https://bettersupabase.com/blocks/inspections.md): 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.
- [Maintenance](https://bettersupabase.com/blocks/maintenance.md): Preventive maintenance plans that fall due by time, by a meter or by an RRULE, meter readings, calibration records, and the dispatch work orders the plans open with their spare parts. Technicians and calibrations can require qualifications.
- [Warranty](https://bettersupabase.com/blocks/warranty.md): Warranty claims for an asset: the supplier or manufacturer, the covered amount, a status, a decision and attachments on the claim.
- [Laboratory information system](https://bettersupabase.com/blocks/lims.md): Samples, test methods with specification limits, results through forms, a nonconformity case for every out of specification result and instruments from assets that must hold a valid qualification.
- [Appraisals](https://bettersupabase.com/blocks/appraisals.md): Performance appraisals: review cycles that can follow an enrollment program and carry a rubric of weighted competencies, one appraisal per person with self, peer and manager reviews, anonymous peer reviewers, goals, calibration sessions that keep their reason, and sign-off through approvals.
- [Deadlines](https://bettersupabase.com/blocks/deadlines.md): Platform-owned rule sets per jurisdiction and kind, versioned and approved once with a content hash: groups of cited rules with conditions, exceptions and counts, and the deadlines computed from a subject's facts per group: due on a date, unknown with the facts still missing, or the reason there is none.
- [Security advisories](https://bettersupabase.com/blocks/advisories.md): Security advisories for a software vendor: products and versions with CycloneDX components, vulnerabilities enriched from OSV, EPSS and the CISA KEV catalog on a schedule, OpenVEX statements per version, and CSAF 2.0 advisories with a /.well-known/csaf handler, linked to incidents and risks through relations.
- [Option sets](https://bettersupabase.com/blocks/option-sets.md): Tenant-editable items for a field such as priority or severity: ordered items with a label, color, icon and a level the record keeps in its own column, replacement when an item is removed, and starter items per brand.

## People

- [Time tracking](https://bettersupabase.com/blocks/time-entries.md): Time entries with one running timer per member and no overlaps, on any record, billable with a rate. Weekly timesheets go through approvals, and a submitted or approved week is locked.
- [Hiring](https://bettersupabase.com/blocks/hiring.md): 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.
- [Employees](https://bettersupabase.com/blocks/employees.md): Employees with or without an account, a manager, team, job title, employment type and status, an org chart, offboarding, and private details and contracts behind employees.view_sensitive. With time-entries, time entries carry the employee_id of their member.
- [Leave](https://bettersupabase.com/blocks/leave.md): Leave types, requests that go through approvals, and a balance ledger per member and year with accruals, adjustments and a year-end carryover. With employees, requests carry the employee_id of their member, or belong to an employee with owner "employee". Balances can live in the app's own table of signed amounts instead of the ledger.
- [Enrollments](https://bettersupabase.com/blocks/enrollments.md): Programs of steps per organization, and enrollments of a party, a member or any subject in them with step progress and completion. Onboarding checklists run on it.
- [Qualifications](https://bettersupabase.com/blocks/qualifications.md): Qualification types (certifications, licences, skills) with a validity in months and optional evidence, requirements naming who must hold them (a role, a team, a job title, an asset kind, a segment or one holder), 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](https://bettersupabase.com/blocks/shifts.md): 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.
- [Observations](https://bettersupabase.com/blocks/observations.md): Typed measurements of a 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.
- [Medications](https://bettersupabase.com/blocks/medications.md): A medication catalog per organization, orders for a record with a dose, route, schedule and an as-needed maximum, orders imported from a pharmacy, planned doses, each dose recorded as given, refused, skipped or missed with a second check for high-risk medication, and a medication chart per record.
- [Care plans](https://bettersupabase.com/blocks/care-plans.md): Care plans per client: problems with codes from your code systems, goals 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.
- [Payroll export](https://bettersupabase.com/blocks/payroll-export.md): Payroll runs that collect the hours worked, the approved leave and optionally the scheduled shifts of a period into lines per person, locked by an export through a versioned PayrollExportFormat port.
- [Clinical decision support](https://bettersupabase.com/blocks/clinical-decision-support.md): Tenant rules for dose range, duplicate therapy and interactions over a record's medication orders, alerts that members acknowledge or override with a reason, and a decision context for external engines whose alerts are stored the same way.
- [E-prescribing](https://bettersupabase.com/blocks/e-prescribing.md): 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.

## Billing & commerce

- [Stripe entitlements](https://bettersupabase.com/blocks/entitlements.md): Active Stripe entitlements per tenant from the Stripe Sync Engine, feature_claims() for the access token hook, and has_entitlement() and tenant_ids_with_entitlement() for RLS.
- [Usage metering and quotas](https://bettersupabase.com/blocks/usage.md): Usage counters per tenant, meter and day with idempotent increments, quotas per tenant or plan, within_quota() for policies and consume_quota(), which raises quota_exceeded. unreported_usage() feeds reportUsageToStripe.
- [Stripe billing](https://bettersupabase.com/blocks/billing.md): Each tenant's Stripe customer, seat counts (options.seatRoles) and the active subscription item from the Stripe Sync Engine, for createBilling(): checkout, the customer portal, seat sync and Stripe webhook handling.
- [Catalog](https://bettersupabase.com/blocks/catalog.md): Products with options, variants and prices in minor units, price lists, a category tree, collections, sales channels, translations per locale, product media and an optional public storefront.
- [Inventory](https://bettersupabase.com/blocks/inventory.md): Stock per catalog variant and location in a unit with decimals: movements posted to the ledger block, lots, serial numbers, expiry, bins, weighted average cost, reservations with expiry, allocations with backorders, transfers, purchase requisitions with approval, and purchase orders with partial receiving into goods receipts.
- [Orders](https://bettersupabase.com/blocks/orders.md): Carts on anonymous or signed-in users, checkout priced from the catalog, confirmed orders from lines or an accepted quote with stock allocations, gapless order and invoice numbers, payments, fulfillments, returns and refunds, with an optional kitchen display. With invoices, a paid order gets an issued, paid invoice.
- [Promotions](https://bettersupabase.com/blocks/promotions.md): Percentage, fixed and free-shipping promotions, automatic or by code, with usage limits and stacking rules, priced into orders carts.
- [Invoices](https://bettersupabase.com/blocks/invoices.md): Invoices an organization sends its own customers and bills from its suppliers: drafts with lines, a gapless number per direction on issue, payments, credit notes, void and write-off, overdue and aging per currency, credit limits, the three-way match of a purchase bill, party payments split over invoices with the rest kept as credit, dunning levels, and invoices from accepted quotes.
- [Reviews](https://bettersupabase.com/blocks/reviews.md): Ratings and reviews of catalog products and other subjects: one per user and subject, verified against paid orders, moderated before or after publishing through the moderation block, with a per-subject aggregate public storefronts can read.
- [Ledger](https://bettersupabase.com/blocks/ledger.md): Double-entry accounts in a currency or a custom unit, balanced transactions, balances and holds. Credits, stock, leave balances and invoice payments post through it.
- [Billable time](https://bettersupabase.com/blocks/billable-time.md): A rate card for time entries, by member, record or organization with effective dates, and draft invoices from unbilled billable time with one line per record, member or entry, in bigint minor units. Billed entries lock until the invoice is voided.
- [Leases](https://bettersupabase.com/blocks/leases.md): Leases of units (assets) to parties with rent in bigint minor units and a frequency, rent charges posted on the ledger once per period, deposits held through ledger holds, renewals and terminations. Maintenance requests are a tasks instance on the unit.
- [Expenses](https://bettersupabase.com/blocks/expenses.md): Expense reports with lines in categories and receipts as attachments, spend policies (a limit per category, a receipt threshold) checked on submit, approval through the approvals block, and the approved total and its reimbursement posted on the ledger in bigint minor units. Without reports, each expense is one row a member or an employee submits and the app decides.
- [Donations](https://bettersupabase.com/blocks/donations.md): Gifts and pledges from donors (registered subjects) to funds and campaigns, each posted gift on the ledger in bigint minor units, charges through the versioned payments provider interface, and tax receipts numbered per organization with a yearly summary.
- [Shipments](https://bettersupabase.com/blocks/shipments.md): Shipments with packages and addresses, labels bought through a versioned carrier interface, and a tracking timeline fed by polling or verified carrier webhooks, with the shipment's status taken from its latest tracking event.
- [Accounting](https://bettersupabase.com/blocks/accounting.md): Double-entry books: a chart of accounts with account roles, journals, fiscal years of periods, balanced journal entries numbered per journal and year, dimensions, exchange rates, tax codes, the trial balance, profit and loss, balance sheet and general ledger, the period and year-end close, entries booked from invoices, expenses, stock, rent and gifts, tax reports and budgets.
- [Manufacturing](https://bettersupabase.com/blocks/manufacturing.md): Versioned bills of materials with routings on work centers, production orders numbered MO-2026-0001 that allocate and consume components and receive the output at component plus work center cost through inventory, lot genealogy and recall, and material requirements that suggest purchase and production orders.
- [Banking](https://bettersupabase.com/blocks/banking.md): 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.
- [Funding](https://bettersupabase.com/blocks/funding.md): Products a funder pays for, awards of units per period to a record from a funder in contacts, care delivered against an award from time entries, bookings or by hand, usage against the award per period, and claims per funder and period with the funder's response per line, rendered and sent through app-supplied formats and channels.
- [Tax](https://bettersupabase.com/blocks/tax.md): Tax codes per organization and legal entity with a rate history, the tax of a document per code on its date (margin scheme and credit restriction included), invoice tax lines written when an invoice is issued, tax returns with box totals, and the EU sales list per customer VAT number.
- [Warehouse](https://bettersupabase.com/blocks/warehouse.md): Warehouse work over inventory: pick waves and pick lists made from stock allocations, picking tasks as work items, confirmed bins, lots and serials, and cycle count plans that hold large variances for review.
- [Requests for quotation](https://bettersupabase.com/blocks/rfqs.md): Requests for quotation to invited suppliers, their quotes per line, a side by side comparison and an award that marks the winner and can create the purchase order.
- [Tills](https://bettersupabase.com/blocks/tills.md): Till sessions with an opening float, cash in and out, end-of-day counts that book their difference in accounting, and cash deposits that reconcile to bank transactions.
- [Periods](https://bettersupabase.com/blocks/periods.md): Dated periods per kind with open, locked and closed states, a lookup by date and a close protocol where blocks contribute close blockers and an on-close step.
- [Commissions](https://bettersupabase.com/blocks/commissions.md): Commission plans (flat or marginal tiers) assigned to sellers, commissions accrued on the ledger from paid records, statements per period with a payout, and the lines payroll adds.
- [Referrals](https://bettersupabase.com/blocks/referrals.md): Referral codes per member, attribution when the referred user or organization signs up, and a reward posted once to the ledger when the referral qualifies.
- [Agent checkout](https://bettersupabase.com/blocks/agent-checkout.md): ACP and UCP checkout sessions over an orders cart with idempotency keys, and AP2 checkout mandates verified with signing keys and used once.

## Scheduling

- [Reminders](https://bettersupabase.com/blocks/reminders.md): Recurrence rules and reminders. Expansion follows RFC 5545 in TypeScript. Delivery is a job that records reminder.sent once per occurrence.
- [Calendar](https://bettersupabase.com/blocks/calendar.md): Calendars, events with RFC 5545 recurrence (RRULE, EXDATE and per-occurrence overrides) and attendees, working hours, out-of-office and focus-time blocks, and a free/busy query that counts approved leave. Series expand in TypeScript with the reminders block's expandRule and in SQL for free/busy; a share link serves an iCal feed.
- [Bookings](https://bettersupabase.com/blocks/bookings.md): Bookable resources with weekly hours and exceptions, services with durations and buffers, and bookings that a gist exclusion constraint (btree_gist) keeps from overlapping per seat. Holds expire; recurring series book every occurrence; a share link opens public booking; confirmed bookings mirror into the calendar and reminders.
- [Passes](https://bettersupabase.com/blocks/passes.md): 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, a log of every scan, class credits that pay for bookings and come back on an early cancellation, and drop-ins counted against the resource's capacity with its bookings.
- [Recurrence](https://bettersupabase.com/blocks/recurrence.md): An RFC 5545 expander in SQL: rrule_occurrences lists the instants a rule starts in a range and rrule_next gives the first after an instant, matching the TypeScript expander in better-supabase/recurrence.

## Content & files

- [Collaborative documents](https://bettersupabase.com/blocks/documents.md): Yjs documents attached to any subject: an update log, a compacted snapshot, a private realtime topic per document for updates and presence, suggestions that editors accept into the log, and named versions through the versions module.
- [Drive](https://bettersupabase.com/blocks/drive.md): Folders and files on the attachments module: access granted to users, teams or roles and inherited down the tree, enforced by storage policies too; moves and renames with a name-conflict policy; revisions through versions, a bin through trash, starred and recent items through share-links' user state, and folder share links.
- [Drive files](https://bettersupabase.com/blocks/drive-files.md): The part of the drive module that needs attachments, versions, trash and share-links: file uploads and revisions with an optional usage quota, extracted text, storage policies, the bin, starred and recent items, folder share links and the purge event. Installed with drive.
- [Forms](https://bettersupabase.com/blocks/forms.md): Forms with numbered versions (steps and show or skip logic), a JSON Schema 2020-12 per version that validates every submission, drafts, public links through share-links with a rate limit and a bot-check hook, handlers that turn a submission into a record, scoring against an answer key respondents can't read, and NPS rollups.
- [Signatures](https://bettersupabase.com/blocks/signatures.md): Simple electronic signatures on a frozen version of a record: drawn, typed or click signatures in parallel or in order, a hash that detects edits after signing, and an approval step a signer can decide.
- [Templates](https://bettersupabase.com/blocks/templates.md): Typed, versioned templates (system starters and tenant forks) that create records, with merge fields and workflows started on each record they create.
- [Courses](https://bettersupabase.com/blocks/courses.md): Courses of modules and lessons ordered by rank keys, with quiz lessons graded by forms, per-lesson progress, completion and certificates. Each course runs as an enrollment program, so learners enroll through enrollments.
- [Content](https://bettersupabase.com/blocks/content.md): Typed, localized content entries per organization, such as pages and posts, with a slug unique per type and locale. Entries are drafted, scheduled and published, optionally through approvals, and anyone can read published entries.
- [Digital asset management](https://bettersupabase.com/blocks/dam.md): Renditions of drive files (thumbnails and web sizes made through the drive's preview renderers) and usage rights with a territory, a channel and an expiry date, with a reminder before a right ends.

## AI

- [Vector search](https://bettersupabase.com/blocks/vector-search.md): search_<table>(query, k) for each table in vectorSearch: the k nearest rows the caller can read, with pgvector iterative index scans so RLS filters still return k rows.
- [AI chat](https://bettersupabase.com/blocks/ai-chat.md): Chats, projects, participants and a message tree (or one linear list) in the canonical AI message format or the SDK's own parts, with runs (and the id of a durable engine's run), run steps for progress, a compare-and-set stream claim, harness sessions, tool approvals and policies, pending inputs, cited sources, feedback, hashed share links, a model catalog per plan, moderation events and private Realtime topics per chat and per user.
- [AI files](https://bettersupabase.com/blocks/ai-files.md): Files and documents for AI chats: a private bucket whose policies only accept an upload a reserved record expects, provider file references with expiry, versioned documents with suggested edits, and a purge that hands back the objects to remove.
- [Knowledge](https://bettersupabase.com/blocks/knowledge.md): Documents and chunks for retrieval with an embedding and a tsvector each, scoped to an organization, agent, project, chat, user or record (subject) and grouped into collections with a visibility, a priority and grants, plus system documents shared with every tenant; hybrid search with reciprocal rank fusion, chunks that keep their embedding when unchanged, and an embed job per document when jobs is installed. With ai-files and jobs, queue_knowledge_file ingests a file through a job.
- [Memory](https://bettersupabase.com/blocks/memory.md): Memory for AI assistants: core memory as files under /memories edited with view, create, str_replace, insert, delete and rename with version checks; archival facts with hybrid similarity search; message embeddings to recall earlier chats, skipped for temporary chats; and versioned documents under an opaque scope key for agent runtimes such as eve.
- [Agents](https://bettersupabase.com/blocks/agents.md): Custom assistants with instructions, a model, tools, connectors, knowledge scopes and starters; private until published to the organization or the public store, with installs, ratings and provider skills.
- [AI scheduled tasks](https://bettersupabase.com/blocks/ai-schedules.md): Prompts a user schedules on a cron, with a run per occurrence; the scheduler claims due tasks, queues an ai_task_run job when jobs is installed, and fails runs that stall.
- [AI response cache](https://bettersupabase.com/blocks/ai-cache.md): Model responses cached by a key the application derives from the request, with a TTL capped by maxTtl, hit counts and a purge of expired entries; only the service role reads and writes it.
- [AI providers](https://bettersupabase.com/blocks/ai-keys.md): A tenant's own provider keys as credential_ref rows, and a registry of provider batch jobs with their results and a poll claim. Sandboxes live in ai-chat.
- [Prompts](https://bettersupabase.com/blocks/prompts.md): Versioned prompt templates by name, per tenant or for the whole system, with labels such as production that point at one version; only the service role reads and writes them.
- [AI evals](https://bettersupabase.com/blocks/ai-evals.md): Evaluation datasets of inputs and expected outputs (imported or taken from rated ai-chat replies), runs against a prompt version and model, a score per scorer and item, and a regression compare between two runs; only the service role reads and writes them.
- [AI guardrails](https://bettersupabase.com/blocks/ai-guardrails.md): Input and output policies per agent (prompt-injection heuristics, PII redaction, topic deny lists, a tool depth limit) and a decision log; a blocked check records guardrail.blocked. Only the service role reads and writes them.

## Automation

- [Job queue](https://bettersupabase.com/blocks/queue.md): Typed jobs on Supabase Queues (pgmq) or a plain table (blocks.queue.options.backend): leases, retries with backoff, dead letters, deduplication keys, queue stats, and schedules with pg_cron or the drain route.
- [Idempotency keys](https://bettersupabase.com/blocks/idempotency.md): Stores responses by Idempotency-Key so retried requests replay the first result instead of running twice.
- [Webhook inbox](https://bettersupabase.com/blocks/webhook-inbox.md): Stores verified webhooks once per message id, per tenant when given, then processes them with leases, retries and checkpoints, in its own table or one of the app's.
- [Write rate limits](https://bettersupabase.com/blocks/rate-limit.md): Fixed-window limits on Data API writes (POST, PATCH, PUT, DELETE) per user or claim, checked by pgrst.db_pre_request. Over the limit: 429 with Retry-After.
- [Outbox](https://bettersupabase.com/blocks/outbox.md): Events written in the same transaction as the change, read by named consumers with their own cursor and lease, kept for history and relayed as CloudEvents.
- [Durable streams](https://bettersupabase.com/blocks/streams.md): Ordered text chunks a writer appends and any reader resumes from an index: idempotent batches, a cancel flag the writer reads on its next append, owner reads through RLS, a payload-free Realtime ping on a private topic per stream, and a purge for expired streams.
- [Workflows](https://bettersupabase.com/blocks/workflows.md): Engine-neutral workflow runs that members read through RLS, with a Realtime ping per status change and workflow_run.completed, .failed and .cancelled outbox events; cron schedules with idempotent fires, counting semaphores, admission control for starts (concurrency, debounce, singleton) and a retention purge.
- [Workflow SDK World](https://bettersupabase.com/blocks/workflow-sdk.md): The tables of the Workflow SDK World (@workflow/world-postgres 5.4.1) in the workflow schema, closed to the API roles; a trigger that copies each run into workflow_runs, a pg_net dispatcher for the delivery queue on a pg_cron schedule, start idempotency keys, a list of the hooks open runs wait on, a purge of ended runs and the purge backstops of zero-retention runs.
- [Workflow builder](https://bettersupabase.com/blocks/workflow-editor.md): Workflow definitions a tenant edits as an engine-neutral node graph, with draft, published and archived versions, triggers (webhook tokens stored hashed), credential references a CredentialProvider resolves, a synced step library, per-node run status pinged on the run's topic, and failed and slow alerts written as workflow_alert.triggered outbox events.
- [Connectors](https://bettersupabase.com/blocks/connectors.md): MCP servers per tenant with no, per-user OAuth or header auth; per-user grants that hold only a credential_ref; MCP sessions per chat; and tool list fingerprints that hold a changed list until an admin approves it.
- [Rules](https://bettersupabase.com/blocks/automations.md): Tenant-editable automations: a filter tree over a subject type's field catalog, tested when a trigger event happens, with action references the action registry runs. Blocks ship default automations (rule_defaults) that every organization gets a copy of, may turn off or edit, and can reset. rule_matches() evaluates a tree in SQL the same way evaluateFilterQuery does in TypeScript.
- [Housekeeping](https://bettersupabase.com/blocks/housekeeping.md): One dispatcher for the recurring cleanups the installed blocks contribute (purges, expiries): maintenance() runs each due job and records its outcome, and maintenance_schedule() registers it with pg_cron.

## Developer platform

- [Outgoing webhooks](https://bettersupabase.com/blocks/webhooks.md): Outgoing webhooks: endpoints subscribed to event types, a delivery log unique per endpoint and event with leases and retries, direct dispatch, secrets in Vault with overlap while rotating, auto-disable after an endpoint keeps failing and redelivery.
- [Incoming webhook endpoints](https://bettersupabase.com/blocks/incoming-webhooks.md): Per-tenant trigger URLs with a hashed token, optional Standard Webhooks or HMAC verification, a body size limit, receive counters and the last status; deliveries go to the webhook inbox with the endpoint's tenant.
- [API keys](https://bettersupabase.com/blocks/api-keys.md): Hashed API keys for tenants and users with scopes, expiry, rotation with a grace period, a per-key rate limit and throttled last-used tracking. verify_api_key() backs apiKeyResolver; has_scope() and api_key_tenant() go in policies.
- [Credentials in Vault](https://bettersupabase.com/blocks/credentials.md): Third-party tokens and API keys in Supabase Vault as bs:cred:<provider>:<name>, behind security definer credential_get, credential_set and credential_delete functions only the service role may call. vaultCredentials() in better-supabase/credentials resolves credential references through them.
- [Service principals](https://bettersupabase.com/blocks/service-accounts.md): Non-human tenant members backed by auth.users rows that can't sign in, with roles through memberships. Organization-owned workflow versions and service webhook endpoints run as the tenant's default principal.
- [Signing keys](https://bettersupabase.com/blocks/signing-keys.md): Ed25519 or ES256 signing keys per owner: the private JWK in Supabase Vault, one active key per owner, rotation that keeps a retired kid in the JWKS until the latest exp a signer noted, and a purge. Only the service role calls it; createSigningKeys() in better-supabase/blocks/signing-keys generates keys and signs with WebCrypto.
- [Shared signals](https://bettersupabase.com/blocks/security-events.md): OpenID Shared Signals streams: stream configuration and status per receiver, push delivery through a webhooks endpoint with format 'set' (RFC 8935), a poll queue (RFC 8936), SETs held while a stream is paused, and a receiver replay table. Only the service role calls it; createSsfTransmitter() and createSsfReceiver() in better-supabase/blocks/security-events mint and verify the SETs.
- [OAuth server](https://bettersupabase.com/blocks/oauth-server.md): Storage for an OAuth 2.1 authorization server: registered clients (RFC 7591) with hashed secrets, a grant per user and client, single-use authorization codes bound to a PKCE S256 challenge, device codes (RFC 8628) and a revocation list of access token jtis. It issues no tokens. createOauthServer() in better-supabase/blocks/oauth-server hashes secrets and checks PKCE, and its isRevoked plugs into accessTokenResolver.
- [Vercel Marketplace](https://bettersupabase.com/blocks/vercel-marketplace.md): Vercel Marketplace provider state: installations per configuration id, provisioned resources with their tenant and secret handles, access tokens sealed in Vault, plans, invoices kept by event time and meter reports sent to Vercel per period. Only the service role calls it; createVercelMarketplace() in better-supabase/blocks/vercel-marketplace serves the Partner API, verifies webhooks, exchanges SSO codes and reports usage.

## Admin & compliance

- [Audit log](https://bettersupabase.com/blocks/audit.md): Records inserts, updates and deletes with the actor and changed columns for tables you register, plus semantic events through audit_event(), with redaction, an append-only guard, a tenant read policy and per-tenant retention as options.
- [Support sessions](https://bettersupabase.com/blocks/impersonation.md): Lets platform staff view the app as a user: time-limited, read-only by default, gated by is_platform() and a second admin's approval, recorded in the audit log, with the target's claims built by your access token hook.
- [Data lifecycle](https://bettersupabase.com/blocks/data-lifecycle.md): Data exports per user or organization from every installed module's tables and the app's, written to a private bucket by the app's export job, and organization deletion with a grace period that disables the tenant before a purge job deletes its rows.
- [Metrics](https://bettersupabase.com/blocks/metrics.md): Metrics declared with defineMetric over a table (count, sum or avg per time bucket and dimension), rolled up into metric_points or read from the table, with metric_series and metric_value checked against a permission in the tenant.
- [Compliance controls](https://bettersupabase.com/blocks/compliance.md): Compliance frameworks and their controls, evidence linked to controls (attachments or notes, with a validity date), recurring evidence tasks with assignees and an overdue state, a status rollup per framework, and policies published as frozen versions that members acknowledge through the acknowledgements block.
- [Consents](https://bettersupabase.com/blocks/consents.md): Consent per record and purpose: the purposes an organization asks consent for with their lawful basis and version, each decision with who made it (the person or a representative) and its signature, form or file as evidence, withdrawals and expiry. consent_active() answers whether processing may go ahead.

## Database primitives

- [Update timestamps](https://bettersupabase.com/blocks/updated-at.md): Keeps an updated_at column current on every update.
- [Realtime table changes](https://bettersupabase.com/blocks/realtime-tables.md): Broadcasts a change signal (no row data) once per statement on bsb:t:<schema>.<table>[:<tenant>], or bsb:t:<schema>.<table>:u:<user> for realtime.users tables, for live queries.
- [JSON Schema checks for jsonb](https://bettersupabase.com/blocks/jsonb-schemas.md): pg_jsonschema check constraints for jsonb columns with a `schema` in the `json` config, so the database enforces the same shape as the types. A trigger reports what failed through jsonschema_validation_errors, which the client maps to a validation error.
- [pgTAP helpers](https://bettersupabase.com/blocks/pgtap.md): tests.create_user, tests.authenticate_as and catalog checks (every_table_has_rls, policies_use, no_anon_policies, every_table_audited, partitions_have_rls) for `supabase test db`. Written to supabase/tests, never to your schema.
- [Read sets](https://bettersupabase.com/blocks/read-sets.md): One `stable` function per `defineReadSet` in `readSets`, so `db.$many(readSet, params)` is a single GET.
- [Number sequences](https://bettersupabase.com/blocks/numbering.md): Gapless numbers per tenant, entity and period. next_number locks the row in the caller's transaction, and a trigger fills the document column so a separate round trip cannot open a gap.
- [Imports](https://bettersupabase.com/blocks/imports.md): Import runs and the external record map. import_upsert_batch writes items through the targets blocks and the app register, skips equal content, reports rows a user changed since the last import and marks missing keys on full runs. The dry run, parsing and mapping live in TypeScript.
- [Rank](https://bettersupabase.com/blocks/rank.md): Fractional rank keys: rank_between, move() for every config.recordTypes entry with a rank column (through the caller's policies and any state-machine trigger), and a rebalance job.
- [Versions](https://bettersupabase.com/blocks/versions.md): Numbered snapshots of a subject's content: manual, debounced auto and frozen snapshots, restore through columns or an apply function, and retention.
- [Trash](https://bettersupabase.com/blocks/trash.md): Soft delete through each subject's deletedAt column: trash with children in one batch, restore with unique checks, a list per organization, and purge after a retention period, skipped for subjects under a legal hold.
- [Field history](https://bettersupabase.com/blocks/field-history.md): The old and new value of chosen columns of any registered record on every update, who changed it and when, read per record and field.
- [Field encryption](https://bettersupabase.com/blocks/field-encryption.md): Encrypts app table columns and custom field values at rest with a data key per tenant, user or app, kept in Supabase Vault as bs:field-key:<owner>. Only security definer read paths that check the caller's scope decrypt; a lookup column keeps an HMAC of the value under the owner's lookup key for equality searches; drop_field_key deletes both keys so the values can no longer be read or found. Members read which of their owners have keys, with the key dates and what they encrypt, through field_key_status(), and rotate_field_key replaces a data key and encrypts its values again.
- [RLS on every new table](https://bettersupabase.com/blocks/rls-guard.md): An event trigger that enables row level security on every table created outside the Supabase-managed schemas, so a new table is never readable through the Data API before it has policies. Install it as postgres: supautils lets that role create event triggers.
