# Backend architecture (Supabase strategy) Status: Step 0 deliverable, 2026-10-08. Conceptual only. No migration, table, policy or function is created by this document. Table and function names follow `faunosteo-business-architecture.md` §4–§20. ## 1. Components and what runs where ```text Browser (apps/app, anon key + user JWT) │ tables via RLS, RPC (security definer), Storage signed URLs ▼ Supabase (self-hosted on Scaleway at launch, §31) ├─ Auth (GoTrue): email/password, Google, Apple, OTP, phone ├─ PostgreSQL: schemas public / private / audit, RLS, functions, pg_cron ├─ Storage: private buckets, storage.objects policies ├─ Edge Functions (Deno): public endpoints, webhooks, signed-URL issuance └─ Realtime (optional): report sync state Worker (apps/worker, service key, same host) └─ jobs table in PostgreSQL, no Redis public-web (anon key, SSR) └─ public views / RPCs only ``` The browser never holds a service-role key, admin credential, storage master key or third-party refresh token (§17.1). ## 2. Auth | Need | Mechanism | Note | |---|---|---| | Email/password, magic link/OTP | GoTrue built-in | strong password policy configured server-side | | Google, Apple | GoTrue OAuth providers | Apple requires a paid developer account and a services id: dependency to confirm | | Phone verification | GoTrue phone OTP needs an SMS provider (Twilio, MessageBird, Vonage) | cost and EU processing to confirm; see `OPEN_QUESTIONS.md` Q7 | | Email verification | GoTrue, mandatory before professional features | | | MFA | GoTrue TOTP; mandatory for owner/admin/moderator/support roles, enforced by RLS helper `has_mfa()` on admin tables | | | Roles | `profile_roles` table, never JWT custom claims as the only source (claims can lag) | helpers read the table | | Impersonation | dedicated RPC issuing a short-lived scoped session, audited, banner in UI (§17.5) | after MVP core | `profiles.id = auth.users.id`, created by a trigger on `auth.users` insert. ## 3. PostgreSQL layout | Schema | Content | Exposure | |---|---|---| | `public` | tables exposed to PostgREST, all with RLS enabled, separate SELECT/INSERT/UPDATE/DELETE policies | browser, public-web, worker | | `private` | security-definer helper functions, internal tables (counters, job queue, route cache), triggers | not exposed to PostgREST | | `audit` | `audit_logs`, append-only, insert via `private.log_event()` | read by admins through a view | Conventions fixed now so every step follows them: - UUID primary keys (`gen_random_uuid()`), `created_at` / `updated_at` with a shared trigger, soft delete `deleted_at` where the architecture names it. - Enums as PostgreSQL `enum` types when the value set is closed by the business (report status, appointment status), `text` + CHECK when the set is expected to grow (document types). - JSONB documents (`reports.current_document`, `anatomical_sheet_versions.content_jsonb`) carry their own `schema_version` and are validated by the matching Zod schema at the application boundary and by a CHECK on `schema_version` in SQL. SQL does not re-implement Zod. - Every table exposed to the browser: RLS enabled, no `USING (true)` policy for `authenticated`, no anonymous policy on core tables (§17.4). ## 4. RLS strategy ### 4.1 Helpers Security-definer functions in `private`, `STABLE`, `search_path` pinned, `SET row_security = off` inside where they read tables that have policies referencing them (prevents recursion), one index per access path they use: ```text private.is_platform_owner(uid) private.is_platform_admin(uid) private.is_platform_moderator(uid) private.is_support(uid) private.is_org_member(uid, org) private.is_org_manager(uid, org) private.is_org_practitioner(uid, org) private.can_view_client(uid, client) private.can_view_animal(uid, animal) private.can_view_report(uid, report) private.can_edit_report(uid, report) private.can_use_sheet(uid, sheet) private.can_fork_sheet(uid, sheet) private.has_active_entitlement(uid, capability text) ``` Each helper ships with pgTAP tests in the same migration step: positive case, negative case, expired grant, revoked grant, wrong organization. ### 4.2 Policy rules per domain (summary of §17.3) | Table family | SELECT | INSERT/UPDATE/DELETE | |---|---|---| | `profiles` | own row; admins via view | own row; roles only through RPC | | `organizations`, `organization_members` | members | managers/owners through RPC (`add_member`, `remove_member`, `set_role`) so that "secretary cannot self-grant practitioner" is one place | | `clients`, `client_contacts`, `client_consents` | `can_view_client` | create by the practitioner who starts the relationship; core identity edits restricted (open question Q6) | | `animals` | `can_view_animal` | practitioner with an active relationship or grant | | `reports` | `can_view_report` | `can_edit_report` for drafts; completion and numbering only via RPC | | `report_revisions` | same as parent report | insert via RPC/trigger only | | `anatomical_sheets` | public metadata through a view; full row for creator, grantee, or follower of a public sheet | creator only; publish via RPC | | `anatomical_sheet_versions` | `can_use_sheet` on the parent | insert draft by creator; published rows immutable (trigger raises on UPDATE of `content_jsonb` when `status = published`) | | `practitioner_follows`, `sheet_usage_grants` | involved parties | own follows; grants by sheet creator or org manager | | `appointments` and agenda tables | owner scope; public availability through RPC only | booking through RPC with row locks | | `plans`, `subscriptions`, `entitlement_grants` | own / org manager | Stripe webhook (service) and admin RPC only | | `audit.audit_logs` | admins | append-only via `private.log_event` | | `storage.objects` | per bucket policy calling the owning domain's helper | upload paths validated against `assets` rows | ### 4.3 Public endpoints Public profile, sheet discovery, availability and booking are security-definer RPCs or narrow views returning approved columns (§17.4). The anon role gets EXECUTE on those functions and nothing else. ## 5. Storage Buckets, all private: `avatars`, `logos`, `professional-documents`, `client-files`, `animal-files`, `report-files`, `anatomical-sheets`, `imports`. Object key: `///`. The `assets` table is authoritative; `storage.objects` policies call the owning helper (`can_view_report` for `report-files/...`). Reads go through signed URLs issued by an RPC/Edge Function after the same check. SVG pipeline (§15.3): upload lands in a quarantine prefix with `assets.sanitization_status = pending`; a server sanitizer (Edge Function or worker) rewrites the file (strip `