Merge feature/step-03-supabase-foundation into develop
ci / check (push) Canceled after 0s
ci / docker (push) Canceled after 0s
ci / supabase (push) Canceled after 0s

This commit is contained in:
bchanot committed 2026-10-08 23:15:14 +02:00
commit 7ea0b1f905
46 files changed
+2740 -34

No files matched your search

+9
View File
@@ -49,3 +49,12 @@ Iterations:
3. `corepack prepare pnpm@10.13.1` → works. Last major before the node:sqlite cache backend; reads lockfile v9 unchanged; already cached on dev host.
Fix: Dockerfile:7 pinned to `pnpm@10.13.1`.
Status: resolved (commit 990c8e7).
---
## BLK-006 | 2026-10-08 | Docker socket permission denied → no local Supabase stack for Claude
Friction: `supabase start` → "permission denied … /var/run/docker.sock"; daemon up (`docker info` client OK), user not in `docker` group. No psql/postgres on host either.
Root: host group membership; needs `sudo usermod -aG docker $USER` + re-login (user runs, not Claude).
Workaround: PGlite harness (BDR-028) executes migrations + 81 pgTAP checks; CLI config parses (`supabase start` fails only at Docker inspect).
Status: resolved 2026-10-08 (same day) — user added docker group; `supabase start` pulled postgres 17.11.0.004, applied 3 migrations + seed; `supabase test db` 81/81 after scoping counts to fixture ids (seed rows broke 6 absolute counts, PGlite had no seed); `gen types` adopted (CLI output unformatted → piped through prettier); REST script §8 matched expectations; `db reset` from zero OK.
+31
View File
@@ -224,3 +224,34 @@ Status: closed.
gitflow lib purges `docs/superpowers/{specs,plans}` at every `finish` (BDR-065, fixed path list). Step 1 finish deleted 9 design docs (8f217d8). Restored from history under `docs/history/superpowers/` (not purged); refs updated (CLAUDE.md, migration map, plan). Audit docs keep old path (frozen).
Alt rejected: revert in place → purged again next finish; editing the lib list → global change for one repo.
Status: closed.
---
## BDR-026 | 2026-10-08 | platform_role enum = owner/admin/moderator/support only; professional statuses excluded
Business arch §4.1 lumps 7 values in `profile_roles.role` (practitioner/student/professor + 4 platform). User rule: never confuse platform roles with professional statuses. Table name kept `profile_roles` (plan + helper names unchanged), enum `platform_role` 4 values. practitioner/student/professor → verification outcome (identity step); cabinet roles → organization_members. Hierarchy for checks: owner ⊇ admin ⊇ moderator; support separate (§17.3). Deactivated profile (`active=false`) → all helpers false.
Alt rejected: 7-value enum per arch doc → self-declared "practitioner" row readable as verified status.
Status: closed (user instruction), name `profile_roles` open to rename if user prefers `platform_roles`.
---
## BDR-027 | 2026-10-08 | Role writes RPC-only + audited; column-level GRANT protects profiles.active / phone_verified_at
No INSERT/UPDATE/DELETE policy on `profile_roles`; only `grant_platform_role` / `revoke_platform_role` (security definer, actor = auth.uid(), self-target refused, owner any role / admin moderator+support) → `private.assign/withdraw_platform_role` → `private.log_event`. Bootstrap first owner: `assign_platform_role(null, uid, 'owner')` from privileged SQL. Last active owner cannot be revoked. `profiles`: `grant update (display_name, first_name, last_name, phone, locale, timezone)` instead of a protect-columns trigger → `active`, `phone_verified_at` raise 42501 for API role, server functions untouched.
Alt rejected: BEFORE UPDATE trigger checking auth.uid() → blocks future server RPC acting for the caller; column grants declarative, visible in `has_column_privilege`.
Status: closed.
---
## BDR-028 | 2026-10-08 | pgTAP single source of SQL tests; PGlite runner in vitest beside `supabase test db`
Docker socket denied to user on dev host (BLK-006). PGlite 0.3.16 (PG17 WASM) ships pgtap extension → `packages/supabase/tests/db/` applies `supabase-shim.sql` (API roles, auth.users, auth.uid(), Supabase default privileges) + migrations, runs every `supabase/tests/*.sql`, fails on `not ok` / plan mismatch. Same files run by `supabase test db` on real stack (CI supabase job). Shim replicates permissive default privileges so a missing `revoke` fails.
Alt rejected: TS-only RLS tests (duplicate harness, drift); waiting for Docker (no executed proof).
Status: closed.
---
## BDR-029 | 2026-10-08 | database.types.ts hand-written in `supabase gen types` format + schema↔types test
CLI gen needs running stack. File written in generator format (Row/Insert/Update/Relationships/Functions/Enums/Constants). `schema-types.test.ts`: compile-time exhaustiveness (every Row column listed, every Args key listed) + runtime diff vs information_schema / pg_enum / pg_proc in PGlite; also pins RLS-on + no `using(true)` for every future public table. CI `db:types:check` diffs against real generator once Docker available; first real run may reformat (PostgrestVersion string) → regenerate + commit.
Status: closed; column scalar types (uuid→string…) reviewed by hand, not executed.
+14
View File
@@ -42,3 +42,17 @@ Method: 7 files on real assets (SVG, catalog, fixtures), oracle = audit tables (
Result: 271/271 green, 0 src change. Audit figures all confirmed (26 mappings score 0, 792/612/41, 48 attrs…).
Anomalies: 4 assertions wrong on first run, all test-side (census regex, stale closure, ZONES drawn as bullet rows not ' · ' line, attachment names in object streams). None app-side.
Action: LRN-033. Known quirks pinned as "KNOWN:" tests (orphan findings, no_attachment cause lost, sphenoid id, fuzzy FR pairs).
## EVAL-006 | 2026-10-08 | Step 3 Supabase foundation — PGlite suite
Method: 4 pgTAP files (81 checks: schema/privileges 24, profiles RLS 17, platform roles 28, audit 12) + schema↔types (6) + client (2) on PGlite; root typecheck/lint/build; app suite.
Result: all green first run except plan count (27→28) and pgtap-in-public polluting function census; 278 app + 13 package tests. Zero app behaviour change.
Anomalies: `set_config` rows appear in TAP line capture (noise, filtered by regex). `now()` constant in tx broke naive updated_at>created_at assertion.
Action: LRN-035/036. Not executed: real Supabase image (`supabase test db`), `gen types` diff, seed.sql (needs auth.identities + extensions.crypt), REST manual script. Flagged in report + BLK-006.
## EVAL-007 | 2026-10-08 | Step 3 on the real Supabase stack
Method: `supabase start` (postgres 17.11.0.004), `supabase test db`, `gen types --local` diff, REST curl script (SUPABASE.md §8) with seed users, psql on audit, `db reset`.
Result: migrations + seed apply from zero; pgTAP 81/81 after fix; REST: alice 1 row, anon 42501, self-deactivate 42501 (column grant), self-grant 42501 (RPC message), cross-row PATCH 0 rows, owner grant → uuid, alice sees her role, owner reads 3 profiles; audit shows system bootstrap + owner grant.
Anomalies: (1) 6 pgTAP counts assumed empty DB — seed rows on real stack (PGlite runs no seed) → scoped to fixture ids + neutralise foreign owners before last-owner test. (2) CLI gen output unformatted + `ComputedFields: never`, no `__InternalSupabase` → hand-written file replaced by generated+prettier; scripts pipe prettier. PGlite harness had hidden both: environment parity gap, not logic gap.
Action: LRN-037 (tests must be seed-agnostic; generated files via deterministic formatter). BLK-006 resolved.
+5
View File
@@ -172,3 +172,8 @@ fix(editor) 2803cf7 — pathology-editor.html 404 in prod (faunosteo.com/patholo
SaaS migration kickoff. Step 0: 8 docs in docs/development/ (27-step plan, domain map, FE/BE arch, migration, tests, 9 open questions) — user validated + decided: no external users, no v2 compat obligation, equine only, 2 SVG assets kept, import anomalies into draft (no silent fix), self-hosted Supabase on adequate infra, design decisions gated by user (ChatGPT), manual report points confirmed. Step 1: 91 characterisation tests, 2 golden fixtures, CHARACTERIZATION_REPORT.md; 271/271, typecheck/lint/build green; host had no pnpm → corepack (LRN-032). Both committed on feature/step-01-characterisation-tests, validated.
- Step 2 (same day): app → apps/app (git mv, 144 R100), pnpm workspace, Node 24 + pnpm 10.13.1 pins, Dockerfile node:24 filtered build (unverified locally, no daemon), Gitea CI, WORKSPACE.md; 271/271, typecheck, lint, build green from root. Finish purged docs/superpowers (lib BDR-065) → restored under docs/history (BDR-025). Both steps merged into develop (c8d48ab, 4959602). BDR-023/024/025, LRN-034. User confirmed `@faunosteo/app`; working method set: harness owns gitflow/memory/quality, user gives step goals, design changes gated. Next: Step 3 on user goals.
## 2026-10-08 (session 3 — Step 3)
Step 3 Supabase foundation on feature/step-03-supabase-foundation (9 commits, pushed). Docker socket denied (BLK-006) → PGlite+pgtap harness (BDR-028). 3 migrations: foundation (private/audit, set_updated_at, append-only audit_logs, log_event), profiles (auth trigger, own-row RLS, column grants), platform_roles (4-value enum BDR-026, RPC-only writes audited BDR-027, helpers hierarchy). 81 pgTAP checks allowed+denied; packages/supabase (client PKCE, types in gen format BDR-029, schema↔types test); app env.supabase null-safe, lib/supabase.ts, entrypoint/env.example; CI supabase job; SUPABASE.md. 278+13 tests, typecheck/lint/build green. Not run: real stack, gen types, seed. LRN-035/036, EVAL-006. Next: user validation; Step 4 (sheet model) parallelizable; Docker access for real-stack proof.
- Same day, Docker access granted by user: real stack up, pgTAP 81/81 after seed-agnostic fix, gen types adopted (prettier pipe), REST script verified, db reset OK. BLK-006 resolved, EVAL-007, LRN-037. Branch still awaiting user validation before finish.
+21
View File
@@ -267,3 +267,24 @@ Apply: any "tests before migration" step on untested legacy code.
`allowBuilds` key in pnpm-workspace.yaml = pnpm ≥10.14 syntax; 10.13.1 ignores it silently → "Ignored build scripts: @swc/core, esbuild" on every install. Fix: `onlyBuiltDependencies` list. Warning persists until `pnpm rebuild` (state cached in node_modules/.modules.yaml), then disappears.
Also: root scripts calling `pnpm -r` fail under `corepack pnpm` (shim not on child PATH) → pin pnpm as root devDependency.
Apply: any pnpm 10.x workspace; check `pnpm --version` vs key syntax before trusting a silent config.
---
## LRN-035 | 2026-10-08 | PGlite + pgtap = Dockerless Supabase RLS tests
`@electric-sql/pglite` 0.3 bundles `pgtap`, `pgcrypto`, `uuid_ossp` (`import { pgtap } from '@electric-sql/pglite/pgtap'`). Boot ~1s, `create extension pgtap with schema extensions` + `set search_path to public, extensions` (else pgTAP functions pollute `public` and break "list public functions" checks; filter `pg_depend deptype='e'` too). `db.exec(file)` runs multi-statement begin…rollback; collect string cells → TAP lines; fail on `/^not ok/` or `# Looks like`. After error: `rollback` to clear aborted tx. Impersonate: `set local role authenticated; set_config('request.jwt.claims', '{"sub":…}', true)`. `now()` frozen in tx → test updated_at by overwriting then `is(updated_at, now())`.
Apply: any Supabase project needing SQL tests in CI without Docker.
---
## LRN-036 | 2026-10-08 | Supabase default privileges grant ALL to anon/authenticated on new public tables
Hosted/local Supabase: `alter default privileges … grant all on tables/functions to anon, authenticated, service_role`. New table or RPC = anon can SELECT/EXECUTE until revoked (RLS still filters rows, but RPC runs). Pattern per migration: `revoke all on <table> from public, anon, authenticated;` then exact grants (column-level for partial UPDATE); `revoke all on function … from public, anon`. Also Postgres default EXECUTE to PUBLIC on functions in own schemas → `alter default privileges in schema private revoke execute on functions from public`. Shim replicates defaults so pgTAP `has_table_privilege('anon',…)` catches omissions.
Apply: every migration; pin with pgTAP privilege checks.
---
## LRN-037 | 2026-10-08 | SQL tests seed-agnostic; generated files through a deterministic formatter
Real stack applies `seed.sql` before `supabase test db`; PGlite harness applies migrations only → absolute `count(*)` and "last owner" assertions passed on PGlite, failed on real stack (6/81). Fix: filter every count by fixture ids; neutralise foreign rows inside the rolled-back tx before invariants like "last owner". `supabase gen types` (CLI 2.120) emits unformatted TS and suggests oxfmt → pipe through project prettier in both `db:types` and `db:types:check`, else CI diff flaps.
Apply: any dual-runner test setup (shim vs real); any CI diff on generated code.
+13 -1
View File
@@ -49,7 +49,19 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [x] Step 0 — preparation docs in docs/development/ (2026-10-08, validated)
- [x] Step 1 — characterisation tests: 7 files / 91 cases, 2 golden fixtures, docs/development/CHARACTERIZATION_REPORT.md; 271/271, typecheck, lint, build green (2026-10-08, branch feature/step-01-characterisation-tests, awaiting validation)
- [x] Step 2 — monorepo workspace: apps/app via git mv (144 files), root scripts, Node 24 + pnpm 10.13.1 pins, Dockerfile node:24 + filtered build, CI .gitea/workflows/ci.yml, WORKSPACE.md; 271/271, typecheck, lint, build green from root (2026-10-08, branch feature/step-02-monorepo-workspace, uncommitted, awaiting validation)
- [ ] Step 3 — Supabase foundation (next, on validation)
- [x] Step 3 — Supabase foundation (2026-10-08, branch feature/step-03-supabase-foundation, awaiting validation; real stack verified: start/reset, pgTAP 81/81, gen types diff, REST script — BLK-006 resolved)
- [x] 3.0 context: plan Step 3, BACKEND_ARCHITECTURE §2-§9, business §4.1/§17/§29; Docker socket denied to user → PGlite harness as executable proof, pgTAP kept for `supabase test db`
- [x] 3.1 supabase/config.toml (CLI pinned as root devDependency) + `supabase/seed.sql` (local users only)
- [x] 3.2 migration 0001 foundation: schemas private/audit, set_updated_at, audit.audit_logs append-only, private.log_event
- [x] 3.3 migration 0002 profiles: table, auth.users trigger, protected columns trigger, RLS own row (+ staff read), grants
- [x] 3.4 migration 0003 platform roles: enum platform_role (owner/admin/moderator/support), profile_roles, private.is_platform_* helpers, grant/revoke RPC with audit, RLS
- [x] 3.5 pgTAP tests supabase/tests/*.sql (schema, profiles RLS allow+deny, roles allow+deny, audit append-only)
- [x] 3.6 packages/supabase: PGlite harness (auth shim + migrations) + vitest RLS suite (allow+deny), database.types.ts (generator format) + schema↔types consistency test, browser client factory
- [x] 3.7 app integration: env.ts supabaseUrl/anonKey, lib/supabase.ts lazy client (null when unconfigured), entrypoint.sh + .env.example + compose; no UI change; tests
- [x] 3.8 CI: supabase job (start, db reset, test db, gen types diff); check job runs PGlite suite via pnpm -r
- [x] 3.9 docs: docs/development/SUPABASE.md (start/reset/test/types/bootstrap owner), CLAUDE.md folder map + scopes, README pointer
- [x] 3.10 verify: typecheck, test:run 278 app + 13 supabase (81 pgTAP), lint 0, build OK; BDR-026..029, LRN-035/036, BLK-006, EVAL-006
- [ ] Step 4 — sheet model + importer (next, on validation; ∥ Step 3 per plan)
---
+6
View File
@@ -8,5 +8,11 @@ APP_BRAND_NAME=Osteo Report
APP_FOOTER_NAME=Osteo Report
APP_TAGLINE=Bilans d'ostéopathie animalière
# Supabase connection exposed to the browser (public values, RLS protects data).
# Empty = app runs without backend. Local stack: `pnpm db:start` prints both.
# NEVER put the service_role key here or in any browser-facing variable.
APP_SUPABASE_URL=
APP_SUPABASE_ANON_KEY=
# Docker Compose project namespace
COMPOSE_PROJECT_NAME=osteo-report
+21 -1
View File
@@ -1,5 +1,6 @@
# Gitea Actions (same syntax as GitHub Actions). Runs on the self-hosted forge
# runner; no external provider. No Supabase dependency at this stage.
# runner; no external provider. The check job covers the SQL layer through the
# PGlite harness (no Docker); the supabase job replays it on the real stack.
name: ci
on:
@@ -30,3 +31,22 @@ jobs:
- uses: actions/checkout@v4
- name: Docker image builds (runner needs a Docker daemon)
run: docker build -t faunosteo:ci .
supabase:
runs-on: ubuntu-latest
needs: check
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with:
node-version-file: .nvmrc
- run: corepack enable && corepack prepare --activate
- run: pnpm install --frozen-lockfile
- name: Start the local stack (runner needs a Docker daemon); applies migrations + seed
run: pnpm supabase start
- name: pgTAP on the real PostgreSQL image
run: pnpm db:test
- name: Generated types match the schema
run: pnpm db:types:check
- if: always()
run: pnpm supabase stop --no-backup
+57 -8
View File
@@ -11,7 +11,9 @@ Single-praticien French web app for veterinary osteopathy bilans on animal anato
Practitioner clicks anatomical zones, builds observations with pathologies/severity,
writes conclusion, and exports an A4 PDF. PDF carries the full JSON state as a native
attachment so importing it restores the session for a follow-up.
Static SPA, no backend, no auth. Deployed via Docker + nginx on Scaleway VPS.
SPA deployed via Docker + nginx on Scaleway VPS. Backend foundation on Supabase
(PostgreSQL + Auth + RLS) since Step 3 of the SaaS plan: profiles, platform roles and
audit log exist; the UI does not use the client yet (local-only flows unchanged).
MVP species: equine only. Open-source MIT.
---
@@ -32,15 +34,18 @@ MVP species: equine only. Open-source MIT.
| SVG raster | native Image/canvas (no dependency) | — |
| Animation | motion | 11 |
| Tests | vitest + happy-dom + @testing-library/react | 3.x |
| Backend | Supabase (PostgreSQL 17, GoTrue, PostgREST) — CLI pinned as root devDependency | CLI 2.120 |
| DB client | @supabase/supabase-js (packages/supabase) | 2.x |
| SQL tests | pgTAP under supabase/tests, run by `supabase test db` and by PGlite (Dockerless) | PGlite 0.3 |
| Deploy | Docker multi-stage → nginx:alpine | — |
---
## Build commands
pnpm workspace: `apps/app` = the private application, `packages/` empty for
now (see `docs/development/WORKSPACE.md`). Every command below runs from the
repository root and delegates to the packages.
pnpm workspace: `apps/app` = the private application, `packages/supabase` =
Supabase access layer (see `docs/development/WORKSPACE.md`). Every command
below runs from the repository root and delegates to the packages.
```bash
# Development
@@ -66,6 +71,13 @@ pnpm lint
# Format
pnpm format
# Supabase local stack (Docker) — docs/development/SUPABASE.md
pnpm db:start # start stack, apply migrations + seed
pnpm db:reset # replay from zero
pnpm db:test # pgTAP on the real stack
pnpm db:types # regenerate packages/supabase/src/database.types.ts
pnpm db:types:check # CI diff
```
## Docker commands
@@ -96,6 +108,8 @@ pnpm test # vitest watch — dev loop
Test files live in `apps/app/tests/unit/*.test.ts(x)`; golden fixtures in
`apps/app/tests/fixtures/`. Setup: `apps/app/tests/setup.ts` imports
@testing-library/jest-dom. Characterisation suite: files prefixed `char.`.
SQL: `supabase/tests/*.sql` (pgTAP) run by `packages/supabase/tests/db/pgtap.test.ts`
on PGlite (part of `pnpm test:run`) and by `pnpm db:test` on the real stack.
---
@@ -159,7 +173,7 @@ faunosteo/
│ ├─ pdf/
│ │ ├─ export.ts + import.ts + attachment.ts + fonts.ts
│ │ └─ render/{header,footer,observationPage,conclusionPage,svgToPng,text,logo,linkAnnotation}.ts
│ ├─ lib/{dates,id,assert,zoneMatch,spineZones}.ts
│ ├─ lib/{dates,id,assert,zoneMatch,spineZones,supabase}.ts ← supabase.ts: getSupabaseClient() | null
│ ├─ styles/{index,tokens,svg-editor}.css ← Tailwind v4 CSS-first + SVG editor styles
│ └─ main.tsx
├─ tests/
@@ -178,7 +192,14 @@ faunosteo/
├─ eslint.config.js, index.html, package.json (@faunosteo/app)
├─ tsconfig*.json, vite.config.ts, vitest.config.ts
│ (end of apps/app)
├─ packages/README.md ← future shared packages (none yet)
├─ packages/supabase/ ← @faunosteo/supabase
│ ├─ src/{index,client,database.types}.ts ← typed browser client + generated types
│ └─ tests/{client.test.ts,db/} ← PGlite harness, shim, pgTAP runner, schema↔types test
├─ supabase/
│ ├─ config.toml, seed.sql ← CLI config (public schema only), local dev accounts
│ ├─ migrations/*.sql ← forward-only; foundation, profiles, platform_roles
│ └─ tests/*.sql ← pgTAP: allowed + denied paths per policy
├─ packages/README.md ← shared packages index
├─ .gitea/workflows/ci.yml ← CI: install, typecheck, test, lint, build, docker
├─ .claude/{tasks/TODO.md,memory/,audits/}
├─ Dockerfile, docker-compose.yml, docker/
@@ -224,6 +245,14 @@ Runtime config
→ index.html loads env.js before bundle
→ src/config/env.ts reads window.__APP_CONFIG__ → VITE_APP_* → defaults
→ ConfigProvider exposes via React context
→ appConfig.supabase (url + anon key) or null → lib/supabase.ts lazy client
Database (Supabase)
→ schemas: public (exposed, RLS on every table) / private (helpers, triggers) / audit (append-only)
→ auth.users insert → private.handle_new_auth_user() → public.profiles row
→ platform roles: public.profile_roles written only by grant_platform_role / revoke_platform_role
(security definer, actor checked via private.is_platform_*; every call logged by private.log_event)
→ tests: supabase/tests/*.sql (pgTAP) via PGlite in CI check job and `supabase test db`
```
---
@@ -278,6 +307,20 @@ Runtime config
- boneIds: [] = all zones; speciesIds: [] = all species
- Source types: manual | journal | database | web
### Database (Supabase)
- Platform roles (`platform_role`: owner/admin/moderator/support) are NOT professional
statuses (practitioner/student/professor come from verification, cabinet roles from
organization_members). Never add a professional status to `platform_role`.
- Every `public` table: RLS enabled, `revoke all` from API roles then exact grants,
separate policies per command, no `using (true)` for anon/authenticated (test-enforced).
- Writes that change privileges or sensitive state go through a security-definer RPC
that checks `auth.uid()` and calls `private.log_event()`. Never a direct table policy.
- Helpers in `private` are `security definer`, `set search_path = ''`, EXECUTE revoked
from public and granted only to the roles that evaluate them.
- A migration is never edited once applied. Each migration ships its pgTAP file with
allowed AND denied cases, and a regenerated `database.types.ts`.
- The browser holds the anon key only. `service_role` never appears in env.js, .env.example or code.
### Component stubs
- Scaffold stubs render <div>ComponentName placeholder</div>
- Replace stub body entirely when implementing — no partial edits on stubs
@@ -288,7 +331,8 @@ Runtime config
- **React SPA**: explicit exception — this is a practitioner tool, not a public website.
No indexing needed. SPA is correct. (See BDR-001)
- **No API versioning**: no backend, no API routes. Section N/A.
- **No API versioning**: no hand-written HTTP API. Supabase exposes tables/RPC through
PostgREST; breaking changes are handled by new migrations and RPC names, not URL versions.
- **80-char line limit**: relaxed to 100 for TypeScript generics and long Zod chains.
---
@@ -313,6 +357,9 @@ Runtime config
| @testing-library/react | Component testing utilities |
| @testing-library/jest-dom | Custom DOM matchers |
| eslint 9 | Linting (flat config) |
| @supabase/supabase-js 2 | Typed client (packages/supabase) |
| supabase (CLI) 2.120 | Local stack, migrations, pgTAP runner, type generation |
| @electric-sql/pglite 0.3 | PostgreSQL 17 in WASM: runs the pgTAP suite without Docker |
| prettier 3 | Code formatting |
---
@@ -327,11 +374,13 @@ Runtime config
- Ask before any change to importReportFromPdf or extractReportJson — these handle user data.
- After PDF roundtrip tests fail: check attachment bytes, then Zod validation, then DecompressionStream inflation.
- Node 24 / pnpm 10.13.1: `corepack enable` or `corepack pnpm`; never a global install.
- SQL change: `pnpm --filter @faunosteo/supabase test:run` (PGlite) before commit; `pnpm db:reset && pnpm db:test`
on the real stack when Docker is available; regenerate types (`pnpm db:types`).
## Commit message convention
Conventional Commits format. Subject ≤72 chars, imperative mood, no trailing period.
Allowed scopes: `schema`, `store`, `anatomy`, `pdf`, `editor`, `home`, `new`, `ui`, `config`, `species`, `i18n`, `docker`, `docs`, `tests`, `chore`, `app`, `workspace`, `ci`.
Allowed scopes: `schema`, `store`, `anatomy`, `pdf`, `editor`, `home`, `new`, `ui`, `config`, `species`, `i18n`, `docker`, `docs`, `tests`, `chore`, `app`, `workspace`, `ci`, `supabase`, `domain`, `worker`, `public-web`.
Examples:
- `test(schema): cover Report version literal`
+5 -1
View File
@@ -36,9 +36,13 @@ each one explicitly.
| `APP_BRAND_NAME` | yes | `Faunosteo` | Header brand block, PDF header. Praticien-visible identity. |
| `APP_FOOTER_NAME` | yes | `Faunosteo` | Footer copyright line. |
| `APP_TAGLINE` | yes | `Outils pour ostéopathes animaliers` | Hero tagline on Home. |
| `APP_SUPABASE_URL` | no | empty | Supabase project URL exposed to the browser. Empty = app runs without backend (current mode). |
| `APP_SUPABASE_ANON_KEY` | no | empty | Supabase anon (publishable) key. Public by design, data stays behind RLS. Never the service_role key. |
| `PORT` | no | `8080` | Container listen port. Must be `>=1024` — the container runs as a non-root `nginx` user and cannot bind privileged ports. |
No secrets are required — there is no API, no DB, no provider credential.
No secrets are required in this file: the anon key is public by design and
the service_role key never leaves the Supabase host (see
`docs/development/SUPABASE.md`).
The `.env` file is not sensitive but should still be `chmod 600` to keep
local identity overrides private.
+1
View File
@@ -11,6 +11,7 @@ RUN corepack enable && corepack prepare pnpm@10.13.1 --activate
# Workspace manifests first for layer caching (install depends only on these)
COPY package.json pnpm-lock.yaml pnpm-workspace.yaml .npmrc ./
COPY apps/app/package.json apps/app/
COPY packages/supabase/package.json packages/supabase/
RUN pnpm install --frozen-lockfile
+6 -3
View File
@@ -39,7 +39,7 @@ contract.
## Stack
- Node.js 20
- Node.js 24 LTS + pnpm 10.13 (corepack)
- React 19 + TypeScript 5 (strict)
- Vite 7 + @vitejs/plugin-react-swc
- Tailwind CSS v4 (CSS-first, no postcss config)
@@ -48,6 +48,7 @@ contract.
- pdf-lib 1.17 (PDF generation + native attachments)
- motion 11 (animations)
- vitest 3 + happy-dom + @testing-library/react
- Supabase (PostgreSQL 17, Auth, RLS) via the pinned CLI; `@supabase/supabase-js` 2; PGlite for Dockerless SQL tests
---
@@ -79,7 +80,7 @@ docker compose up --build
```bash
pnpm typecheck # TypeScript strict, no emit
pnpm lint # ESLint 9 flat config, 0 warnings
pnpm test:run # vitest run (271 tests)
pnpm test:run # vitest run (app 278 + supabase 13, incl. 79 pgTAP checks on PGlite)
pnpm build # tsc + vite build → apps/app/dist/
```
@@ -104,6 +105,7 @@ For production deployment (VPS provisioning, firewall, TLS, nginx reverse proxy,
- [docs/ADDING-A-SPECIES.md](docs/ADDING-A-SPECIES.md) — guide for adding a second species post-MVP
- [docs/PATHOLOGIES-FORMAT.md](docs/PATHOLOGIES-FORMAT.md) — findings catalog format + authoring guide
- [docs/PDF-FORMAT.md](docs/PDF-FORMAT.md) — PDF page layout and attachment contract
- [docs/development/SUPABASE.md](docs/development/SUPABASE.md) — local Supabase stack, migrations, RLS tests, generated types
- [DEPLOY.md](DEPLOY.md) — production VPS deploy guide (Docker + nginx + TLS + hardening)
- [CHANGELOG.md](CHANGELOG.md) — versioned release notes
- [.claude/tasks/TODO.md](.claude/tasks/TODO.md) — implementation roadmap
@@ -127,7 +129,8 @@ faunosteo/ pnpm workspace (see docs/development/WORKSPACE.md)
├─ src/lib/ id, dates, assert utilities
├─ src/styles/ Tailwind v4 CSS + design tokens
├─ tests/unit/ vitest tests (apps/app/tests, incl. characterisation suite)
├─ packages/ shared packages, none yet
├─ packages/supabase/ @faunosteo/supabase: typed client, generated types, PGlite SQL test harness
├─ supabase/ CLI config, SQL migrations, local seed, pgTAP tests
├─ docker/ entrypoint.sh + nginx.conf
├─ docs/ conventions + species guide + PDF spec
├─ index.html SPA entry point
+1
View File
@@ -15,6 +15,7 @@
"scaffold:species": "node scripts/scaffold-species.mjs"
},
"dependencies": {
"@faunosteo/supabase": "workspace:*",
"motion": "^11.11.17",
"pdf-lib": "^1.17.1",
"react": "^19.0.0",
+49 -12
View File
@@ -1,10 +1,11 @@
/// <reference types="vite/client" />
import type { SupabaseConnection } from '@faunosteo/supabase'
/**
* Runtime application config.
* Resolution order:
* 1. window.__APP_CONFIG__ (injected by docker/entrypoint.sh)
* 2. import.meta.env.VITE_APP_* (build-time Vite defines)
* 2. import.meta.env.VITE_* (build-time Vite defines)
* 3. Hard-coded defaults
*/
export interface AppConfig {
@@ -12,41 +13,77 @@ export interface AppConfig {
brandName: string
footerName: string
tagline: string
/** null = no backend configured; the app keeps its local-only behaviour. */
supabase: SupabaseConnection | null
}
/** Shape written by docker/entrypoint.sh (flat strings, empty = unset). */
export interface RuntimeConfig {
siteName?: string
brandName?: string
footerName?: string
tagline?: string
supabaseUrl?: string
supabaseAnonKey?: string
}
declare global {
interface Window {
__APP_CONFIG__?: Partial<AppConfig>
__APP_CONFIG__?: RuntimeConfig
}
}
const DEFAULTS: AppConfig = {
const DEFAULTS: Omit<AppConfig, 'supabase'> = {
siteName: 'Faunosteo',
brandName: 'Faunosteo',
footerName: 'Faunosteo',
tagline: 'Outils pour ostéopathes animaliers',
}
function resolveConfig(): AppConfig {
const runtime = typeof window !== 'undefined' ? window.__APP_CONFIG__ : {}
/** Empty strings from env.js or Vite count as "not set". */
function nonEmpty(value: string | undefined): string | undefined {
return value && value.trim() !== '' ? value : undefined
}
/** Both settings are required; one without the other is a misconfiguration. */
export function resolveSupabaseConnection(
url: string | undefined,
anonKey: string | undefined,
): SupabaseConnection | null {
const cleanUrl = nonEmpty(url)
const cleanKey = nonEmpty(anonKey)
if (cleanUrl && cleanKey) return { url: cleanUrl, anonKey: cleanKey }
if ((cleanUrl || cleanKey) && import.meta.env.DEV) {
console.warn(
'[config] supabaseUrl and supabaseAnonKey must be set together; Supabase disabled',
)
}
return null
}
export function resolveConfig(runtime: RuntimeConfig = {}): AppConfig {
return {
siteName:
runtime?.siteName ??
runtime.siteName ??
import.meta.env.VITE_APP_SITE_NAME ??
DEFAULTS.siteName,
brandName:
runtime?.brandName ??
runtime.brandName ??
import.meta.env.VITE_APP_BRAND_NAME ??
DEFAULTS.brandName,
footerName:
runtime?.footerName ??
runtime.footerName ??
import.meta.env.VITE_APP_FOOTER_NAME ??
DEFAULTS.footerName,
tagline:
runtime?.tagline ??
import.meta.env.VITE_APP_TAGLINE ??
DEFAULTS.tagline,
runtime.tagline ?? import.meta.env.VITE_APP_TAGLINE ?? DEFAULTS.tagline,
supabase: resolveSupabaseConnection(
runtime.supabaseUrl ?? import.meta.env.VITE_SUPABASE_URL,
runtime.supabaseAnonKey ?? import.meta.env.VITE_SUPABASE_ANON_KEY,
),
}
}
export const appConfig: AppConfig = resolveConfig()
export const appConfig: AppConfig = resolveConfig(
typeof window !== 'undefined' ? window.__APP_CONFIG__ : undefined,
)
+27
View File
@@ -0,0 +1,27 @@
import { createBrowserClient, type FaunosteoClient } from '@faunosteo/supabase'
import { appConfig, type AppConfig } from '@/config/env'
let cached: { connectionUrl: string; client: FaunosteoClient } | null = null
/**
* Lazily created Supabase client, or null when the deployment has no backend
* configured. Callers must handle null: the current local-only flows do not
* depend on Supabase. No UI uses this yet (foundation step).
*/
export function getSupabaseClient(
config: AppConfig = appConfig,
): FaunosteoClient | null {
if (!config.supabase) return null
if (cached?.connectionUrl !== config.supabase.url) {
cached = {
connectionUrl: config.supabase.url,
client: createBrowserClient(config.supabase),
}
}
return cached.client
}
/** True when the app can talk to Supabase. */
export function isSupabaseConfigured(config: AppConfig = appConfig): boolean {
return config.supabase !== null
}
+37
View File
@@ -0,0 +1,37 @@
import { describe, it, expect } from 'vitest'
import { resolveConfig, resolveSupabaseConnection } from '@/config/env'
describe('resolveConfig', () => {
it('keeps the identity defaults and no Supabase when nothing is injected', () => {
const config = resolveConfig({})
expect(config.brandName).toBe('Faunosteo')
expect(config.supabase).toBeNull()
})
it('reads the runtime Supabase connection from env.js values', () => {
const config = resolveConfig({
supabaseUrl: 'http://127.0.0.1:54321',
supabaseAnonKey: 'anon',
})
expect(config.supabase).toEqual({
url: 'http://127.0.0.1:54321',
anonKey: 'anon',
})
})
it('still resolves identity strings injected at runtime', () => {
expect(resolveConfig({ brandName: 'Clinic' }).brandName).toBe('Clinic')
})
})
describe('resolveSupabaseConnection', () => {
it('treats empty strings as unset', () => {
expect(resolveSupabaseConnection('', '')).toBeNull()
expect(resolveSupabaseConnection(' ', 'key')).toBeNull()
})
it('refuses a half configuration', () => {
expect(resolveSupabaseConnection('http://x', undefined)).toBeNull()
expect(resolveSupabaseConnection(undefined, 'key')).toBeNull()
})
})
+29
View File
@@ -0,0 +1,29 @@
import { describe, it, expect } from 'vitest'
import { getSupabaseClient, isSupabaseConfigured } from '@/lib/supabase'
import type { AppConfig } from '@/config/env'
const base: AppConfig = {
siteName: 'S',
brandName: 'B',
footerName: 'F',
tagline: 'T',
supabase: null,
}
describe('getSupabaseClient', () => {
it('returns null when no backend is configured (current default)', () => {
expect(getSupabaseClient(base)).toBeNull()
expect(isSupabaseConfigured(base)).toBe(false)
})
it('creates one client per connection and reuses it', () => {
const configured: AppConfig = {
...base,
supabase: { url: 'http://127.0.0.1:54321', anonKey: 'anon' },
}
const first = getSupabaseClient(configured)
expect(first).not.toBeNull()
expect(getSupabaseClient(configured)).toBe(first)
expect(isSupabaseConfigured(configured)).toBe(true)
})
})
+7 -1
View File
@@ -17,13 +17,19 @@ SITE_NAME=$(js_escape "${APP_SITE_NAME:-Faunosteo}")
BRAND_NAME=$(js_escape "${APP_BRAND_NAME:-Faunosteo}")
FOOTER_NAME=$(js_escape "${APP_FOOTER_NAME:-Faunosteo}")
TAGLINE=$(js_escape "${APP_TAGLINE:-Outils pour ostéopathes animaliers}")
# Supabase public connection (anon key only; empty = backend disabled).
# The service-role key must never be set here.
SUPABASE_URL=$(js_escape "${APP_SUPABASE_URL:-}")
SUPABASE_ANON_KEY=$(js_escape "${APP_SUPABASE_ANON_KEY:-}")
cat > "$ENV_JS" <<EOF
window.__APP_CONFIG__ = {
siteName: "${SITE_NAME}",
brandName: "${BRAND_NAME}",
footerName: "${FOOTER_NAME}",
tagline: "${TAGLINE}"
tagline: "${TAGLINE}",
supabaseUrl: "${SUPABASE_URL}",
supabaseAnonKey: "${SUPABASE_ANON_KEY}"
};
EOF
+188
View File
@@ -0,0 +1,188 @@
# Supabase: local stack, migrations, tests
Status: Step 3 deliverable, 2026-10-08. Covers the foundation only (profiles,
platform roles, audit log). Conventions: `BACKEND_ARCHITECTURE.md` §3–§9.
## 1. Layout
```text
supabase/
├─ config.toml CLI config (public schema exposed only, PG 17, strong passwords)
├─ migrations/ forward-only SQL, <timestamp>_<name>.sql
│ ├─ 20261008100000_foundation.sql schemas private/audit, updated_at, audit log
│ ├─ 20261008100100_profiles.sql profiles + auth.users trigger + RLS
│ └─ 20261008100200_platform_roles.sql platform_role, profile_roles, helpers, RPCs
├─ seed.sql LOCAL dev accounts + first owner (never run in prod)
└─ tests/ pgTAP, one file per concern, allowed AND denied paths
packages/supabase/
├─ src/client.ts createBrowserClient() (anon key, PKCE)
├─ src/database.types.ts `supabase gen types` output
└─ tests/db/ PGlite harness: runs the pgTAP files without Docker
```
## 2. Prerequisites
- Node 24 + pnpm via corepack (`WORKSPACE.md`).
- Docker daemon reachable by your user for the real stack. If `docker info`
says `permission denied ... docker.sock`, add yourself to the `docker`
group and log in again:
```bash
sudo usermod -aG docker "$USER"
```
- No Docker: the PGlite suite still runs (see §5), the CLI commands do not.
The Supabase CLI is a root devDependency (`pnpm supabase <cmd>`), pinned
like every other tool. Never install it globally.
## 3. Start, stop, reset
```bash
pnpm db:start # supabase start: pulls images, applies migrations + seed, prints URLs and keys
pnpm db:stop # supabase stop (keeps the volume)
pnpm db:reset # drop + replay every migration + seed from zero
```
Local endpoints (`config.toml`):
| Service | URL |
|---|---|
| API (PostgREST, Auth, Storage) | `http://127.0.0.1:54321` |
| PostgreSQL | `postgresql://postgres:postgres@127.0.0.1:54322/postgres` |
| Studio | `http://127.0.0.1:54323` |
| Mail catcher (confirmation / OTP mails) | `http://127.0.0.1:54324` |
`pnpm db:start` prints the `anon` and `service_role` keys. Only the anon key
ever reaches the browser.
Seed accounts (local only, password `LocalDev-only-password-1`):
| Email | Role |
|---|---|
| `owner@faunosteo.local` | platform owner (bootstrapped by `seed.sql`) |
| `alice@faunosteo.local` | plain user |
| `bob@faunosteo.local` | plain user |
## 4. Writing a migration
1. `pnpm supabase migration new <name>` creates `supabase/migrations/<timestamp>_<name>.sql`.
2. A migration that adds a table adds, in the same file: RLS enable, explicit
`revoke all ... from public, anon, authenticated` then the exact grants,
separate SELECT / INSERT / UPDATE / DELETE policies, indexes, comments.
3. Add or extend a pgTAP file under `supabase/tests/`: the allowed path and
every denied path (other user, anon, direct write bypassing an RPC). Scope
counts to the fixture ids: on the real stack the seed accounts exist, in
PGlite they do not.
4. `pnpm --filter @faunosteo/supabase test:run` (PGlite, seconds), then
`pnpm db:reset && pnpm db:test` on the real stack.
5. `pnpm db:types` and commit `packages/supabase/src/database.types.ts`.
6. Never edit an applied migration. Corrections are new migrations.
Rules enforced by the schema-types test for every future `public` table:
RLS enabled, no `using (true)` / `with check (true)` policy for `anon` or
`authenticated`.
## 5. Tests
Two runners, one SQL source of truth (`supabase/tests/*.sql`, pgTAP):
| Command | Engine | Needs Docker | What runs |
|---|---|---|---|
| `pnpm --filter @faunosteo/supabase test:run` | PGlite (PostgreSQL 17 in WASM) | no | shim of the Supabase base schema + all migrations + every pgTAP file; schema ↔ types check; client factory |
| `pnpm db:test` | `supabase test db` (pg_prove in the local stack) | yes | the same pgTAP files against the real Supabase image |
`pnpm test:run` at the root runs the PGlite suite together with the app
suite. The shim (`packages/supabase/tests/db/supabase-shim.sql`) recreates
the API roles, `auth.users`, `auth.uid()` and the permissive default
privileges of Supabase so that a forgotten `revoke` fails a test.
How a test impersonates a user (same technique in both runners):
```sql
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"<user uuid>","role":"authenticated"}', true);
```
## 6. Generated types
```bash
pnpm db:types # regenerate packages/supabase/src/database.types.ts (local stack running)
pnpm db:types:check # CI: fail on any diff
```
The CLI emits unformatted TypeScript; both scripts pipe it through Prettier
(repo config) so the committed file is stable byte for byte. The schema-types
test checks tables, columns, enum labels and RPC argument names against the
migrated schema, so a stale file fails before CI.
## 7. First platform owner in a real environment
The RPCs refuse self-grants and need an existing owner or admin. The first
owner is created once, from a privileged SQL session (service connection,
`psql` on the host), never from the browser:
```sql
select private.assign_platform_role(null, '<auth.users.id of the owner>', 'owner');
```
The call is audited with a null actor. Afterwards every role change goes
through `grant_platform_role` / `revoke_platform_role`.
## 8. Manual validation (Definition of Done: "an authenticated request hits a protected table safely")
```bash
URL=http://127.0.0.1:54321
ANON=<anon key printed by pnpm db:start>
token() { # $1 = email
curl -s -X POST "$URL/auth/v1/token?grant_type=password" \
-H "apikey: $ANON" -H "Content-Type: application/json" \
-d "{\"email\":\"$1\",\"password\":\"LocalDev-only-password-1\"}" | jq -r .access_token
}
ALICE=$(token alice@faunosteo.local); OWNER=$(token owner@faunosteo.local)
ALICE_ID=10000000-0000-0000-0000-00000000000a
# 1. alice reads exactly one profile (hers)
curl -s "$URL/rest/v1/profiles?select=id,display_name" -H "apikey: $ANON" -H "Authorization: Bearer $ALICE"
# 2. anon reads nothing (permission denied)
curl -s "$URL/rest/v1/profiles" -H "apikey: $ANON"
# 3. alice cannot deactivate herself (column privilege) nor self-grant admin
curl -s -X PATCH "$URL/rest/v1/profiles?id=eq.$ALICE_ID" -H "apikey: $ANON" \
-H "Authorization: Bearer $ALICE" -H "Content-Type: application/json" -d '{"active":false}'
curl -s -X POST "$URL/rest/v1/rpc/grant_platform_role" -H "apikey: $ANON" \
-H "Authorization: Bearer $ALICE" -H "Content-Type: application/json" \
-d "{\"target_user_id\":\"$ALICE_ID\",\"role\":\"admin\"}"
# 4. the owner grants moderator to alice; the grant is audited
curl -s -X POST "$URL/rest/v1/rpc/grant_platform_role" -H "apikey: $ANON" \
-H "Authorization: Bearer $OWNER" -H "Content-Type: application/json" \
-d "{\"target_user_id\":\"$ALICE_ID\",\"role\":\"moderator\"}"
psql postgresql://postgres:postgres@127.0.0.1:54322/postgres \
-c "select actor_user_id, action, target_user_id, metadata from audit.audit_logs order by occurred_at"
```
Expected: 1 → one row; 2 → `42501`; 3 → both `42501`; 4 → a uuid, then two
audit rows (bootstrap with null actor, grant by the owner).
## 9. Wiring the app
`.env` (Docker) or `apps/app/.env.local` (Vite dev):
```bash
APP_SUPABASE_URL=http://127.0.0.1:54321 # VITE_SUPABASE_URL in dev
APP_SUPABASE_ANON_KEY=<anon key> # VITE_SUPABASE_ANON_KEY in dev
```
Both empty (the default) keeps the app in its current local-only mode:
`getSupabaseClient()` returns null. No screen uses the client yet.
## 10. Self-hosted parity
The local stack runs the same images as a self-hosted deployment
(`supabase/docker` compose), so migrations, policies and tests transfer
unchanged. The self-hosted runbook (VPS sizing, secrets, backups, TLS) is a
separate deliverable once the hosting question (OPEN_QUESTIONS Q2) is
settled; it reuses `pnpm supabase db push --db-url <...>` for migrations.
+2 -1
View File
@@ -13,7 +13,8 @@ faunosteo/
│ ├─ src/ public/ tests/ scripts/ index.html
│ ├─ vite.config.ts vitest.config.ts tsconfig*.json eslint.config.js
│ └─ package.json app dependencies and scripts
├─ packages/ shared code, empty on purpose (see packages/README.md)
├─ packages/supabase/ @faunosteo/supabase: typed client, generated types, PGlite SQL tests
├─ supabase/ Supabase CLI config, migrations, seed, pgTAP tests (docs/development/SUPABASE.md)
├─ docker/ nginx.conf, entrypoint.sh (unchanged)
├─ docs/ conventions, audit, development plan
├─ logos/ brand sources
+9 -2
View File
@@ -19,10 +19,17 @@
"lint": "pnpm -r lint",
"format": "prettier --write .",
"check": "pnpm typecheck && pnpm test:run && pnpm lint && pnpm build",
"scaffold:species": "pnpm --filter @faunosteo/app scaffold:species"
"scaffold:species": "pnpm --filter @faunosteo/app scaffold:species",
"db:start": "supabase start",
"db:stop": "supabase stop",
"db:reset": "supabase db reset",
"db:test": "supabase test db",
"db:types": "supabase gen types typescript --local --schema public | prettier --parser typescript > packages/supabase/src/database.types.ts",
"db:types:check": "supabase gen types typescript --local --schema public | prettier --parser typescript | diff - packages/supabase/src/database.types.ts"
},
"devDependencies": {
"pnpm": "10.13.1",
"prettier": "^3.4.2"
"prettier": "^3.4.2",
"supabase": "^2.100.0"
}
}
+4 -4
View File
@@ -1,8 +1,8 @@
# packages/
Shared code lives here once it has a real owner and real content. Nothing is
extracted yet: an empty package would only add build configuration to maintain
(IMPLEMENTATION_PLAN.md Step 2, FRONTEND_ARCHITECTURE.md §6).
Shared code lives here once it has a real owner and real content: an empty
package would only add build configuration to maintain (IMPLEMENTATION_PLAN.md
Step 2, FRONTEND_ARCHITECTURE.md §6). First package: `supabase/` (Step 3).
Planned packages and the step that creates each one:
@@ -12,7 +12,7 @@ Planned packages and the step that creates each one:
| `@faunosteo/anatomy` | SVG convention parser, legacy importer, renderer helpers, spine logic | Step 4 |
| `@faunosteo/pdf` | export / import / attachment, render helpers | Step 6 (PDF v3) |
| `@faunosteo/i18n` | FR/EN dictionaries (no React) + `useT` | first second consumer (public-web or worker) |
| `@faunosteo/supabase` | client factories, generated database types, typed RPC wrappers | Step 3 (Supabase foundation) |
| `@faunosteo/supabase` | browser client factory, generated database types, PGlite harness running the pgTAP suite | **created**, Step 3 |
| `@faunosteo/config` | runtime config resolution shared by app, public-web, worker | with public-web |
| `@faunosteo/ui` | UI primitives and design tokens | only when public-web reuses them |
+20
View File
@@ -0,0 +1,20 @@
import globals from 'globals'
import tseslint from 'typescript-eslint'
export default tseslint.config(
{ ignores: ['node_modules/**'] },
{
files: ['**/*.ts'],
extends: [...tseslint.configs.recommended],
languageOptions: {
globals: { ...globals.node, ...globals.es2022 },
},
rules: {
'@typescript-eslint/no-explicit-any': 'warn',
'@typescript-eslint/no-unused-vars': [
'error',
{ argsIgnorePattern: '^_' },
],
},
},
)
+33
View File
@@ -0,0 +1,33 @@
{
"name": "@faunosteo/supabase",
"version": "0.1.0",
"private": true,
"description": "Faunosteo Supabase access layer: typed browser client, generated database types, SQL test harness",
"license": "MIT",
"type": "module",
"main": "./src/index.ts",
"types": "./src/index.ts",
"exports": {
".": "./src/index.ts",
"./types": "./src/database.types.ts"
},
"scripts": {
"typecheck": "tsc -p tsconfig.json --noEmit",
"test": "vitest",
"test:run": "vitest run",
"lint": "eslint . --max-warnings 0",
"build": "tsc -p tsconfig.json --noEmit"
},
"dependencies": {
"@supabase/supabase-js": "^2.100.0"
},
"devDependencies": {
"@electric-sql/pglite": "^0.3.0",
"@types/node": "^20.19.41",
"eslint": "^9.17.0",
"globals": "^15.14.0",
"typescript": "^5.7.2",
"typescript-eslint": "^8.19.0",
"vitest": "^3.2.7"
}
}
+31
View File
@@ -0,0 +1,31 @@
import { createClient, type SupabaseClient } from '@supabase/supabase-js'
import type { Database } from './database.types'
/** Typed Supabase client for the Faunosteo database. */
export type FaunosteoClient = SupabaseClient<Database>
/**
* Public connection settings. The anon (publishable) key is safe to ship to
* the browser: every table is behind RLS. The service-role key never is.
*/
export interface SupabaseConnection {
url: string
anonKey: string
}
/**
* Browser client: session persisted in localStorage, tokens refreshed in the
* background, PKCE for OAuth and magic-link redirects.
*/
export function createBrowserClient(
connection: SupabaseConnection,
): FaunosteoClient {
return createClient<Database>(connection.url, connection.anonKey, {
auth: {
persistSession: true,
autoRefreshToken: true,
detectSessionInUrl: true,
flowType: 'pkce',
},
})
}
+264
View File
@@ -0,0 +1,264 @@
export type Json =
| string
| number
| boolean
| null
| { [key: string]: Json | undefined }
| Json[]
export type Database = {
public: {
Tables: {
profile_roles: {
Row: {
granted_at: string
granted_by: string | null
id: string
revoke_reason: string | null
revoked_at: string | null
revoked_by: string | null
role: Database['public']['Enums']['platform_role']
user_id: string
}
ComputedFields: never
Insert: {
granted_at?: string
granted_by?: string | null
id?: string
revoke_reason?: string | null
revoked_at?: string | null
revoked_by?: string | null
role: Database['public']['Enums']['platform_role']
user_id: string
}
Update: {
granted_at?: string
granted_by?: string | null
id?: string
revoke_reason?: string | null
revoked_at?: string | null
revoked_by?: string | null
role?: Database['public']['Enums']['platform_role']
user_id?: string
}
Relationships: [
{
foreignKeyName: 'profile_roles_granted_by_fkey'
columns: ['granted_by']
isOneToOne: false
referencedRelation: 'profiles'
referencedColumns: ['id']
},
{
foreignKeyName: 'profile_roles_revoked_by_fkey'
columns: ['revoked_by']
isOneToOne: false
referencedRelation: 'profiles'
referencedColumns: ['id']
},
{
foreignKeyName: 'profile_roles_user_id_fkey'
columns: ['user_id']
isOneToOne: false
referencedRelation: 'profiles'
referencedColumns: ['id']
},
]
}
profiles: {
Row: {
active: boolean
created_at: string
display_name: string
first_name: string | null
id: string
last_name: string | null
locale: string
phone: string | null
phone_verified_at: string | null
timezone: string
updated_at: string
}
ComputedFields: never
Insert: {
active?: boolean
created_at?: string
display_name: string
first_name?: string | null
id: string
last_name?: string | null
locale?: string
phone?: string | null
phone_verified_at?: string | null
timezone?: string
updated_at?: string
}
Update: {
active?: boolean
created_at?: string
display_name?: string
first_name?: string | null
id?: string
last_name?: string | null
locale?: string
phone?: string | null
phone_verified_at?: string | null
timezone?: string
updated_at?: string
}
Relationships: []
}
}
Views: {
[_ in never]: never
}
Functions: {
grant_platform_role: {
Args: {
role: Database['public']['Enums']['platform_role']
target_user_id: string
}
Returns: string
}
revoke_platform_role: {
Args: {
reason?: string
role: Database['public']['Enums']['platform_role']
target_user_id: string
}
Returns: string
}
}
Enums: {
platform_role: 'owner' | 'admin' | 'moderator' | 'support'
}
CompositeTypes: {
[_ in never]: never
}
}
}
type DatabaseWithoutInternals = Omit<Database, '__InternalSupabase'>
type DefaultSchema = DatabaseWithoutInternals[Extract<keyof Database, 'public'>]
export type Tables<
DefaultSchemaTableNameOrOptions extends
| keyof (DefaultSchema['Tables'] & DefaultSchema['Views'])
| { schema: keyof DatabaseWithoutInternals },
TableName extends DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof (DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions['schema']]['Tables'] &
DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions['schema']]['Views'])
: never = never,
> = DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? (DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions['schema']]['Tables'] &
DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions['schema']]['Views'])[TableName] extends {
Row: infer R
}
? R
: never
: DefaultSchemaTableNameOrOptions extends keyof (DefaultSchema['Tables'] &
DefaultSchema['Views'])
? (DefaultSchema['Tables'] &
DefaultSchema['Views'])[DefaultSchemaTableNameOrOptions] extends {
Row: infer R
}
? R
: never
: never
export type TablesInsert<
DefaultSchemaTableNameOrOptions extends
| keyof DefaultSchema['Tables']
| { schema: keyof DatabaseWithoutInternals },
TableName extends DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions['schema']]['Tables']
: never = never,
> = DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions['schema']]['Tables'][TableName] extends {
Insert: infer I
}
? I
: never
: DefaultSchemaTableNameOrOptions extends keyof DefaultSchema['Tables']
? DefaultSchema['Tables'][DefaultSchemaTableNameOrOptions] extends {
Insert: infer I
}
? I
: never
: never
export type TablesUpdate<
DefaultSchemaTableNameOrOptions extends
| keyof DefaultSchema['Tables']
| { schema: keyof DatabaseWithoutInternals },
TableName extends DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions['schema']]['Tables']
: never = never,
> = DefaultSchemaTableNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? DatabaseWithoutInternals[DefaultSchemaTableNameOrOptions['schema']]['Tables'][TableName] extends {
Update: infer U
}
? U
: never
: DefaultSchemaTableNameOrOptions extends keyof DefaultSchema['Tables']
? DefaultSchema['Tables'][DefaultSchemaTableNameOrOptions] extends {
Update: infer U
}
? U
: never
: never
export type Enums<
DefaultSchemaEnumNameOrOptions extends
| keyof DefaultSchema['Enums']
| { schema: keyof DatabaseWithoutInternals },
EnumName extends DefaultSchemaEnumNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof DatabaseWithoutInternals[DefaultSchemaEnumNameOrOptions['schema']]['Enums']
: never = never,
> = DefaultSchemaEnumNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? DatabaseWithoutInternals[DefaultSchemaEnumNameOrOptions['schema']]['Enums'][EnumName]
: DefaultSchemaEnumNameOrOptions extends keyof DefaultSchema['Enums']
? DefaultSchema['Enums'][DefaultSchemaEnumNameOrOptions]
: never
export type CompositeTypes<
PublicCompositeTypeNameOrOptions extends
| keyof DefaultSchema['CompositeTypes']
| { schema: keyof DatabaseWithoutInternals },
CompositeTypeName extends PublicCompositeTypeNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? keyof DatabaseWithoutInternals[PublicCompositeTypeNameOrOptions['schema']]['CompositeTypes']
: never = never,
> = PublicCompositeTypeNameOrOptions extends {
schema: keyof DatabaseWithoutInternals
}
? DatabaseWithoutInternals[PublicCompositeTypeNameOrOptions['schema']]['CompositeTypes'][CompositeTypeName]
: PublicCompositeTypeNameOrOptions extends keyof DefaultSchema['CompositeTypes']
? DefaultSchema['CompositeTypes'][PublicCompositeTypeNameOrOptions]
: never
export const Constants = {
public: {
Enums: {
platform_role: ['owner', 'admin', 'moderator', 'support'],
},
},
} as const
+23
View File
@@ -0,0 +1,23 @@
export {
createBrowserClient,
type FaunosteoClient,
type SupabaseConnection,
} from './client'
export type {
Database,
Enums,
Json,
Tables,
TablesInsert,
TablesUpdate,
} from './database.types'
export { Constants } from './database.types'
import type { Enums, Tables } from './database.types'
/** Row of public.profiles. */
export type Profile = Tables<'profiles'>
/** Row of public.profile_roles. */
export type ProfileRole = Tables<'profile_roles'>
/** owner | admin | moderator | support. Not a professional status. */
export type PlatformRole = Enums<'platform_role'>
+21
View File
@@ -0,0 +1,21 @@
import { createBrowserClient, Constants, type PlatformRole } from '../src'
describe('createBrowserClient', () => {
it('builds a typed client bound to the given project URL', () => {
const client = createBrowserClient({
url: 'http://127.0.0.1:54321',
anonKey: 'anon-key-placeholder',
})
expect(typeof client.from).toBe('function')
expect(client.auth).toBeDefined()
// supabase-js keeps the resolved REST URL on the client instance.
expect(
String((client as unknown as { supabaseUrl: string }).supabaseUrl),
).toContain('127.0.0.1:54321')
})
it('exposes the platform roles as runtime constants', () => {
const roles: readonly PlatformRole[] = Constants.public.Enums.platform_role
expect(roles).toEqual(['owner', 'admin', 'moderator', 'support'])
})
})
+83
View File
@@ -0,0 +1,83 @@
/**
* PGlite harness: a real PostgreSQL (WASM) that applies the Supabase shim,
* then every migration under supabase/migrations, in filename order.
* Lets the pgTAP suite and the schema checks run without Docker. The same
* SQL runs unchanged under `supabase test db` on the real stack.
*/
import { readdir, readFile } from 'node:fs/promises'
import { resolve, join } from 'node:path'
import { fileURLToPath } from 'node:url'
import { PGlite } from '@electric-sql/pglite'
import { pgtap } from '@electric-sql/pglite/pgtap'
const here = fileURLToPath(new URL('.', import.meta.url))
export const repoRoot = resolve(here, '../../../..')
export const supabaseDir = join(repoRoot, 'supabase')
export const migrationsDir = join(supabaseDir, 'migrations')
export const pgTapTestsDir = join(supabaseDir, 'tests')
async function listSqlFiles(dir: string): Promise<string[]> {
const entries = await readdir(dir)
return entries.filter((f) => f.endsWith('.sql')).sort()
}
export async function listMigrations(): Promise<string[]> {
return listSqlFiles(migrationsDir)
}
export async function listPgTapTests(): Promise<string[]> {
return listSqlFiles(pgTapTestsDir)
}
/** Boots PGlite, installs the shim and applies all migrations. */
export async function createMigratedDatabase(): Promise<PGlite> {
const db = await PGlite.create({ extensions: { pgtap } })
await db.exec(await readFile(join(here, 'supabase-shim.sql'), 'utf8'))
// Same placement as `supabase test db`: pgTAP lives in extensions, out of public.
await db.exec('create extension if not exists pgtap with schema extensions;')
await db.exec('set search_path to public, extensions;')
for (const file of await listMigrations()) {
await db.exec(await readFile(join(migrationsDir, file), 'utf8'))
}
return db
}
export interface TapReport {
lines: string[]
failures: string[]
}
function collectTapLines(results: Array<{ rows: unknown[] }>): string[] {
const lines: string[] = []
for (const result of results) {
for (const row of result.rows) {
const values = Object.values(row as Record<string, unknown>)
for (const value of values) {
if (typeof value === 'string') lines.push(...value.split('\n'))
}
}
}
return lines
}
/**
* Runs one pgTAP file (which must wrap itself in begin/rollback) and reports
* every `not ok` line plus plan mismatches announced by finish().
*/
export async function runPgTapFile(
db: PGlite,
file: string,
): Promise<TapReport> {
const sql = await readFile(join(pgTapTestsDir, file), 'utf8')
let lines: string[]
try {
lines = collectTapLines(await db.exec(sql))
} finally {
// A failing statement leaves the transaction aborted: always clean up.
await db.exec('rollback;').catch(() => undefined)
}
const failures = lines.filter(
(line) => /^not ok\b/.test(line) || /^# Looks like/.test(line),
)
return { lines, failures }
}
+32
View File
@@ -0,0 +1,32 @@
/**
* Runs every pgTAP file under supabase/tests against a migrated PGlite
* database. One vitest case per SQL file: the failing TAP lines are the
* assertion message, so a red test names the exact pgTAP check.
*/
import type { PGlite } from '@electric-sql/pglite'
import { createMigratedDatabase, listPgTapTests, runPgTapFile } from './harness'
const files = await listPgTapTests()
describe('pgTAP suite (supabase/tests) on PGlite', () => {
let db: PGlite
beforeAll(async () => {
db = await createMigratedDatabase()
})
afterAll(async () => {
await db?.close()
})
it('finds at least one pgTAP file', () => {
expect(files.length).toBeGreaterThan(0)
})
it.each(files)('%s passes', async (file) => {
const report = await runPgTapFile(db, file)
const okCount = report.lines.filter((l) => /^ok\b/.test(l)).length
expect(report.failures, report.lines.join('\n')).toEqual([])
expect(okCount).toBeGreaterThan(0)
})
})
@@ -0,0 +1,179 @@
/**
* database.types.ts must describe the migrated schema: same tables, same
* columns, same enum labels, same RPC names and arguments. The column map
* below is checked twice: by the compiler (every listed name exists in the
* type, and the type has no column missing from the list) and at runtime
* against information_schema in PGlite.
*
* Also pins two invariants for every future table in public: RLS enabled, and
* no `using (true)` policy for authenticated.
*/
import type { PGlite } from '@electric-sql/pglite'
import { Constants, type Database } from '../../src/database.types'
import { createMigratedDatabase } from './harness'
type Tables = Database['public']['Tables']
type Functions = Database['public']['Functions']
type ColumnMap = {
readonly [T in keyof Tables]: readonly (keyof Tables[T]['Row'] & string)[]
}
const expectedColumns = {
profile_roles: [
'granted_at',
'granted_by',
'id',
'revoke_reason',
'revoked_at',
'revoked_by',
'role',
'user_id',
],
profiles: [
'active',
'created_at',
'display_name',
'first_name',
'id',
'last_name',
'locale',
'phone',
'phone_verified_at',
'timezone',
'updated_at',
],
} as const satisfies ColumnMap
// Compile-time: a column present in the type but absent from the list is an error.
type MissingColumns = {
[T in keyof Tables]: Exclude<
keyof Tables[T]['Row'],
(typeof expectedColumns)[T][number]
>
}[keyof Tables]
const noMissingColumn: MissingColumns extends never ? true : never = true
type FunctionArgs = {
readonly [F in keyof Functions]: readonly (keyof Functions[F]['Args'] &
string)[]
}
const expectedFunctionArgs = {
grant_platform_role: ['role', 'target_user_id'],
revoke_platform_role: ['reason', 'role', 'target_user_id'],
} as const satisfies FunctionArgs
type MissingArgs = {
[F in keyof Functions]: Exclude<
keyof Functions[F]['Args'],
(typeof expectedFunctionArgs)[F][number]
>
}[keyof Functions]
const noMissingArg: MissingArgs extends never ? true : never = true
interface ColumnRow {
table_name: string
column_name: string
}
interface NameRow {
name: string
}
interface FunctionRow {
name: string
args: string[]
}
interface PolicyRow {
tablename: string
policyname: string
}
describe('database.types.ts matches the migrated schema', () => {
let db: PGlite
beforeAll(async () => {
db = await createMigratedDatabase()
})
afterAll(async () => {
await db?.close()
})
it('has the compile-time exhaustiveness witnesses', () => {
expect(noMissingColumn).toBe(true)
expect(noMissingArg).toBe(true)
})
it('lists exactly the public tables and their columns', async () => {
const { rows } = await db.query<ColumnRow>(
`select table_name, column_name
from information_schema.columns
where table_schema = 'public'
order by table_name, column_name`,
)
const actual: Record<string, string[]> = {}
for (const row of rows)
(actual[row.table_name] ??= []).push(row.column_name)
const expected = Object.fromEntries(
Object.entries(expectedColumns).map(([table, cols]) => [
table,
[...cols].sort(),
]),
)
expect(actual).toEqual(expected)
})
it('lists the enum labels in order', async () => {
const { rows } = await db.query<NameRow>(
`select e.enumlabel as name
from pg_enum e join pg_type t on t.oid = e.enumtypid
join pg_namespace n on n.oid = t.typnamespace
where n.nspname = 'public' and t.typname = 'platform_role'
order by e.enumsortorder`,
)
expect(rows.map((r) => r.name)).toEqual([
...Constants.public.Enums.platform_role,
])
})
it('lists exactly the public functions and their argument names', async () => {
const { rows } = await db.query<FunctionRow>(
`select p.proname as name, coalesce(p.proargnames, '{}') as args
from pg_proc p join pg_namespace n on n.oid = p.pronamespace
where n.nspname = 'public' and p.prokind = 'f'
and not exists (
select 1 from pg_depend d where d.objid = p.oid and d.deptype = 'e'
)
order by p.proname`,
)
const actual = Object.fromEntries(
rows.map((r) => [r.name, [...r.args].sort()]),
)
const expected = Object.fromEntries(
Object.entries(expectedFunctionArgs).map(([fn, args]) => [
fn,
[...args].sort(),
]),
)
expect(actual).toEqual(expected)
})
it('keeps RLS enabled on every public table', async () => {
const { rows } = await db.query<NameRow>(
`select c.relname as name
from pg_class c join pg_namespace n on n.oid = c.relnamespace
where n.nspname = 'public' and c.relkind = 'r' and not c.relrowsecurity`,
)
expect(rows).toEqual([])
})
it('has no unconditional policy for API roles', async () => {
const { rows } = await db.query<PolicyRow>(
`select tablename, policyname
from pg_policies
where schemaname = 'public'
and (qual = 'true' or with_check = 'true')
and roles && array['authenticated', 'anon']::name[]`,
)
expect(rows).toEqual([])
})
})
@@ -0,0 +1,75 @@
-- Minimal stand-in for the Supabase base schema, applied to a bare PGlite
-- database before the project migrations. Mirrors what the hosted/local stack
-- provides: API roles, auth schema with users table + JWT claim helpers, and
-- the permissive default privileges on public (ALL to the API roles), so a
-- migration that forgets to revoke is caught by the tests.
-- Test-only file: never applied to a real Supabase database.
create role anon nologin noinherit;
create role authenticated nologin noinherit;
create role service_role nologin noinherit bypassrls;
create schema auth;
create schema extensions;
create table auth.users (
instance_id uuid,
id uuid primary key default gen_random_uuid(),
aud varchar(255),
role varchar(255),
email varchar(255),
encrypted_password varchar(255),
email_confirmed_at timestamptz,
raw_app_meta_data jsonb,
raw_user_meta_data jsonb,
created_at timestamptz default now(),
updated_at timestamptz default now()
);
create or replace function auth.uid()
returns uuid
language sql
stable
as $$
select nullif(
coalesce(
current_setting('request.jwt.claim.sub', true),
(nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'sub')
),
''
)::uuid
$$;
create or replace function auth.role()
returns text
language sql
stable
as $$
select nullif(
coalesce(
current_setting('request.jwt.claim.role', true),
(nullif(current_setting('request.jwt.claims', true), '')::jsonb ->> 'role')
),
''
)::text
$$;
create or replace function auth.jwt()
returns jsonb
language sql
stable
as $$
select coalesce(
nullif(current_setting('request.jwt.claim', true), ''),
nullif(current_setting('request.jwt.claims', true), '')
)::jsonb
$$;
grant usage on schema auth to anon, authenticated, service_role;
grant execute on function auth.uid(), auth.role(), auth.jwt() to anon, authenticated, service_role;
grant usage on schema public to anon, authenticated, service_role;
grant usage on schema extensions to anon, authenticated, service_role;
alter default privileges in schema public grant all on tables to anon, authenticated, service_role;
alter default privileges in schema public grant all on functions to anon, authenticated, service_role;
alter default privileges in schema public grant all on sequences to anon, authenticated, service_role;
+21
View File
@@ -0,0 +1,21 @@
{
"compilerOptions": {
"target": "ES2022",
"lib": ["ES2022", "DOM"],
"module": "ESNext",
"moduleResolution": "bundler",
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
"noImplicitReturns": true,
"skipLibCheck": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"isolatedModules": true,
"types": ["node", "vitest/globals"],
"noEmit": true
},
"include": ["src", "tests"],
"exclude": ["node_modules"]
}
+12
View File
@@ -0,0 +1,12 @@
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
environment: 'node',
globals: true,
include: ['tests/**/*.test.ts'],
// PGlite boots a WASM Postgres per file: give it room on slow CI runners.
testTimeout: 60_000,
hookTimeout: 120_000,
},
})
+237
View File
@@ -14,9 +14,15 @@ importers:
prettier:
specifier: ^3.4.2
version: 3.8.3
supabase:
specifier: ^2.100.0
version: 2.120.0
apps/app:
dependencies:
'@faunosteo/supabase':
specifier: workspace:*
version: link:../../packages/supabase
motion:
specifier: ^11.11.17
version: 11.18.2(react-dom@19.2.6(react@19.2.6))(react@19.2.6)
@@ -91,6 +97,34 @@ importers:
specifier: ^3.2.7
version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0)
packages/supabase:
dependencies:
'@supabase/supabase-js':
specifier: ^2.100.0
version: 2.117.3
devDependencies:
'@electric-sql/pglite':
specifier: ^0.3.0
version: 0.3.16
'@types/node':
specifier: ^20.19.41
version: 20.19.41
eslint:
specifier: ^9.17.0
version: 9.39.4(jiti@2.7.0)
globals:
specifier: ^15.14.0
version: 15.15.0
typescript:
specifier: ^5.7.2
version: 5.9.3
typescript-eslint:
specifier: ^8.19.0
version: 8.59.3(eslint@9.39.4(jiti@2.7.0))(typescript@5.9.3)
vitest:
specifier: ^3.2.7
version: 3.2.7(@types/node@20.19.41)(happy-dom@20.10.6)(jiti@2.7.0)(lightningcss@1.32.0)
packages:
'@adobe/css-tools@4.4.4':
@@ -108,6 +142,15 @@ packages:
resolution: {integrity: sha512-JiDShH45zKHWyGe4ZNVRrCjBz8Nh9TMmZG1kh4QTK8hCBTWBi8Da+i7s1fJw7/lYpM4ccepSNfqzZ/QvABBi5g==}
engines: {node: '>=6.9.0'}
'@ecies/ciphers@0.2.6':
resolution: {integrity: sha512-patgsRPKGkhhoBjETV4XxD0En4ui5fbX0hzayqI3M8tvNMGUoUvmyYAIWwlxBc1KX5cturfqByYdj5bYGRpN9g==}
engines: {bun: '>=1', deno: '>=2.7.10', node: '>=16'}
peerDependencies:
'@noble/ciphers': ^1.0.0
'@electric-sql/pglite@0.3.16':
resolution: {integrity: sha512-mZkZfOd9OqTMHsK+1cje8OSzfAQcpD7JmILXTl5ahdempjUDdmg4euf1biDex5/LfQIDJ3gvCu6qDgdnDxfJmA==}
'@esbuild/aix-ppc64@0.28.1':
resolution: {integrity: sha512-Svl7tq8k/08+p6CXPpRjQ1fKX+1odH/BQbb48fV6fj3CWHhsoIOoY87w1oHXm0qEpkIK3ZfVgp0hed3XBXzXMQ==}
engines: {node: '>=18'}
@@ -338,6 +381,18 @@ packages:
'@jridgewell/trace-mapping@0.3.31':
resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}
'@noble/ciphers@1.3.0':
resolution: {integrity: sha512-2I0gnIVPtfnMw9ee9h1dJG7tp81+8Ob3OJb3Mv37rx5L40/b0i7djjCVvGOVqc9AEIQyvyu1i6ypKdFw8R8gQw==}
engines: {node: ^14.21.3 || >=16}
'@noble/curves@1.9.7':
resolution: {integrity: sha512-gbKGcRUYIjA3/zCCNaWDciTMFI0dCkvou3TL8Zmy5Nc7sJ47a0jtOeZoTaMxkuqRo9cRhjOdZJXegxYE5FN/xw==}
engines: {node: ^14.21.3 || >=16}
'@noble/hashes@1.8.0':
resolution: {integrity: sha512-jCs9ldd7NwzpgXDIf6P3+NrHh9/sD6CQdxHyjQI+h/6rDNo88ypBxxz45UDuZHz9r3tNz7N/VInSVoVdtXEI4A==}
engines: {node: ^14.21.3 || >=16}
'@pdf-lib/standard-fonts@1.0.0':
resolution: {integrity: sha512-hU30BK9IUN/su0Mn9VdlVKsWBS6GyhVfqjwl1FjZN4TxP6cCw0jP2w7V3Hf5uX7M0AZJ16vey9yE0ny7Sa59ZA==}
@@ -472,6 +527,78 @@ packages:
cpu: [x64]
os: [win32]
'@supabase/auth-js@2.117.3':
resolution: {integrity: sha512-XOZV+jllcU2Hzij8SwgM78zl0lOEr6BTjzi2MYkBb39nOAQzb5AelGpMUvVj7lwGSB11JmpAs/FEQroAyFzWEA==}
engines: {node: '>=22.0.0'}
'@supabase/cli-darwin-arm64@2.120.0':
resolution: {integrity: sha512-GXjW2+J4dGYjbZW0oeDs9y8+Eo/AloRYkbc7LpZmKagc1NYVPzQyviSHZ8LzidCXGlNF3Gds3k8UetjTQQmXbQ==}
cpu: [arm64]
os: [darwin]
'@supabase/cli-darwin-x64@2.120.0':
resolution: {integrity: sha512-o6ISS9smQnNfpws2nqs3e9lxA0UTsWGI9LAvz2zMymRm11Iy8vZIeOXHV8BbGQWtqxLgfiHHCVvBLE9/41AKQA==}
cpu: [x64]
os: [darwin]
'@supabase/cli-linux-arm64-musl@2.120.0':
resolution: {integrity: sha512-+4IwiBpGOQgLFeEG6RImxSUrMHo+LDsFNGJ4WLoLBOozFaippoz5J6CnNpVSTeJj9QaOX3G9iVsL/wYF6P1Cxw==}
cpu: [arm64]
os: [linux]
'@supabase/cli-linux-arm64@2.120.0':
resolution: {integrity: sha512-pmR61xpBmzUc79gkh3sE42KtBkludBXex1TIQTVY6jkTjs2+JhJYNKxR7udeaFgxFpiV+zTeAyqJBYXLibxQJw==}
cpu: [arm64]
os: [linux]
'@supabase/cli-linux-x64-musl@2.120.0':
resolution: {integrity: sha512-YIrqu1+hBiLwYIk1HKesrfIm2ycQIsOfN5VGV3r/okQx8JyWl9Jrw7emKVS/F+1afe+1MqKEBP70B0PbuvX+jQ==}
cpu: [x64]
os: [linux]
'@supabase/cli-linux-x64@2.120.0':
resolution: {integrity: sha512-IWJ0yFefhX/69ofcgJfN8MyOC9TtCG4SLrlMCvXjH3vZXxnRkiVNggxQqUCIhshS9Afa+q17DRbQen7/IZTL4A==}
cpu: [x64]
os: [linux]
'@supabase/cli-windows-arm64@2.120.0':
resolution: {integrity: sha512-U+IDegKWC4xXxk7aCRUUy2ZTJ4bwwrcVlnzG1VJqC7nB7SLgMiyUMyvuo1tB+Xt8hHf0hkuViNtohnXPdZHCIQ==}
cpu: [arm64]
os: [win32]
'@supabase/cli-windows-x64@2.120.0':
resolution: {integrity: sha512-y96p4JdUuKygzUDCRo1T8yEiLbyWIiL/4Qdnmgu/X84WJOZmji/TlW5ThqDllsQuGWbkgovy+6LLqWKHk330XQ==}
cpu: [x64]
os: [win32]
'@supabase/functions-js@2.117.3':
resolution: {integrity: sha512-6GuizbP4N5xWaxEVUsI+UQpJdmMmn0t3sYNpObo9gCAldvM22gFjnYzRVmkHxp5ylU21azEYmiWVwk9iDgCMkQ==}
engines: {node: '>=22.0.0'}
'@supabase/phoenix@0.4.5':
resolution: {integrity: sha512-aAn9H9ovVyeApKy11OWOrrOGq8DV68yWeH4ud2lN9fzn4aO8Zb5GLL9m1pUg9nLqIcT+ZDfAcsZe0E/nqdv2lw==}
'@supabase/postgrest-js@2.117.3':
resolution: {integrity: sha512-NpyTgullu6tw11ojYKTdZg9HannZ4mu4FUlhc9V5zDXOVllUJzEmuyLM+WWoYF0BurfrRvarimpm3SR8P0Gzfw==}
engines: {node: '>=22.0.0'}
'@supabase/realtime-js@2.117.3':
resolution: {integrity: sha512-4W4ISbreRygNXbhwqxeqyuRul8RPx+SF+Hp2IT8wctebQEHSVCULfKatiRiEhmasfoXvYm2AHV4XFsOxhoousA==}
engines: {node: '>=22.0.0'}
'@supabase/storage-js@2.117.3':
resolution: {integrity: sha512-QhUxFC33Crlw6WDeA4hLADdi1PzjI3c4UJs7ivWHHEnU7ulmCWEZSDaRCuIfmsjUwbHYaIfRNFQNsm+IsGYS6w==}
engines: {node: '>=22.0.0'}
'@supabase/supabase-js@2.117.3':
resolution: {integrity: sha512-K+f8PimXDunPWQ63CKRXaF5pbVPJxmfw5ryAnh0s9S9PkwcuqBjiSpIaqpF7KLDljeYwXIL85ST8QxaO0+XuvA==}
engines: {node: '>=22.0.0'}
peerDependencies:
'@opentelemetry/api': '>=1.0.0'
peerDependenciesMeta:
'@opentelemetry/api':
optional: true
'@swc/core-darwin-arm64@1.15.33':
resolution: {integrity: sha512-N+L0uXhuO7FIfzqwgxmzv0zIpV0qEp8wPX3QQs2p4atjMoywup2JTeDlXPw+z9pWJGCae3JjM+tZ6myclI+2gA==}
engines: {node: '>=10'}
@@ -1013,6 +1140,10 @@ packages:
resolution: {integrity: sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==}
engines: {node: '>= 0.4'}
eciesjs@0.5.0:
resolution: {integrity: sha512-s0J9SEVYAEPg7J63GFMApLYzPH9VNIQIyC6s15JpnqVc0TqcKWdbgFlnAweEBRyMmko2dcs2sfC83Hj4J43tuA==}
engines: {bun: '>=1', deno: '>=2.7.10', node: '>=16'}
enhanced-resolve@5.21.3:
resolution: {integrity: sha512-QyL119InA+XXEkNLNTPCXPugSvOfhwv0JOlGNzvxs0hZaiHLNvXSpudUWsOlsXGWJh8G6ckCScEkVHfX3kw/2Q==}
engines: {node: '>=10.13.0'}
@@ -1267,6 +1398,10 @@ packages:
resolution: {integrity: sha512-ej4AhfhfL2Q2zpMmLo7U1Uv9+PyhIZpgQLGT1F9miIGmiCJIoCgSmczFdrc97mWT4kVY72KA+WnnhJ5pghSvSg==}
engines: {node: '>= 0.4'}
iceberg-js@0.8.1:
resolution: {integrity: sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==}
engines: {node: '>=20.0.0'}
ignore@5.3.2:
resolution: {integrity: sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g==}
engines: {node: '>= 4'}
@@ -1401,6 +1536,9 @@ packages:
resolution: {integrity: sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==}
hasBin: true
jose@6.2.12:
resolution: {integrity: sha512-9NiFmJEex0sy2Dk58j2UGBSHgUs2ypF9eZSu4L6vjOX3Dp96Sw1F3uL+H+D1sx02jZZdzUT0HgvCy59CuvXcWw==}
js-tokens@4.0.0:
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
@@ -1852,6 +1990,10 @@ packages:
strip-literal@3.1.0:
resolution: {integrity: sha512-8r3mkIM/2+PpjHoOtiAW8Rg3jJLHaV7xPwG+YRGrv6FP0wwk/toTpATxWYOW0BKdWwl82VT2tFYi5DlROa0Mxg==}
supabase@2.120.0:
resolution: {integrity: sha512-NF8ueHsOZMbyiFJARKbiZy9AhNtj5E5R49P+cVqlv2u/T2JpMtsvp29YgPgrIWkVUjsfhJseTmKEdckatSeWZQ==}
hasBin: true
supports-color@7.2.0:
resolution: {integrity: sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw==}
engines: {node: '>=8'}
@@ -2101,6 +2243,12 @@ snapshots:
'@babel/runtime@7.29.2': {}
'@ecies/ciphers@0.2.6(@noble/ciphers@1.3.0)':
dependencies:
'@noble/ciphers': 1.3.0
'@electric-sql/pglite@0.3.16': {}
'@esbuild/aix-ppc64@0.28.1':
optional: true
@@ -2260,6 +2408,14 @@ snapshots:
'@jridgewell/resolve-uri': 3.1.2
'@jridgewell/sourcemap-codec': 1.5.5
'@noble/ciphers@1.3.0': {}
'@noble/curves@1.9.7':
dependencies:
'@noble/hashes': 1.8.0
'@noble/hashes@1.8.0': {}
'@pdf-lib/standard-fonts@1.0.0':
dependencies:
pako: 1.0.11
@@ -2345,6 +2501,62 @@ snapshots:
'@rollup/rollup-win32-x64-msvc@4.60.4':
optional: true
'@supabase/auth-js@2.117.3':
dependencies:
tslib: 2.8.1
'@supabase/cli-darwin-arm64@2.120.0':
optional: true
'@supabase/cli-darwin-x64@2.120.0':
optional: true
'@supabase/cli-linux-arm64-musl@2.120.0':
optional: true
'@supabase/cli-linux-arm64@2.120.0':
optional: true
'@supabase/cli-linux-x64-musl@2.120.0':
optional: true
'@supabase/cli-linux-x64@2.120.0':
optional: true
'@supabase/cli-windows-arm64@2.120.0':
optional: true
'@supabase/cli-windows-x64@2.120.0':
optional: true
'@supabase/functions-js@2.117.3':
dependencies:
tslib: 2.8.1
'@supabase/phoenix@0.4.5': {}
'@supabase/postgrest-js@2.117.3':
dependencies:
tslib: 2.8.1
'@supabase/realtime-js@2.117.3':
dependencies:
'@supabase/phoenix': 0.4.5
tslib: 2.8.1
'@supabase/storage-js@2.117.3':
dependencies:
iceberg-js: 0.8.1
tslib: 2.8.1
'@supabase/supabase-js@2.117.3':
dependencies:
'@supabase/auth-js': 2.117.3
'@supabase/functions-js': 2.117.3
'@supabase/postgrest-js': 2.117.3
'@supabase/realtime-js': 2.117.3
'@supabase/storage-js': 2.117.3
'@swc/core-darwin-arm64@1.15.33':
optional: true
@@ -2904,6 +3116,13 @@ snapshots:
es-errors: 1.3.0
gopd: 1.2.0
eciesjs@0.5.0:
dependencies:
'@ecies/ciphers': 0.2.6(@noble/ciphers@1.3.0)
'@noble/ciphers': 1.3.0
'@noble/curves': 1.9.7
'@noble/hashes': 1.8.0
enhanced-resolve@5.21.3:
dependencies:
graceful-fs: 4.2.11
@@ -3280,6 +3499,8 @@ snapshots:
dependencies:
function-bind: 1.1.2
iceberg-js@0.8.1: {}
ignore@5.3.2: {}
ignore@7.0.5: {}
@@ -3420,6 +3641,8 @@ snapshots:
jiti@2.7.0: {}
jose@6.2.12: {}
js-tokens@4.0.0: {}
js-tokens@9.0.1: {}
@@ -3912,6 +4135,20 @@ snapshots:
dependencies:
js-tokens: 9.0.1
supabase@2.120.0:
dependencies:
eciesjs: 0.5.0
jose: 6.2.12
optionalDependencies:
'@supabase/cli-darwin-arm64': 2.120.0
'@supabase/cli-darwin-x64': 2.120.0
'@supabase/cli-linux-arm64': 2.120.0
'@supabase/cli-linux-arm64-musl': 2.120.0
'@supabase/cli-linux-x64': 2.120.0
'@supabase/cli-linux-x64-musl': 2.120.0
'@supabase/cli-windows-arm64': 2.120.0
'@supabase/cli-windows-x64': 2.120.0
supports-color@7.2.0:
dependencies:
has-flag: 4.0.0
+2
View File
@@ -7,3 +7,5 @@ packages:
onlyBuiltDependencies:
- '@swc/core'
- esbuild
# Supabase CLI npm wrapper downloads its binary in a postinstall script.
- supabase
+1
View File
@@ -0,0 +1 @@
v2.120.0
+118
View File
@@ -0,0 +1,118 @@
# Supabase CLI configuration (local stack + self-hosted parity).
# Generated from `supabase init` (CLI 2.120) and trimmed to what the project
# needs. Full reference: https://supabase.com/docs/guides/local-development/cli/config
project_id = "faunosteo"
[api]
enabled = true
port = 54321
# Only public is exposed through PostgREST. private and audit stay internal
# (docs/development/BACKEND_ARCHITECTURE.md §3).
schemas = ["public"]
extra_search_path = ["public", "extensions"]
max_rows = 1000
[api.tls]
enabled = false
[db]
port = 54322
shadow_port = 54320
health_timeout = "2m"
# PostgreSQL 17, same major as the PGlite harness in packages/supabase.
major_version = 17
[db.pooler]
enabled = false
[db.migrations]
enabled = true
schema_paths = []
[db.seed]
enabled = true
# Local development data only (dev accounts + first owner). Never run in prod.
sql_paths = ["./seed.sql"]
[realtime]
# Not used before the cloud-reports step.
enabled = false
[studio]
enabled = true
port = 54323
api_url = "http://127.0.0.1"
# Local mail catcher: confirmation and OTP mails land at http://127.0.0.1:54324
[local_smtp]
enabled = true
port = 54324
[storage]
enabled = true
file_size_limit = "50MiB"
[storage.s3_protocol]
enabled = false
[storage.analytics]
enabled = false
[storage.vector]
enabled = false
[auth]
enabled = true
# Vite dev server of apps/app
site_url = "http://127.0.0.1:5173"
additional_redirect_urls = ["http://127.0.0.1:5173", "http://localhost:5173"]
jwt_expiry = 3600
enable_refresh_token_rotation = true
refresh_token_reuse_interval = 10
enable_signup = true
enable_anonymous_sign_ins = false
enable_manual_linking = false
# Security baseline (business architecture §30): strong password policy.
minimum_password_length = 12
password_requirements = "lower_upper_letters_digits"
[auth.rate_limit]
email_sent = 2
sms_sent = 30
anonymous_users = 30
token_refresh = 150
sign_in_sign_ups = 30
token_verifications = 30
[auth.email]
enable_signup = true
double_confirm_changes = true
# Email verification is mandatory before professional features (§30).
enable_confirmations = true
secure_password_change = true
max_frequency = "1m0s"
otp_length = 6
otp_expiry = 3600
[auth.sms]
# SMS provider deferred (OPEN_QUESTIONS Q7).
enable_signup = false
enable_confirmations = false
[auth.mfa]
max_enrolled_factors = 10
[auth.mfa.totp]
# Enrolment opens with the identity step (mandatory for platform staff).
enroll_enabled = false
verify_enabled = false
[edge_runtime]
# No Edge Function before the files/webhooks steps; keeps the local stack light.
enabled = false
[analytics]
enabled = false
[experimental.pgdelta]
enabled = false
@@ -0,0 +1,136 @@
-- Foundation: schemas, shared triggers, append-only audit log.
-- Conventions: docs/development/BACKEND_ARCHITECTURE.md §3, §7; business architecture §29.
-- Forward-only. Never edit after it has been applied: write a new migration.
-- ---------------------------------------------------------------------------
-- Schemas
-- ---------------------------------------------------------------------------
-- private: security-definer helpers and internal functions. Not exposed to
-- PostgREST (config.toml api.schemas lists public only).
create schema if not exists private;
-- audit: append-only event log, read by platform admins only.
create schema if not exists audit;
revoke all on schema private from public;
revoke all on schema audit from public;
-- Policies evaluated for API roles call private.* helpers by qualified name,
-- which needs USAGE on the schema. EXECUTE is granted per function below.
-- anon gets nothing: no policy for anon evaluates a helper yet.
grant usage on schema private to authenticated, service_role;
grant usage on schema audit to authenticated, service_role;
-- PostgreSQL grants EXECUTE on every new function to PUBLIC. Flip the default
-- for both schemas so a helper is callable only where a migration says so.
alter default privileges in schema private revoke execute on functions from public;
alter default privileges in schema audit revoke execute on functions from public;
-- ---------------------------------------------------------------------------
-- Shared trigger: updated_at
-- ---------------------------------------------------------------------------
create or replace function private.set_updated_at()
returns trigger
language plpgsql
set search_path = ''
as $$
begin
new.updated_at := now();
return new;
end;
$$;
comment on function private.set_updated_at() is
'BEFORE UPDATE trigger: stamps updated_at. Attach to every table that has the column.';
-- ---------------------------------------------------------------------------
-- Audit log (business architecture §29)
-- ---------------------------------------------------------------------------
create table audit.audit_logs (
id uuid primary key default gen_random_uuid(),
occurred_at timestamptz not null default now(),
-- null actor = system action (migration, worker, bootstrap).
actor_user_id uuid,
-- "<domain>.<verb>" e.g. platform_role.granted. Kept as text + CHECK: the
-- set grows with every step.
action text not null
constraint audit_logs_action_format check (action ~ '^[a-z_]+\.[a-z_]+$'),
resource_type text not null
constraint audit_logs_resource_type_format check (resource_type ~ '^[a-z_]+$'),
resource_id uuid,
organization_id uuid,
target_user_id uuid,
-- Sanitized by the caller: never report contents, passwords, tokens.
metadata jsonb not null default '{}'::jsonb
constraint audit_logs_metadata_object check (jsonb_typeof(metadata) = 'object'),
correlation_id text
);
comment on table audit.audit_logs is
'Append-only trace of sensitive operations. Insert only through private.log_event(). No FK on user ids: rows outlive accounts.';
create index audit_logs_occurred_at_idx on audit.audit_logs (occurred_at desc);
create index audit_logs_actor_idx on audit.audit_logs (actor_user_id, occurred_at desc);
create index audit_logs_target_idx on audit.audit_logs (target_user_id, occurred_at desc);
create index audit_logs_resource_idx on audit.audit_logs (resource_type, resource_id);
-- Append-only, enforced for every role including the table owner.
create or replace function audit.reject_mutation()
returns trigger
language plpgsql
set search_path = ''
as $$
begin
raise exception 'audit.audit_logs is append-only (% refused)', tg_op
using errcode = '42501';
end;
$$;
create trigger audit_logs_append_only
before update or delete on audit.audit_logs
for each row execute function audit.reject_mutation();
-- Privileges: nobody writes through the API; admins read (policy added with
-- the role helpers in the platform-roles migration).
revoke all on audit.audit_logs from public, anon, authenticated, service_role;
grant select on audit.audit_logs to authenticated, service_role;
alter table audit.audit_logs enable row level security;
create or replace function private.log_event(
p_actor_user_id uuid,
p_action text,
p_resource_type text,
p_resource_id uuid default null,
p_target_user_id uuid default null,
p_organization_id uuid default null,
p_metadata jsonb default '{}'::jsonb
)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid;
v_correlation text;
begin
-- PostgREST exposes request headers as a JSON setting; absent elsewhere.
v_correlation := nullif(current_setting('request.headers', true), '')::jsonb ->> 'x-correlation-id';
insert into audit.audit_logs (
actor_user_id, action, resource_type, resource_id,
target_user_id, organization_id, metadata, correlation_id
)
values (
p_actor_user_id, p_action, p_resource_type, p_resource_id,
p_target_user_id, p_organization_id, coalesce(p_metadata, '{}'::jsonb), v_correlation
)
returning id into v_id;
return v_id;
end;
$$;
comment on function private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb) is
'Single write path into audit.audit_logs. Called from server-side functions only; never granted to API roles.';
revoke all on function private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb) from public;
grant execute on function private.log_event(uuid, text, text, uuid, uuid, uuid, jsonb) to service_role;
@@ -0,0 +1,121 @@
-- Profiles: one row per auth.users row, created by trigger.
-- Business architecture §4.1 (profiles), §17.3 (own row only).
-- avatar_asset_id waits for the assets table (files step): added then.
create table public.profiles (
id uuid primary key references auth.users (id) on delete cascade,
display_name text not null
constraint profiles_display_name_length check (char_length(display_name) between 1 and 80),
first_name text
constraint profiles_first_name_length check (char_length(first_name) <= 80),
last_name text
constraint profiles_last_name_length check (char_length(last_name) <= 80),
-- E.164; verification is server-side (phone_verified_at is not user-writable).
phone text
constraint profiles_phone_e164 check (phone ~ '^\+[1-9][0-9]{6,14}$'),
phone_verified_at timestamptz,
locale text not null default 'fr'
constraint profiles_locale_supported check (locale in ('fr', 'en')),
timezone text not null default 'Europe/Paris'
constraint profiles_timezone_length check (char_length(timezone) between 1 and 64),
-- Platform-level switch (deactivation by staff). Not user-writable.
active boolean not null default true,
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
comment on table public.profiles is
'Account profile, id = auth.users.id. Created by trigger on auth.users; never inserted through the API.';
comment on column public.profiles.active is
'false = deactivated by platform staff; role helpers treat the account as having no platform role.';
create trigger profiles_set_updated_at
before update on public.profiles
for each row execute function private.set_updated_at();
-- A new phone number is unverified until the server verifies it again.
create or replace function private.reset_phone_verification()
returns trigger
language plpgsql
set search_path = ''
as $$
begin
if new.phone is distinct from old.phone then
new.phone_verified_at := null;
end if;
return new;
end;
$$;
create trigger profiles_reset_phone_verification
before update of phone on public.profiles
for each row execute function private.reset_phone_verification();
-- ---------------------------------------------------------------------------
-- auth.users -> profiles
-- ---------------------------------------------------------------------------
create or replace function private.handle_new_auth_user()
returns trigger
language plpgsql
security definer
set search_path = ''
as $$
declare
v_meta jsonb := coalesce(new.raw_user_meta_data, '{}'::jsonb);
v_display_name text;
v_locale text;
begin
v_display_name := left(
coalesce(
nullif(trim(v_meta ->> 'display_name'), ''),
nullif(split_part(coalesce(new.email, ''), '@', 1), ''),
'Utilisateur'
),
80
);
v_locale := case
when v_meta ->> 'locale' in ('fr', 'en') then v_meta ->> 'locale'
else 'fr'
end;
insert into public.profiles (id, display_name, locale)
values (new.id, v_display_name, v_locale)
on conflict (id) do nothing;
return new;
end;
$$;
comment on function private.handle_new_auth_user() is
'AFTER INSERT on auth.users: creates the profile row. Display name from metadata, else the email local part.';
create trigger on_auth_user_created
after insert on auth.users
for each row execute function private.handle_new_auth_user();
-- ---------------------------------------------------------------------------
-- Privileges + RLS (API roles). Supabase default privileges grant ALL to
-- anon/authenticated/service_role on new tables: start from zero instead.
-- ---------------------------------------------------------------------------
revoke all on public.profiles from public, anon, authenticated;
grant select on public.profiles to authenticated;
-- Column-level UPDATE: active and phone_verified_at stay server-only.
grant update (display_name, first_name, last_name, phone, locale, timezone)
on public.profiles to authenticated;
alter table public.profiles enable row level security;
create policy profiles_select_own
on public.profiles
for select
to authenticated
using (id = (select auth.uid()));
create policy profiles_update_own
on public.profiles
for update
to authenticated
using (id = (select auth.uid()))
with check (id = (select auth.uid()));
-- No INSERT policy (trigger only), no DELETE policy (no deletion of user data).
@@ -0,0 +1,283 @@
-- Platform roles: owner / admin / moderator / support.
-- Business architecture §2.1, §4.1 (profile_roles), §17.2 (helpers), §17.3.
--
-- Platform roles are NOT professional statuses. practitioner / student /
-- professor are outcomes of professional verification (identity step) and
-- cabinet roles live in organization_members (organizations step). Keeping
-- them out of this enum avoids a self-declared "practitioner" row ever being
-- read as a verified status.
--
-- Hierarchy for permission checks: owner ⊇ admin ⊇ moderator. support is
-- separate and inherits nothing (§17.3 "Support does not inherit moderation").
-- Writes go through the two RPCs below only; the API roles cannot insert,
-- update or delete rows. Revocation keeps the row (history), re-grant adds one.
create type public.platform_role as enum ('owner', 'admin', 'moderator', 'support');
create table public.profile_roles (
id uuid primary key default gen_random_uuid(),
user_id uuid not null references public.profiles (id) on delete cascade,
role public.platform_role not null,
granted_at timestamptz not null default now(),
-- null = system (bootstrap, migration).
granted_by uuid references public.profiles (id) on delete set null,
revoked_at timestamptz,
revoked_by uuid references public.profiles (id) on delete set null,
revoke_reason text
constraint profile_roles_revoke_reason_length check (char_length(revoke_reason) <= 500),
-- revoked_by / revoke_reason only make sense on a revoked row.
constraint profile_roles_revoke_consistent
check (revoked_at is not null or (revoked_by is null and revoke_reason is null))
);
comment on table public.profile_roles is
'Platform role grants (owner/admin/moderator/support). One active row per (user, role); revoked rows kept as history. Writes only via grant_platform_role / revoke_platform_role.';
create unique index profile_roles_active_unique
on public.profile_roles (user_id, role) where revoked_at is null;
create index profile_roles_user_active_idx
on public.profile_roles (user_id) where revoked_at is null;
-- ---------------------------------------------------------------------------
-- Helpers (security definer, read profile_roles bypassing its policies)
-- ---------------------------------------------------------------------------
create or replace function private.has_platform_role(p_user_id uuid, variadic p_roles public.platform_role[])
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select exists (
select 1
from public.profile_roles r
join public.profiles p on p.id = r.user_id
where r.user_id = p_user_id
and r.revoked_at is null
and r.role = any (p_roles)
and p.active
);
$$;
create or replace function private.is_platform_owner(p_user_id uuid)
returns boolean language sql stable security definer set search_path = ''
as $$ select private.has_platform_role(p_user_id, 'owner'); $$;
create or replace function private.is_platform_admin(p_user_id uuid)
returns boolean language sql stable security definer set search_path = ''
as $$ select private.has_platform_role(p_user_id, 'owner', 'admin'); $$;
create or replace function private.is_platform_moderator(p_user_id uuid)
returns boolean language sql stable security definer set search_path = ''
as $$ select private.has_platform_role(p_user_id, 'owner', 'admin', 'moderator'); $$;
create or replace function private.is_support(p_user_id uuid)
returns boolean language sql stable security definer set search_path = ''
as $$ select private.has_platform_role(p_user_id, 'support'); $$;
comment on function private.is_platform_admin(uuid) is 'true for owner or admin (active account).';
comment on function private.is_platform_moderator(uuid) is 'true for owner, admin or moderator (active account).';
comment on function private.is_support(uuid) is 'true for support only; support inherits nothing.';
-- Who may grant or revoke which role. owner: any role. admin: moderator, support.
create or replace function private.can_manage_platform_role(p_actor uuid, p_role public.platform_role)
returns boolean
language sql
stable
security definer
set search_path = ''
as $$
select case
when private.is_platform_owner(p_actor) then true
when private.has_platform_role(p_actor, 'admin') then p_role in ('moderator', 'support')
else false
end;
$$;
-- Policies run as the API role: they need EXECUTE on the predicates.
grant execute on function private.has_platform_role(uuid, public.platform_role[]) to authenticated;
grant execute on function private.is_platform_owner(uuid) to authenticated;
grant execute on function private.is_platform_admin(uuid) to authenticated;
grant execute on function private.is_platform_moderator(uuid) to authenticated;
grant execute on function private.is_support(uuid) to authenticated;
-- can_manage_platform_role is called from the RPCs only (owner context).
-- ---------------------------------------------------------------------------
-- Internal write path (system or RPC), audited
-- ---------------------------------------------------------------------------
create or replace function private.assign_platform_role(
p_actor uuid,
p_target uuid,
p_role public.platform_role
)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid;
begin
if not exists (select 1 from public.profiles where id = p_target) then
raise exception 'unknown user %', p_target using errcode = 'P0002';
end if;
if exists (
select 1 from public.profile_roles
where user_id = p_target and role = p_role and revoked_at is null
) then
raise exception 'role % already granted to %', p_role, p_target using errcode = '23505';
end if;
insert into public.profile_roles (user_id, role, granted_by)
values (p_target, p_role, p_actor)
returning id into v_id;
perform private.log_event(
p_actor, 'platform_role.granted', 'profile_role', v_id, p_target, null,
jsonb_build_object('role', p_role)
);
return v_id;
end;
$$;
create or replace function private.withdraw_platform_role(
p_actor uuid,
p_target uuid,
p_role public.platform_role,
p_reason text
)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
declare
v_id uuid;
begin
select id into v_id
from public.profile_roles
where user_id = p_target and role = p_role and revoked_at is null;
if v_id is null then
raise exception 'role % is not active for %', p_role, p_target using errcode = 'P0002';
end if;
-- Lock-out guard: the platform always keeps one active owner.
if p_role = 'owner' and (
select count(*) from public.profile_roles where role = 'owner' and revoked_at is null
) <= 1 then
raise exception 'cannot revoke the last platform owner' using errcode = '42501';
end if;
update public.profile_roles
set revoked_at = now(), revoked_by = p_actor, revoke_reason = p_reason
where id = v_id;
perform private.log_event(
p_actor, 'platform_role.revoked', 'profile_role', v_id, p_target, null,
jsonb_build_object('role', p_role, 'reason', p_reason)
);
return v_id;
end;
$$;
comment on function private.assign_platform_role(uuid, uuid, public.platform_role) is
'System write path. Bootstrap the first owner with p_actor = null from a privileged SQL session (docs/development/SUPABASE.md).';
-- ---------------------------------------------------------------------------
-- RPCs (authenticated callers, checked against the actor's own roles)
-- ---------------------------------------------------------------------------
create or replace function public.grant_platform_role(
target_user_id uuid,
role public.platform_role
)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
declare
v_actor uuid := auth.uid();
begin
if v_actor is null then
raise exception 'authentication required' using errcode = '42501';
end if;
if v_actor = target_user_id then
raise exception 'a user cannot change their own platform roles' using errcode = '42501';
end if;
if not private.can_manage_platform_role(v_actor, role) then
raise exception 'insufficient privileges to grant role %', role using errcode = '42501';
end if;
return private.assign_platform_role(v_actor, target_user_id, role);
end;
$$;
create or replace function public.revoke_platform_role(
target_user_id uuid,
role public.platform_role,
reason text default null
)
returns uuid
language plpgsql
security definer
set search_path = ''
as $$
declare
v_actor uuid := auth.uid();
begin
if v_actor is null then
raise exception 'authentication required' using errcode = '42501';
end if;
if v_actor = target_user_id then
raise exception 'a user cannot change their own platform roles' using errcode = '42501';
end if;
if not private.can_manage_platform_role(v_actor, role) then
raise exception 'insufficient privileges to revoke role %', role using errcode = '42501';
end if;
return private.withdraw_platform_role(v_actor, target_user_id, role, reason);
end;
$$;
comment on function public.grant_platform_role(uuid, public.platform_role) is
'Grants a platform role to another user. owner: any role; admin: moderator/support. Audited.';
comment on function public.revoke_platform_role(uuid, public.platform_role, text) is
'Revokes an active platform role of another user (same rights as grant). Keeps one owner. Audited.';
revoke all on function public.grant_platform_role(uuid, public.platform_role) from public, anon;
revoke all on function public.revoke_platform_role(uuid, public.platform_role, text) from public, anon;
grant execute on function public.grant_platform_role(uuid, public.platform_role) to authenticated, service_role;
grant execute on function public.revoke_platform_role(uuid, public.platform_role, text) to authenticated, service_role;
-- ---------------------------------------------------------------------------
-- Privileges + RLS
-- ---------------------------------------------------------------------------
revoke all on public.profile_roles from public, anon, authenticated;
grant select on public.profile_roles to authenticated;
alter table public.profile_roles enable row level security;
-- Own grants, or every grant for owners/admins. No write policy at all.
create policy profile_roles_select_own_or_admin
on public.profile_roles
for select
to authenticated
using (
user_id = (select auth.uid())
or private.is_platform_admin((select auth.uid()))
);
-- Staff read of profiles (owner/admin/support), now that the helpers exist.
create policy profiles_select_staff
on public.profiles
for select
to authenticated
using (
private.is_platform_admin((select auth.uid()))
or private.is_support((select auth.uid()))
);
-- Audit log read: owners and admins.
create policy audit_logs_select_admin
on audit.audit_logs
for select
to authenticated
using (private.is_platform_admin((select auth.uid())));
+54
View File
@@ -0,0 +1,54 @@
-- Local development seed. Applied by `supabase db reset` / `supabase start`
-- on the LOCAL stack only (config.toml [db.seed]). Never run against a shared
-- or production database: it creates accounts with a known password.
--
-- Accounts (password for all three: LocalDev-only-password-1)
-- owner@faunosteo.local platform owner (bootstrapped below)
-- alice@faunosteo.local plain user
-- bob@faunosteo.local plain user
--
-- Needs the real auth schema (auth.identities, extensions.crypt): not part of
-- the PGlite harness, which only applies migrations.
create or replace function pg_temp.seed_user(p_id uuid, p_email text, p_display_name text)
returns void
language plpgsql
as $$
begin
insert into auth.users (
instance_id, id, aud, role, email, encrypted_password, email_confirmed_at,
raw_app_meta_data, raw_user_meta_data, created_at, updated_at,
confirmation_token, recovery_token, email_change_token_new, email_change
)
values (
'00000000-0000-0000-0000-000000000000', p_id, 'authenticated', 'authenticated',
p_email, extensions.crypt('LocalDev-only-password-1', extensions.gen_salt('bf')), now(),
'{"provider":"email","providers":["email"]}'::jsonb,
jsonb_build_object('display_name', p_display_name, 'locale', 'fr'),
now(), now(), '', '', '', ''
)
on conflict (id) do nothing;
insert into auth.identities (
id, user_id, provider_id, identity_data, provider,
last_sign_in_at, created_at, updated_at
)
values (
gen_random_uuid(), p_id, p_id::text,
jsonb_build_object('sub', p_id::text, 'email', p_email, 'email_verified', true),
'email', now(), now(), now()
)
on conflict (provider_id, provider) do nothing;
end;
$$;
select pg_temp.seed_user('10000000-0000-0000-0000-000000000001', 'owner@faunosteo.local', 'Owner Local');
select pg_temp.seed_user('10000000-0000-0000-0000-00000000000a', 'alice@faunosteo.local', 'Alice Local');
select pg_temp.seed_user('10000000-0000-0000-0000-00000000000b', 'bob@faunosteo.local', 'Bob Local');
-- First platform owner (system bootstrap, audited with a null actor).
select private.assign_platform_role(null, '10000000-0000-0000-0000-000000000001', 'owner')
where not exists (
select 1 from public.profile_roles
where user_id = '10000000-0000-0000-0000-000000000001' and role = 'owner' and revoked_at is null
);
+55
View File
@@ -0,0 +1,55 @@
-- Schema contract: objects exist, RLS is on, API roles start from zero.
begin;
select plan(24);
-- Schemas
select has_schema('private', 'schema private exists');
select has_schema('audit', 'schema audit exists');
-- Tables
select has_table('public', 'profiles', 'table public.profiles exists');
select has_table('public', 'profile_roles', 'table public.profile_roles exists');
select has_table('audit', 'audit_logs', 'table audit.audit_logs exists');
-- RLS enabled everywhere (pgTAP has no helper: read pg_class)
select ok(
(select relrowsecurity from pg_class where oid = 'public.profiles'::regclass),
'RLS enabled on profiles'
);
select ok(
(select relrowsecurity from pg_class where oid = 'public.profile_roles'::regclass),
'RLS enabled on profile_roles'
);
select ok(
(select relrowsecurity from pg_class where oid = 'audit.audit_logs'::regclass),
'RLS enabled on audit_logs'
);
-- Enum
select enum_has_labels(
'public', 'platform_role',
array['owner', 'admin', 'moderator', 'support'],
'platform_role has exactly the four platform roles (no professional status)'
);
-- Functions
select has_function('private', 'log_event', 'private.log_event exists');
select has_function('private', 'is_platform_owner', array['uuid'], 'private.is_platform_owner exists');
select has_function('private', 'is_platform_admin', array['uuid'], 'private.is_platform_admin exists');
select has_function('private', 'is_platform_moderator', array['uuid'], 'private.is_platform_moderator exists');
select has_function('private', 'is_support', array['uuid'], 'private.is_support exists');
select has_function('public', 'grant_platform_role', array['uuid', 'platform_role'], 'public.grant_platform_role exists');
select has_function('public', 'revoke_platform_role', array['uuid', 'platform_role', 'text'], 'public.revoke_platform_role exists');
-- Privileges: anon has nothing, authenticated has only what RLS then filters
select ok(not has_table_privilege('anon', 'public.profiles', 'select'), 'anon cannot select profiles');
select ok(not has_table_privilege('anon', 'public.profile_roles', 'select'), 'anon cannot select profile_roles');
select ok(not has_table_privilege('authenticated', 'public.profiles', 'insert'), 'authenticated cannot insert profiles');
select ok(not has_table_privilege('authenticated', 'public.profiles', 'delete'), 'authenticated cannot delete profiles');
select ok(not has_table_privilege('authenticated', 'public.profile_roles', 'insert'), 'authenticated cannot insert profile_roles');
select ok(not has_column_privilege('authenticated', 'public.profiles', 'active', 'update'), 'authenticated cannot update profiles.active');
select ok(not has_schema_privilege('anon', 'private', 'usage'), 'anon has no usage on schema private');
select ok(not has_function_privilege('anon', 'public.grant_platform_role(uuid, public.platform_role)', 'execute'), 'anon cannot execute grant_platform_role');
select * from finish();
rollback;
+131
View File
@@ -0,0 +1,131 @@
-- profiles: trigger creation, own-row read/update, every denied path.
begin;
select plan(17);
-- Fixtures (privileged session = migration owner)
insert into auth.users (id, email, raw_user_meta_data) values
('00000000-0000-0000-0000-00000000000a', 'alice@test.local', '{"display_name":"Alice","locale":"en"}'),
('00000000-0000-0000-0000-00000000000b', 'bob@test.local', '{}'),
('00000000-0000-0000-0000-00000000000c', 'carol.long.name@test.local', '{"locale":"xx"}');
-- 1. Trigger builds the profile
select results_eq(
$$ select display_name, locale from public.profiles where id = '00000000-0000-0000-0000-00000000000a' $$,
$$ values ('Alice'::text, 'en'::text) $$,
'profile created from metadata (display_name + locale)'
);
select results_eq(
$$ select display_name, locale from public.profiles where id = '00000000-0000-0000-0000-00000000000b' $$,
$$ values ('bob'::text, 'fr'::text) $$,
'profile falls back to the email local part and locale fr'
);
select is(
(select locale from public.profiles where id = '00000000-0000-0000-0000-00000000000c'),
'fr',
'unsupported locale in metadata falls back to fr'
);
-- 2. Alice, authenticated
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
select results_eq(
$$ select id from public.profiles order by id $$,
$$ values ('00000000-0000-0000-0000-00000000000a'::uuid) $$,
'alice sees exactly her own profile'
);
select is(
(select count(*) from public.profiles where id = '00000000-0000-0000-0000-00000000000b'),
0::bigint,
'alice cannot read bob by id (no IDOR)'
);
select lives_ok(
$$ update public.profiles set display_name = 'Alice B.', timezone = 'Europe/Brussels' where id = '00000000-0000-0000-0000-00000000000a' $$,
'alice updates her own display_name and timezone'
);
select is(
(select display_name from public.profiles where id = '00000000-0000-0000-0000-00000000000a'),
'Alice B.',
'own update is visible'
);
-- Update on another row: RLS filters it out silently (0 rows)
update public.profiles set display_name = 'hacked' where id = '00000000-0000-0000-0000-00000000000b';
select throws_ok(
$$ update public.profiles set active = false where id = '00000000-0000-0000-0000-00000000000a' $$,
'42501',
null,
'alice cannot deactivate herself (column privilege)'
);
select throws_ok(
$$ update public.profiles set phone_verified_at = now() where id = '00000000-0000-0000-0000-00000000000a' $$,
'42501',
null,
'alice cannot self-verify her phone (column privilege)'
);
select throws_ok(
$$ insert into public.profiles (id, display_name) values (gen_random_uuid(), 'ghost') $$,
'42501',
null,
'alice cannot insert a profile'
);
select throws_ok(
$$ delete from public.profiles where id = '00000000-0000-0000-0000-00000000000a' $$,
'42501',
null,
'alice cannot delete her profile'
);
select throws_ok(
$$ update public.profiles set phone = '0612345678' where id = '00000000-0000-0000-0000-00000000000a' $$,
'23514',
null,
'phone must be E.164'
);
-- 3. Bob sees his row untouched
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
select is(
(select display_name from public.profiles where id = '00000000-0000-0000-0000-00000000000b'),
'bob',
'alice''s cross-row update did not touch bob'
);
-- 4. Phone change resets verification
reset role;
update public.profiles
set phone = '+33612345678', phone_verified_at = now()
where id = '00000000-0000-0000-0000-00000000000b';
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
select lives_ok(
$$ update public.profiles set phone = '+33698765432' where id = '00000000-0000-0000-0000-00000000000b' $$,
'bob changes his phone'
);
select is(
(select phone_verified_at from public.profiles where id = '00000000-0000-0000-0000-00000000000b'),
null,
'changing the phone clears phone_verified_at'
);
-- 5. Anonymous: no access at all
set local role anon;
select set_config('request.jwt.claims', '', true);
select throws_ok(
$$ select * from public.profiles $$,
'42501',
null,
'anon cannot select profiles'
);
-- 6. updated_at trigger overrides whatever the writer sends
reset role;
update public.profiles set updated_at = '2000-01-01' where id = '00000000-0000-0000-0000-00000000000a';
select is(
(select updated_at from public.profiles where id = '00000000-0000-0000-0000-00000000000a'),
now(),
'updated_at is stamped by the trigger, not by the writer'
);
select * from finish();
rollback;
+160
View File
@@ -0,0 +1,160 @@
-- Platform roles: bootstrap, delegation rules, every denied path, visibility.
begin;
select plan(28);
insert into auth.users (id, email) values
('00000000-0000-0000-0000-000000000001', 'root@test.local'),
('00000000-0000-0000-0000-00000000000a', 'alice@test.local'),
('00000000-0000-0000-0000-00000000000b', 'bob@test.local'),
('00000000-0000-0000-0000-00000000000c', 'carol@test.local');
-- 1. Nobody has a role; bootstrap the first owner from a privileged session
select ok(not private.is_platform_owner('00000000-0000-0000-0000-000000000001'), 'fresh account has no owner role');
select lives_ok(
$$ select private.assign_platform_role(null, '00000000-0000-0000-0000-000000000001', 'owner') $$,
'system bootstraps the first owner (actor null)'
);
select ok(private.is_platform_owner('00000000-0000-0000-0000-000000000001'), 'root is owner');
select ok(private.is_platform_admin('00000000-0000-0000-0000-000000000001'), 'owner counts as admin');
select ok(private.is_platform_moderator('00000000-0000-0000-0000-000000000001'), 'owner counts as moderator');
select ok(not private.is_support('00000000-0000-0000-0000-000000000001'), 'owner is not support');
-- 2. Owner grants admin to alice through the RPC
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-000000000001","role":"authenticated"}', true);
select lives_ok(
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000a', 'admin') $$,
'owner grants admin'
);
select throws_ok(
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000a', 'admin') $$,
'23505',
null,
'granting an active role twice is refused'
);
select throws_ok(
$$ select public.grant_platform_role('00000000-0000-0000-0000-000000000001', 'admin') $$,
'42501',
null,
'owner cannot change their own roles'
);
select throws_ok(
$$ select public.grant_platform_role(gen_random_uuid(), 'support') $$,
'P0002',
null,
'unknown target is refused'
);
-- 3. Alice (admin) may delegate moderator/support, nothing above
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
select lives_ok(
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000b', 'moderator') $$,
'admin grants moderator'
);
select throws_ok(
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000b', 'admin') $$,
'42501',
null,
'admin cannot grant admin'
);
select throws_ok(
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000b', 'owner') $$,
'42501',
null,
'admin cannot grant owner'
);
select throws_ok(
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000a', 'owner') $$,
'42501',
null,
'admin cannot promote herself to owner'
);
-- 4. Direct writes are impossible for the API role
select throws_ok(
$$ insert into public.profile_roles (user_id, role) values ('00000000-0000-0000-0000-00000000000a', 'owner') $$,
'42501',
null,
'admin cannot insert a role row directly'
);
select throws_ok(
$$ update public.profile_roles set role = 'owner' where user_id = '00000000-0000-0000-0000-00000000000a' $$,
'42501',
null,
'admin cannot update role rows directly'
);
select throws_ok(
$$ delete from public.profile_roles $$,
'42501',
null,
'admin cannot delete role rows directly'
);
-- 5. Bob (moderator) cannot delegate; sees only his own grants; carol sees nothing
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
select throws_ok(
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000c', 'support') $$,
'42501',
null,
'moderator cannot grant any role'
);
select results_eq(
$$ select user_id, role::text from public.profile_roles $$,
$$ values ('00000000-0000-0000-0000-00000000000b'::uuid, 'moderator'::text) $$,
'moderator sees only his own grant rows'
);
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000c","role":"authenticated"}', true);
select is((select count(*) from public.profile_roles), 0::bigint, 'plain user sees no role rows');
select is((select count(*) from public.profiles), 1::bigint, 'plain user still sees one profile (own)');
-- 6. Admin sees every grant and every profile (staff read)
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
select is(
(select count(*) from public.profile_roles
where user_id in ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-00000000000a', '00000000-0000-0000-0000-00000000000b')),
3::bigint,
'admin sees all three fixture grant rows'
);
select is(
(select count(*) from public.profiles where id in (
'00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-00000000000a',
'00000000-0000-0000-0000-00000000000b', '00000000-0000-0000-0000-00000000000c')),
4::bigint,
'admin reads every fixture profile'
);
-- 7. Anonymous
set local role anon;
select set_config('request.jwt.claims', '', true);
select throws_ok(
$$ select public.grant_platform_role('00000000-0000-0000-0000-00000000000c', 'support') $$,
'42501',
null,
'anon cannot call grant_platform_role'
);
-- 8. Revocation and deactivation
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
select lives_ok(
$$ select public.revoke_platform_role('00000000-0000-0000-0000-00000000000b', 'moderator', 'test') $$,
'admin revokes moderator'
);
select ok(not private.is_platform_moderator('00000000-0000-0000-0000-00000000000b'), 'revoked role no longer counts');
reset role;
update public.profiles set active = false where id = '00000000-0000-0000-0000-00000000000a';
select ok(not private.is_platform_admin('00000000-0000-0000-0000-00000000000a'), 'deactivated account loses its roles');
-- 9. Last-owner guard on the system path (neutralise owners seeded outside the fixtures)
update public.profile_roles set revoked_at = now()
where role = 'owner' and revoked_at is null and user_id <> '00000000-0000-0000-0000-000000000001';
select throws_ok(
$$ select private.withdraw_platform_role(null, '00000000-0000-0000-0000-000000000001', 'owner', 'oops') $$,
'42501',
null,
'the last owner cannot be revoked'
);
select * from finish();
rollback;
+106
View File
@@ -0,0 +1,106 @@
-- audit.audit_logs: sensitive operations leave a row, rows are immutable,
-- only owners/admins read them.
begin;
select plan(12);
insert into auth.users (id, email) values
('00000000-0000-0000-0000-000000000001', 'root@test.local'),
('00000000-0000-0000-0000-00000000000a', 'alice@test.local'),
('00000000-0000-0000-0000-00000000000b', 'bob@test.local');
select private.assign_platform_role(null, '00000000-0000-0000-0000-000000000001', 'owner');
-- 1. Bootstrap is audited as a system action
select results_eq(
$$ select actor_user_id, action, resource_type, target_user_id, metadata ->> 'role'
from audit.audit_logs where target_user_id = '00000000-0000-0000-0000-000000000001' $$,
$$ values (null::uuid, 'platform_role.granted'::text, 'profile_role'::text,
'00000000-0000-0000-0000-000000000001'::uuid, 'owner'::text) $$,
'bootstrap grant logged with null actor'
);
-- 2. RPC grant and revoke are audited with the actor
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-000000000001","role":"authenticated"}', true);
select public.grant_platform_role('00000000-0000-0000-0000-00000000000a', 'admin');
select public.revoke_platform_role('00000000-0000-0000-0000-00000000000a', 'admin', 'rotation');
reset role;
select results_eq(
$$ select action, actor_user_id, target_user_id, metadata ->> 'reason'
from audit.audit_logs where actor_user_id = '00000000-0000-0000-0000-000000000001'
order by occurred_at, action $$,
$$ values ('platform_role.granted'::text, '00000000-0000-0000-0000-000000000001'::uuid,
'00000000-0000-0000-0000-00000000000a'::uuid, null::text),
('platform_role.revoked'::text, '00000000-0000-0000-0000-000000000001'::uuid,
'00000000-0000-0000-0000-00000000000a'::uuid, 'rotation'::text) $$,
'grant and revoke logged with actor, target and metadata'
);
select is(
(select count(*) from audit.audit_logs a
join public.profile_roles r on r.id = a.resource_id
where a.target_user_id in ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-00000000000a')),
3::bigint,
'every fixture audit row points at its profile_roles row'
);
-- 3. Append-only, even for the privileged owner session
select throws_ok(
$$ update audit.audit_logs set action = 'platform_role.tampered' $$,
'42501',
null,
'audit rows cannot be updated'
);
select throws_ok(
$$ delete from audit.audit_logs $$,
'42501',
null,
'audit rows cannot be deleted'
);
-- 4. log_event validates its inputs
select throws_ok(
$$ select private.log_event(null, 'Bad Action', 'profile') $$,
'23514',
null,
'action must match <domain>.<verb>'
);
select throws_ok(
$$ select private.log_event(null, 'export.requested', 'profile', null, null, null, '[]'::jsonb) $$,
'23514',
null,
'metadata must be a JSON object'
);
-- 5. Read access: owner yes, plain user no, anon no, nobody writes through the API
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-000000000001","role":"authenticated"}', true);
select is(
(select count(*) from audit.audit_logs
where target_user_id in ('00000000-0000-0000-0000-000000000001', '00000000-0000-0000-0000-00000000000a')),
3::bigint,
'owner reads the audit log'
);
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000b","role":"authenticated"}', true);
select is((select count(*) from audit.audit_logs), 0::bigint, 'plain user reads nothing');
select throws_ok(
$$ insert into audit.audit_logs (action, resource_type) values ('x.y', 'z') $$,
'42501',
null,
'authenticated cannot insert audit rows'
);
select throws_ok(
$$ select private.log_event(null, 'x.y', 'z') $$,
'42501',
null,
'authenticated cannot call log_event'
);
set local role anon;
select throws_ok(
$$ select * from audit.audit_logs $$,
'42501',
null,
'anon cannot read the audit log'
);
select * from finish();
rollback;