Architecture
Open CRM is a React single-page app (Vite, TypeScript, Tailwind, shadcn/ui, TanStack Query) on one Supabase project: Postgres with row-level security, Auth, Storage, and edge functions on Deno. The browser talks to Postgres directly (through PostgREST, as the signed-in user) for everything row-level security can decide, and to an edge function for everything it cannot: work with secrets, email and text messages, encryption, public links, and steps that must happen together.
browser ──(anon key + user token)──> PostgREST ──> Postgres (RLS on every table)
│ ▲
└──(user token / link token)──> edge functions ─────┘ (service role)
│
pg_cron tick ──(x-cron-secret)──> job-runner ──> other functions / SQL
│
outbound adapter ──> Resend, Twilio, or dev_outbox
The feature registry
Each domain is a folder, src/features/<domain>/, with a manifest.tsx that exports a
FeatureManifest (src/features/types.ts). A manifest declares what the domain contributes:
- owner rail items and routes inside the shell, and standalone owner routes (the connector’s consent page);
- workspace routes, workspace tabs, bottom-bar counts and New-menu entries (see below);
- portal tabs, routes, home cards and profile sections, and the portal frame;
- public routes (no session:
/sign,/invite,/start,/unsubscribe,/esign/verify, the password pages); - contact record tabs (with a waiting-count badge), header actions, right-bar panels and activity cards;
- settings sections.
src/features/registry.ts lists the manifests and sorts each slot by order. The owner app,
the shell, the portal and the public router read only the registry, so a domain adds a screen
by editing its own manifest, never a shared file.
Manifests load with the entry bundle that every public page downloads, so a manifest imports
only React, the router, icons and three small helpers; everything it points at is lazy
(lazyNamed). Public pages live under src/features/<domain>/public/, the build names their
chunks public-*, and bundleBoundary.test.ts proves none of them loads supabase-js.
registry.test.ts checks the other rules (relative routes, unique keys and paths, every nav
item opens a screen).
The owner shell and the workspace
The owner app is a shell of four zones (src/components/layout/AppShell.tsx): a permanent icon
rail on the left (New, search, the rail items with each count drawn once on its icon’s corner,
light and dark, the account), the content, and a bottom bar pinned to the window’s foot. Below
md the rail is a labelled drawer opened from a top bar, and the bottom bar is not drawn.
- The workspace is a layout route around the contacts, the board, documents, requests,
messages, e-sign and marketing (each domain’s
workspaceRoutes). It mounts the client panel (every contact, an All / Clients switch remembered per browser, one A to Z list by last name with each row’s status as its tint, a search that reaches everyone, selection and bulk actions over the rows on screen) and one tab strip across the top (workspaceTabs, with the waiting counts their badges draw). The strip is the top row and never scrolls; on a phone each tab is its icon. A page’sPageHeaderlands in the row under the tabs: on a workspace screen the workspace holds THE top-bar slot and the shell draws none (one id, one element).registry.tsmatches the shell’s and the workspace’s routes as one tree (ownerRouteTree), so a literal path such ascontacts/newbeats the workspace’scontacts/:id, and the router and the shell can never disagree. - A workspace route’s
handlemay carrypanelFirst(belowlg, where one pane fits, the panel is that pane: the contacts screen outside Tiers) andpickParam(a pick sets that query parameter in place instead of opening the record: documents’?contact=; belowlgthe panel is the screen until the parameter holds a valid id). - The bottom bar draws
shellCounts: what is waiting (unread, to review, to accept) and the size of the book (clients, open leads), each a link. A count is a lazy render-prop component. A waiting count shares the query key of the feature’s badge, so the two share one fetch; the book’s figures are head-only counts under the contacts key, so any contact write refreshes them and no page loads the contact list for them. - The New menu draws
newMenu: an entry goes to its feature’s create screen (path) or opens its feature’s dialog where the owner is (Dialog), and closing the dialog hands focus back to New. - Ctrl K (or Cmd K) reaches the search: the client panel’s box where it is on screen, else a box that floats beside the rail and clears when dismissed.
Inside a domain: one api module with its own query keys, Zod at the boundaries, paged reads with
a stable tiebreaker, and mutations with error toasts and rollback of optimistic updates. Shared
CRM pieces (contact stages, revenue math, the contact picker, the pick-list hook) are in
src/lib, src/api and src/hooks.
Principals
Defined once, in 0001_core and 0002_contacts:
- owner:
is_owner(), the user recorded inorg_profile.owner_user_id, at aal2 once a two-factor factor is verified, on a token issued after any two-factor recovery. - client:
get_client_contact_id(), the contact an active portal account belongs to. - server: the service role, used by edge functions. It bypasses row-level security but not triggers.
- system actor: an Auth user that never signs in, recorded as the actor on audit rows written with no user (scheduled jobs, webhooks).
A role claim in a token grants nothing. View as client is a client session that a statement trigger on every client-writable table, the storage policies and the edge handler all keep read-only.
The shared edge layer
Every function is supabase/functions/<name>/ with handler.ts (pure, every dependency
injected, tested in vitest) and index.ts (wires Deno and Supabase). Common code is in
supabase/functions/_shared/:
handler.ts,createHandler: the one request pipeline. In order: CORS preflight, the method allowlist, refusal of a browser origin not on the list, authentication, refusal of a View as client session for client writes, the rate limit, a body read with a size cap, then the function. Errors leave as their own status with a generic message; anything unexpected is a generic 500.- Auth modes, combinable per function:
owner(bearer token, owner at the right assurance level),client(bearer token, a portal account; the function must declareclientWrites),cron(x-cron-secretagainstCRON_SHARED_SECRET),internal(a named header against a named secret, one function calling another),apiKey(a server-to-server key the function verifies; must declare a rate limit) andpublic(no Supabase principal: the function proves the caller itself with a signed link, a webhook signature or an OAuth token; must declare a rate limit). config.ts(URLs, keys, allowed origins),secrets.ts(constant-time secret checks),rate-limit.ts(the per-address, per-user and global buckets in0001_core),audit.ts,crypto.ts,magic-bytes.ts(every stored upload’s bytes are checked against its type),log.ts(redacting logger),organization.ts(the org’s names and branding for emails),email-layout.ts,paging.tsandoutbound.ts.
The outbound adapter
Every email and text message leaves through _shared/outbound.ts, which picks an adapter per
send from the environment:
- resend when
RESEND_API_KEYis set (withEMAIL_FROM); - twilio when all three Twilio values are set;
- local when no provider is set and
ENVIRONMENTis notproduction: the message is written to thedev_outboxtable with its sender, headers and idempotency key, and the owner reads it on System, Outbox. Every flow works on a fresh project with no provider account.
In production a missing provider throws: a message is never dropped silently and never parked in
the outbox of a live install. A send answers sent, failed (the provider refused; safe to
retry) or unknown (no answer; it may have been accepted, so it is never retried with a new
idempotency key).
Background work: jobs and the job runner
No migration schedules anything. Background work is a row in public.jobs, and one scheduled
tick runs the queue:
npm run schedules:installstores the project URL andCRON_SHARED_SECRETin Vault and appliessupabase/schedules.sql: an every-minute tick that posts tojob-runner(reading the URL and secret from Vault when it runs), daily jobs that enqueue one row of each kind only when none is already waiting, an hourly View as client sweep, and a cron history trim.job-runnerclaims due jobs with a lease and routes each by its kind (supabase/functions/job-runner/kinds.ts):esign:expire_envelopes,needs:reminder_dispatchandportal:daily_digestpost to their functions with the cron secret;ops:maintenancecalls the server-only retention functions in SQL.- Execution is at least once, so every callee is safe to run twice and treats “nothing to do” as success. Results (counts and ids only) are kept 30 days and shown on System, Jobs, where the owner can retry a failed job.
Migrations
supabase/migrations/, applied in filename order by npx supabase db push and by the PGlite
test harness:
| File | Holds |
|---|---|
0001_core |
The principals and org_profile, two-factor session checks and backup codes, the rate-limit buckets, the append-only audit log, app settings, the jobs queue, the dev outbox, CSP violation reports, and the shared trigger helpers. |
0002_contacts |
Contacts and their pick-lists (stages, lead sources, organization types, services), businesses, emails, notes, relationships, quotes and upsells; portal accounts, invitations, client activity and tasks; View as client sessions and the read-only rules; the safe contact delete. |
0003_documents |
Documents and folders, encryption metadata, annotations, the private documents bucket and its policies. |
0004_messages |
Client messages and the organization’s message key. |
0005_requests |
Requests, their items, answers and uploaded documents, request categories and tags, templates, and start links. |
0006_esign |
Envelopes, their documents, pages, signers, fields and events, templates, text message codes, drawn signatures, and the e-sign working bucket. |
0007_mcp |
The AI connector’s OAuth tables (every secret stored hashed) and the audited functions behind its tools. |
0008_board |
Work items, their history, board stages and work item types. |
0009_marketing |
Monthly targets and ad spend. |
0010_email |
Group email campaigns, recipients, suppressions and unsubscribe tokens. |
0011_control_center |
The lead-intake key and deliveries, and the public logo bucket. |
0012_portal |
The server side of invitations, sign-in records, and the View as client credential lock. |
0013_crm |
Client tiers and reversible archiving (stamped by the database), and the group email claim that skips archived contacts. |
0014_requests |
Requests that close themselves once nothing is left to do, the once-a-day upload notice, and the guarded write a client’s contact confirmation goes through. |
0015_mcp |
The AI connector’s pipeline, work board and request follow-up tools, and a consent version, bound to each approval, that makes older connector approvals re-consent. |
0016_small |
Deactivating a portal account expires the contact’s pending start links in the same transaction. |
0017_crm_full_access |
Notes that can be corrected and deleted (never relabelled), the database half of changing a portal sign-in email, and the AI connector’s whole-record, quote-accept, note, sign-in email, answer and document tools, with the consent version moved to 3. |
Every migration states the schema’s rules in its header, and
src/__tests__/db/invariants.test.ts checks the migrated catalog against them (row-level
security and an MFA gate on every table, explicit grants, search_path pinned on every
function, per-bucket storage policies, the View as client trigger on client-writable tables).
CONTRIBUTING.md lists them.
Tests
src/__tests__/db/: the migrations in PGlite, with every principal against every table.src/__tests__/edge/: each function’s handler, through the shared contract and its own behaviour tests.src/features/<domain>/__tests__/: the screens and api modules.src/__tests__/: the registry, the bundle boundary, the bootstrap, the firm-strings scan.src/__tests__/seed/: the demo seed (supabase/seed/demo.sql).