Merge feature/step-07-identity-app-shell 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-12 00:54:05 +02:00
commit 505b83087b
83 files changed
+4597 -30

No files matched your search

+11
View File
@@ -343,3 +343,14 @@ Status: closed (Step 6 validated by user 2026-10-11; D8 finalised in BDR-040).
User decisions after manual validation (logos and picker text confirmed OK on their side; Step 6 VALIDATED). (1) Re-export of the imported archive from the UI REFUSED permanently: the practitioner already holds the original PDF; no second button, no dedicated UX flow. Keep the archived snapshot, its integrity and the autonomy tests (engine `exportFromEnvelope` stays as the proof + future server use); the UI exports only the open working report. Do not propose this feature again. (2) Rebase on draft restore shown to the user (`editor.draft_rebased`) approved; import messages approved on principle with an explicit "full restoration" vs "partial recovery" headline. (3) BLK-009 treated now: byte-scan attachment extraction without pdf-lib load on import + export without object streams; remaining risks (worker/server import, pdf-lib replacement, read caps) stay an explicit BLOCKER gate before any external user import; never declared solved by passing tests alone.
Alt rejected: a re-export action on the home screen after import (same objection); a toast system for import feedback (no component, alert pattern kept).
Status: closed.
## BDR-041 | 2026-10-11 | Step 7 scope: zustand auth store (no TanStack), professional fields on profiles, MFA = documented gap, config-driven OAuth buttons, local tool stays open
Step 7 brief (UX validated by user with external mockups, not versioned). Choices: (1) no TanStack Query: one profile read/update per section, zustand `authStore` + `localeSync` enough; query layer deferred to the first list screens. (2) `practice_name`, `professional_title`, `siret` added to `profiles` as declared free text (CHECKs, column grants), verification stays the Professional Verification domain (Step 11). (3) MFA: foundations had TOTP disabled, no `has_mfa()`, no admin table → TOTP enabled server-side, enforcement + enrolment UI documented as gap (IDENTITY.md §4), Security section shows a note, no fake UI. (4) OAuth buttons listed by `APP_AUTH_PROVIDERS` / `VITE_AUTH_PROVIDERS`; config.toml providers read `env()` ids, `enabled = false` until ids exist; `platform_invitations` not written. (5) Local tool routes untouched + unauthenticated (`LocalToolShell`, catch-all), Home header entry only when Supabase configured; `/app` guard sends to `/login?next=` with same-origin check. (6) Account locale wins over device locale once per sign-in; switches while signed in persist to `profiles.locale`.
Alt rejected: TanStack now (YAGNI); MFA enrolment screen (unvalidated UI, nothing to protect); `/register` naming (`/signup` kept); nested `<a><button>` for card CTAs (ButtonLink instead).
Status: active, awaiting user validation of the step.
## BDR-042 | 2026-10-12 | Step 7 validated; validated mockups versioned as permanent design reference; Home without sidebar accepted
User validated every Step 7 screen and flow (login, signup, recovery, dashboard, account, sidebar + drawer, logout, FR/EN, responsive), no UI correction. Decisions: (1) the mockup file the user produced (`docs/design/faunosteo-etape7-maquettes-validees.png`, 7 views) is the permanent graphic reference for the SaaS shell; `docs/design/README.md` lists what it shows beyond Step 7 with the owning step (Bilans/Clients/Animaux/Agenda/Fiches entries, stat tiles, bell, avatar photo → Step 8, Mon compte tabs, mobile tab bar) so no screen invents them early; a redesign needs a new validated file there. (2) Local-tool Home (`/`) shows no sidebar when signed in, only "Mon espace": accepted until the tool is integrated into `/app` (Step 14). (3) Password rule in the mockup (8 chars) does NOT override the server policy (12 + classes). (4) Follow-ups kept in TODO 7.10: MFA before sensitive admin features, professional verification ≠ SIRET format, real OAuth tests once ids exist, tool integration into /app.
Status: closed; Step 7 finished into develop.
+7
View File
@@ -115,3 +115,10 @@ Method: user manual tests round 1 (logos absent, picker blurry) → reproduction
Result: neither visual defect reproduced here (4 environments, 2 engines, 2 PDF renderers); shipped the environment-independent fixes (branding bundled, no fetch; warnings surfaced) and the user confirmed logos + crisp text. Scanner: verifier CONFORME 7/7; audit 1 PASS + 2 MEDIUM (Chromium DecompressionStream read-ahead defeats the cancel: +2.2 GB on a 4 GiB bomb; ×32 candidate CPU) → executor (16 KiB slice feeding, shared 16 MiB budget, monotonic bounded endstream search, `{` pre-check; 133 pdf tests) → audit 2 focused. Workspace 710 tests, build, docker green.
Anomalies: the blur fix of the previous round (will-change) had been marked PARTIALLY MET "desktop by user" — the user's "still blurry" came from that unverified half; this round could not verify real-GPU text rendering either (headless engines render grayscale AA, headed captures failed) → lesson: a screen-rendering defect needs the user's own capture + an A/B recipe early, not days of headless measurement. The Node vitest suite cannot observe browser stream read-ahead: record browser-only bounds as owed manual checks (PDF_IMPORT_HARDENING §5).
Action: BLK-009 stays "mitigated, gate open" (BDR-040); Step 6 finished into develop; release/0.2.0 prepped for the user's go.
## EVAL-015 | 2026-10-11 | Step 7 identity — gates on the whole step
Method: contract with 16 criteria (`2026-10-11-step-07-verify.md`) → fresh verifier; security-auditor (semgrep 159 rules + checklist) on `c746952..HEAD`; headless e2e vs the local stack (playwright-core in scratchpad, Mailpit API); real-stack pgTAP + docker build by the orchestrator.
Result: verifier pass 1 ECARTS(2): (a) real gap, `safeNextPath` prefix check let `/\host` and `/<TAB>/host` through (router `location.assign` fallback = open redirect after login) → fixed by resolving against a sentinel origin and rebuilding from parsed parts, 5 new cases; (b) contract regex over-matched other unions (`'google' | 'apple'`, `'fr' | 'en'`) → CHECK scoped. Pass 2 CONFORME 16/16. Security PASS, 1 MEDIUM (same redirect, already fixed) + 4 LOW: 3 closed same session (sign-out failure reported, `reauthentication_needed` phrased, exact prod redirect allowlist documented), 1 pre-existing (TOTP not enforced for staff = documented gap). E2E 20/20. Workspace 763 tests, lint 0, build, docker, real-stack pgTAP 280 green.
Anomalies: both gates found the same redirect hole my own tests missed → a prefix check on a URL is never enough, parse it; the auditor misread the sign-out note ("this device") as "everywhere" but the LOW still pointed at a silent failure path worth phrasing. Mockups validated with ChatGPT are not in the repo: the screens follow the written direction and the existing tokens, pixel fidelity unverifiable here.
Action: awaiting user validation of Step 7 (manual procedure IDENTITY.md §5); release/0.2.0 still open for the human go.
+8
View File
@@ -211,3 +211,11 @@ User: step not merged; findings-picker text still blurry; footer logos absent in
## 2026-10-11 (Step 6 closure)
User round 2: logos OK, picker text crisp, flows OK → STEP 6 VALIDATED. Decisions BDR-040: re-export-archive button refused for good; restore-rebase alert approved; import headlines full/partial (62b8a43). BLK-009: byte-scan attachment reader + export without object streams (60ee712), verifier CONFORME, audit PASS+2 MEDIUM → slice-fed inflater + candidate budget (3a6e926), focused re-audit. EVAL-014. Then: gitflow finish into develop, release/0.2.0 prep (Milestone A) up to the human go; Step 7 not started (UX/design to discuss with ChatGPT first).
## 2026-10-11 (Step 7 implementation)
User: mockups validated (external, not in repo), implement Step 7 on a branch. feature/step-07-identity-app-shell off develop (release/0.2.0 still open, awaiting go). Foundation: packages/supabase auth/profile/roles services (closed AuthFailure kinds), migration 20261011100000 professional columns + pgTAP 009 (PGlite 22/22, real stack 280/280, types regenerated), config.toml TOTP on + google/apple via env(), `APP_AUTH_PROVIDERS`. App: authStore + localeSync + AuthProvider, routes /login /signup /forgot-password /reset-password /auth/callback, guards, AppLayout (sidebar / top bar / drawer), dashboard (profile completeness, local tool, account), Mon compte (4 sections, one save each), Home entry when configured. Tests 277 app + 24 supabase, lint 0, typecheck, build, docker OK; impeccable detect clean; headless e2e against the local stack 20/20 (guard, login, account save, SIRET error, language, mobile no overflow, drawer, logout, signup → Mailpit confirmation → /app, recovery → reset → login). Docs: IDENTITY.md, CLAUDE.md, SUPABASE.md, CHANGELOG, plan note. BDR-041, LRN-047. Gates (verifier, security) dispatched; awaiting user validation; `.env.example` edit denied (file rule) → user adds `APP_AUTH_PROVIDERS=`. Gates: verifier ECARTS(2) → `safeNextPath` parser-escape fix (+5 tests) + contract CHECK scoped → CONFORME 16/16; security PASS (MEDIUM = same redirect; LOWs: sign-out failure alert, `reauthentication_needed` kind, prod redirect allowlist doc). EVAL-015. Real-stack pgTAP 280, build, docker green. Stop: user validation.
## 2026-10-12 (Step 7 closure)
User validated Step 7 (all screens, flows, FR/EN, responsive; Home-without-sidebar accepted). Mockup file dropped at root → `docs/design/faunosteo-etape7-maquettes-validees.png` + README (deltas vs step, owning steps); CLAUDE.md design-reference rule; IDENTITY.md pointer. BDR-042; TODO 7.10 follow-ups (MFA gate, verification ≠ SIRET, OAuth real tests, tool integration). Final check green; gitflow finish into develop. Next: Step 8 files foundation, awaiting user go (Q2 hosting/edge-runtime decision shapes the SVG sanitizer).
+5
View File
@@ -352,3 +352,8 @@ Apply: any `motion.*`/CSS transition on lists, cards, modals holding text; desig
Step 6 moved the PDF pipeline into `packages/pdf` with zero visible change. What made it provable: Phase 0 froze drawn text (page, x, y, size, font), image placements, link annotations and per-view structural facts with the OLD code, in two harness modes (logos absent / present via a fetch stub serving the real public/ bytes) and per locale (footer geometry depends on label width). Golden JSON = oracle; the port had 0 mismatch; the two intentional differences (hidden markers absent, data-* gone) were declared as relaxed fields, never by editing goldens. Snapshot shaped as a valid lean `AnatomicalSheetDocument` reused the index, the renderer and 21 integrity rules (3 challengers killed the dedicated-schema idea). Node-side xmldom composer already existed in curation (`app-review.ts`): promote, don't rewrite. resvg 0.40 panics on gradient fills culled by a cropped root viewBox (head view) → test adapter renders the full box and crops pixels; Chrome is fine. Executors denied `rm`/`git rm`: orchestrator deletes on literal relative paths after checking importers.
Apply: any pipeline extraction (Step 13 Supabase provider, Step 14 worker); any "snapshot" design: reuse the live schema minus content before inventing one.
## LRN-047 | 2026-10-11 | Supabase Auth in a SPA: initialize() + PKCE same-browser rule, GoTrue codes → closed kinds, pgTAP data-modifying CTE trap
Step 7 facts worth keeping. (1) `client.auth.initialize()` is public and idempotent: await it at store start to catch the URL exchange error (expired/foreign link) that `onAuthStateChange` never reports; `INITIAL_SESSION` ordering vs that promise is not guaranteed → a callback route landing signed-out = failure, don't wait for a flag. (2) PKCE confirmation/recovery links only open a session in the browser that made the request (verifier in its localStorage); the email is still confirmed server-side → phrase it ("opened in another browser… just sign in"), don't claim expiry. (3) supabase-js 2.117 `AuthError.code` (`invalid_credentials`, `user_already_exists`, `weak_password`, `otp_expired`, `bad_code_verifier`…) → map to a closed union in the access layer, UI translates `auth.failure.<kind>`; raw messages never rendered. (4) Account load must run outside the auth callback (`setTimeout 0`): the client serialises callbacks, awaiting a request inside deadlocks. (5) pgTAP: `select is((with upd as (update … returning 1) select count(*) from upd), …)` fails ("data-modifying CTE must be top level") and silently breaks the plan count; use `lives_ok` + a read after `reset role`. (6) Mailpit API (`/api/v1/search?query=to:<email>`, `/api/v1/message/<id>`) makes the confirmation + recovery flows scriptable headlessly; playwright-core installed in the scratchpad + cached `ms-playwright` chromium via `executablePath` = no project dependency.
Apply: every future Supabase auth surface (Step 14 gating, invitations), any pgTAP write assertion, any e2e of email flows.
+12
View File
@@ -114,6 +114,18 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [ ] 6.7 follow-ups recorded for Step 13: catalog asset cap aligned with the archive cap (2 MiB), allowlist sanitiser at upload, app canvas sanitiser (EVAL-011)
- [ ] 5 follow-up: allowlist SVG sanitiser before Storage-served assets (Step 13); orphan findings UX (D5) at the report UX step; report:compare residuals (ZodError reason genericised, v3 lines computed once, long template lines); 16 MiB attachment cap without direct test
- [x] Step 7 — identity: auth, profile, roles, /app shell (started 2026-10-11, branch feature/step-07-identity-app-shell; USER VALIDATED 2026-10-12, all screens and flows OK, no UI correction; mockups now versioned at docs/design/faunosteo-etape7-maquettes-validees.png; finished into develop). Scope decisions: professional fields = additive migration on profiles (practice_name, professional_title, siret free text, verification = later domain); MFA = documented gap (TOTP disabled in config, no has_mfa helper, no admin table); no TanStack Query (zustand store suffices); legacy routes untouched and unauthenticated; /app visible from Home only when Supabase is configured
- [x] 7.0 plan + branch + ctx7 cache (supabase-js auth, config.toml providers)
- [x] 7.1 config: appConfig.authProviders (APP_AUTH_PROVIDERS / VITE_AUTH_PROVIDERS, google|apple), entrypoint + env.example + DEPLOY table; config.toml: TOTP enroll/verify on, [auth.external.google|apple] via env(), redirect URLs; packages/supabase: auth service wrappers (typed errors), profile read/update service
- [x] 7.2 migration 20261011100000_profiles_professional: practice_name, professional_title, siret (+ CHECKs, column grants); pgTAP 009; database.types regenerated (real stack) + schema-types map
- [x] 7.3 app state: authStore (status loading|signed_out|signed_in, session, user, profile, roles), bootstrap on getSession + onAuthStateChange, profile fetch, roles fetch; locale sync (profile.locale → localeStore on sign-in, localeStore → profiles.locale while signed in); AuthProvider in App
- [x] 7.4 auth screens: /login (email+password, OAuth buttons per authProviders, links), /signup (display name, email, password ×2, policy hints, "check your inbox" state), /forgot-password, /reset-password (PASSWORD_RECOVERY → new password), /auth/callback (code exchange → /app); AuthLayout (brand, cream card); not-configured state
- [x] 7.5 /app shell: RequireAuth guard (redirect /login?next=), AppLayout (desktop sidebar: dashboard, account, local tool link, logout; mobile top bar + drawer), /app dashboard (welcome, profile completeness card, local tool card, no fake stats)
- [x] 7.6 /app/account: personal (display, first, last, phone), professional (title, practice, siret), preferences (locale, timezone), security (change password, logout, MFA gap note), roles badge read-only
- [x] 7.7 Home coexistence: "Mon espace / Se connecter" entry on the header when configured; characterisation tests T12 unchanged with default config
- [x] 7.8 tests: config, authStore (fake client), locale sync, forms, guards, shell, dashboard, account; i18n parity; pgTAP 009 (PGlite + real stack 280/280); root check + docker build green; headless e2e vs local stack 20/20 (signup via Mailpit, recovery, logout, mobile)
- [x] 7.9 docs (IDENTITY.md, SUPABASE.md, CLAUDE.md, CHANGELOG, plan note); memory BDR-041, LRN-047, EVAL-015, journal; gates: verifier ECARTS(2) → open-redirect fix + contract CHECK → CONFORME 16/16; security PASS (MEDIUM fixed, 3 LOW closed, TOTP enforcement = documented gap). User validated 2026-10-12; user action still open: `.env.example` += `APP_AUTH_PROVIDERS=` (file edit denied here)
- [ ] 7.10 follow-ups kept by the user (2026-10-12), each owned by a later step: MFA mandatory before any sensitive admin feature (has_mfa helper + enrolment UI, IDENTITY.md §4; first admin screen); professional verification distinct from the SIRET format check (Step 11); real tests of Google and Apple once the provider ids exist (config.toml env(), APP_AUTH_PROVIDERS); integration of the report tool into the signed-in /app space (Step 14 gating); mockup elements not built yet listed in docs/design/README.md (bell, avatar photo → Step 8, stat tiles, tabs, mobile tab bar)
---
## Phase A — DONE (kept for reference)
@@ -0,0 +1,57 @@
# CONTRACT — step-07 identity, auth, /app shell (whole step, for the fresh verifier)
- date: 2026-10-11 | flow: ad-hoc step (user brief) | branch: feature/step-07-identity-app-shell
- status: active (amended 2026-10-11 after verifier pass 1: criterion 3 strengthened, criterion 5 CHECK regex scoped to the AuthFailureKind union)
- spec: docs/development/IDENTITY.md; user brief (below)
## REQUEST (user brief 2026-10-11, condensed — IMMUTABLE)
Implement Step 7 keeping the current visual identity (logo, palette, cream/white cards, terracotta buttons, desktop side navigation, mobile adaptation). Scope: (1) auth: email/password sign-in and sign-up, email verification, password recovery/reset, Google sign-in, Apple if clean, no phone; (2) guarded /app shell with desktop sidebar, mobile adaptation, light top bar, simple dashboard with useful cards and clean empty states, no fake modules; (3) Mon compte: personal info, professional info, preferences (incl. language), security, sign-out; (4) Supabase auth + profile integration, language synced with profiles.locale, platform roles per the foundations, MFA mandatory for admin roles if the foundations allow it, else document the gap. Constraints: existing local tool routes (home, new report, PDF import, editor) keep working unauthenticated; explicit coexistence; no unvalidated complex UI, no artificial stats, no rich admin screens, no change to the report engine.
## ACCEPTANCE CRITERIA
1. Routes exist and are wired: /login /signup /forgot-password /reset-password /auth/callback /app /app/account.
CHECK: grep -c "path=\"/login\"\|path=\"/signup\"\|path=\"/forgot-password\"\|path=\"/reset-password\"\|path=\"/auth/callback\"\|path=\"/app\"\|path=\"account\"" apps/app/src/app/App.tsx
EXPECT: 7
2. Local tool routes unchanged and unauthenticated: HomeRoute, NewReportRoute, EditorRoute are rendered outside RequireAuth; their characterisation tests pass.
CHECK: grep -n "LocalToolShell\|RequireAuth" apps/app/src/app/App.tsx | head; cd apps/app && corepack pnpm vitest run tests/unit/routes.HomeRoute.import.test.tsx tests/unit/routes.HomeRoute.archive.test.tsx tests/unit/routes.EditorRoute.test.tsx tests/unit/routes.NewReportRoute.test.tsx 2>&1 | tail -2
EXPECT: the three local routes are inside LocalToolShell (path "*"), not under the /app RequireAuth element ; passed
3. Guard: /app/* requires a session, redirects to /login?next=<same-origin path>; `next` never accepts an absolute, protocol-relative or parser-escaped (`/\host`, tab/newline) URL: the value is resolved against a sentinel origin and rebuilt from the parsed parts.
CHECK: cd apps/app && corepack pnpm vitest run tests/unit/guards.RequireAuth.test.tsx tests/unit/auth.validation.test.ts 2>&1 | tail -2; grep -n "url.origin !== PROBE_ORIGIN" apps/app/src/auth/redirects.ts; node -e "const u=new URL('/\\\\evil.test','http://next.invalid');console.log(u.origin)"
EXPECT: passed (incl. the backslash/tab cases) ; one match ; http://evil.test (proves the parser escape the check guards against)
4. Auth flows call the client with the right inputs: sign-in (email, password), sign-up (metadata display_name + locale, emailRedirectTo ending in /auth/callback), reset (redirectTo /reset-password), updateUser({password}), signOut, signInWithOAuth(provider, redirectTo /auth/callback).
CHECK: grep -n "emailRedirectTo\|RESET_PASSWORD_PATH\|AUTH_CALLBACK_PATH" apps/app/src/app/routes/auth/*.tsx apps/app/src/components/auth/OAuthButtons.tsx | wc -l; cd apps/app && corepack pnpm vitest run tests/unit/routes.LoginRoute.test.tsx tests/unit/routes.SignupRoute.test.tsx tests/unit/routes.AccountRoute.test.tsx 2>&1 | tail -2
EXPECT: >= 4 ; passed
5. Server errors are never shown raw: every GoTrue error goes through classifyAuthError → AuthFailure kind → `auth.failure.<kind>` key present in fr and en for every kind of the union.
CHECK: sed -n '/^export type AuthFailureKind =/,/^$/p' packages/supabase/src/auth.ts | grep -o "| '[a-z_]*'" | sed "s/| '//;s/'//" | sort -u > "$TMPDIR/kinds.txt"; for k in $(cat "$TMPDIR/kinds.txt"); do grep -q "'auth.failure.$k'" apps/app/src/i18n/fr.ts && grep -q "'auth.failure.$k'" apps/app/src/i18n/en.ts || echo MISSING $k; done
EXPECT: no MISSING line (13 kinds)
6. Email verification mandatory and password policy mirrored: config.toml enable_confirmations = true, minimum_password_length = 12, password_requirements lower_upper_letters_digits; client passwordSchema min 12 + the three classes.
CHECK: grep -n "enable_confirmations = true\|minimum_password_length = 12\|lower_upper_letters_digits" supabase/config.toml | wc -l; grep -n "PASSWORD_MIN_LENGTH = 12\|\[a-z\]\|\[A-Z\]\|\[0-9\]" apps/app/src/auth/validation.ts | wc -l
EXPECT: 3 ; >= 4
7. Google and Apple: config.toml sections read ids from env(), app shows buttons only for APP_AUTH_PROVIDERS / VITE_AUTH_PROVIDERS, entrypoint and DEPLOY.md carry the variable.
CHECK: grep -n "\[auth.external.google\]\|\[auth.external.apple\]\|env(SUPABASE_AUTH_EXTERNAL" supabase/config.toml | wc -l; grep -n "APP_AUTH_PROVIDERS" docker/entrypoint.sh DEPLOY.md | wc -l; grep -n "resolveAuthProviders" apps/app/src/config/env.ts | wc -l
EXPECT: 6 ; >= 2 ; >= 2
8. Profile integration: own-row read + update through packages/supabase; professional columns exist with CHECKs and column grants; pgTAP 009 runs on PGlite and the real stack; database.types in sync.
CHECK: cd packages/supabase && corepack pnpm vitest run 2>&1 | tail -2; grep -c "grant update (practice_name, professional_title, siret)" supabase/migrations/20261011100000_profiles_professional.sql; grep -c "practice_name" packages/supabase/src/database.types.ts
EXPECT: passed ; 1 ; 3
9. Language sync both ways: profile locale applied on sign-in, switch saved to profiles.locale while signed in, untouched when signed out.
CHECK: cd apps/app && corepack pnpm vitest run tests/unit/services.localeSync.test.ts 2>&1 | tail -2
EXPECT: passed (3 tests)
10. Platform roles shown read-only (badges, `shell.role.*` for the four enum values), no grant/revoke UI.
CHECK: grep -c "'shell.role\." apps/app/src/i18n/fr.ts; grep -rn "grant_platform_role\|revoke_platform_role" apps/app/src | wc -l
EXPECT: 4 ; 0
11. MFA: documented gap (IDENTITY.md §4) and server-side TOTP enabled; the Security section shows the note; no fake enrolment UI.
CHECK: grep -n "enroll_enabled = true" supabase/config.toml | wc -l; grep -n "^## 4. MFA" docs/development/IDENTITY.md; grep -n "mfa_note" apps/app/src/components/account/SecurityPanel.tsx | wc -l
EXPECT: 1 ; one heading ; 1
12. Shell and responsive: desktop sidebar (lg:), mobile drawer behind a labelled button, no horizontal overflow risk patterns; tests pass.
CHECK: cd apps/app && corepack pnpm vitest run tests/unit/shell.AppLayout.test.tsx tests/unit/routes.DashboardRoute.test.tsx 2>&1 | tail -2; grep -n "lg:hidden\|hidden lg:flex" apps/app/src/components/shell/AppLayout.tsx | wc -l
EXPECT: passed ; >= 2
13. Dashboard content is honest: no numeric statistic, no fake module; cards = profile completeness, local tool, account facts.
CHECK: grep -n "ProfileCard\|ToolCard\|AccountCard" apps/app/src/app/routes/app/DashboardRoute.tsx | wc -l; grep -nE "[0-9]+ (bilans|reports|clients)" apps/app/src/i18n/fr.ts apps/app/src/i18n/en.ts | wc -l
EXPECT: >= 6 ; 0
14. i18n parity (fr/en same key set) and lint 0 warnings, typecheck clean, build OK.
CHECK: cd apps/app && corepack pnpm vitest run tests/unit/i18n.dicts.test.ts 2>&1 | tail -2; cd ../.. && corepack pnpm typecheck 2>&1 | grep -c "error TS"; corepack pnpm lint 2>&1 | grep -c "✖"
EXPECT: passed ; 0 ; 0
15. Coexistence explicit: Home header shows the entry only when Supabase is configured (HomeSpaceLink returns null otherwise); /app dashboard links back to the local tool.
CHECK: grep -n "if (!supabase) return null" apps/app/src/components/brand/HomeSpaceLink.tsx | wc -l; grep -n 'to="/new"\|to="/"' apps/app/src/app/routes/app/DashboardRoute.tsx | wc -l
EXPECT: 1 ; 2
16. Docs synced: IDENTITY.md exists with routes, session, config, MFA gap, manual validation; CLAUDE.md map + architecture mention the identity layer; CHANGELOG entry; plan note.
CHECK: grep -c "^## " docs/development/IDENTITY.md; grep -n "authStore\|IDENTITY.md" CLAUDE.md | wc -l; grep -n "Identity (Step 7)" CHANGELOG.md | wc -l; grep -n "Step 7 implementation note" docs/development/IMPLEMENTATION_PLAN.md | wc -l
EXPECT: 5 ; >= 2 ; 1 ; 1
+4
View File
@@ -6,6 +6,10 @@ Versions follow [Semantic Versioning](https://semver.org/).
## [Unreleased]
### Added (SaaS migration, plan Step 7)
- **Identity (Step 7)** — sign-in and sign-up by email/password (confirmation mandatory, policy 12 chars + lower/upper/digit), password recovery, OAuth buttons (Google, Apple) driven by `APP_AUTH_PROVIDERS`, landing route for confirmation / OAuth links; the guarded `/app` shell (desktop sidebar, light top bar, mobile drawer) with a dashboard (greeting, profile completeness, local tool, account) and **Mon compte** (personal, professional, preferences, security). Profile columns `practice_name`, `professional_title`, `siret` (migration `20261011100000`, pgTAP 009), language synced with `profiles.locale`, platform roles shown read-only. GoTrue TOTP enabled server-side; MFA enforcement for platform roles documented as a gap (`docs/development/IDENTITY.md`). The local tool (`/`, `/new`, `/editor`) stays unauthenticated; the Home header links to the space only when Supabase is configured.
### Added (SaaS migration, plan Steps 3–6)
- **Autonomous PDF archives (Step 6)** — new `@faunosteo/pdf` engine (`packages/pdf`): the PDF is rendered from explicit inputs (report, sheet snapshot, branding, labels, locale, rasterizer, export date), with no network and no browser DOM; the attachment becomes a **report archive envelope v1** (`osteo-report.json`) carrying the Report v3, a lean but valid snapshot of the anatomical sheet (views, annotations, geometry, colours, relations, the finding paths used with their ancestor labels, the SVG drawing), the branding used at export and the FR/EN label dictionary, so an old bilan is reproduced identically after any catalog, wording or logo change. Layered reading keeps the report even when the wrapper or the snapshot is refused (closed reasons), v2 and bare v3 PDFs still import, a PDF whose attachment was stripped is recognised. Imported archives are kept in the session; a bilan reopened on a different sheet is rebased on a working copy with unresolved items flagged and their labels kept, and the import message says so. SVG assets go through an allowlist sanitiser with size and complexity caps checked at import and at export; a WinAnsi guard keeps any text from crashing the export. Pages unchanged (frozen by 39 goldens). `docs/PDF-FORMAT.md` written for real.
+34 -6
View File
@@ -22,7 +22,12 @@ through a generated migration map. Step 6 made the PDF an autonomous archive: th
labels, rasterizer) with no network and no DOM, and the attachment is an envelope v1
carrying the report, a lean sheet snapshot, the branding and the labels used, so an old
bilan is reproduced identically after any catalog, wording or logo change
(`docs/PDF-FORMAT.md`). The Supabase client is still unused by the UI.
(`docs/PDF-FORMAT.md`). Step 7 added identity: email/password sign-up with
confirmation, password recovery, OAuth buttons driven by config, the guarded
`/app` shell (dashboard, Mon compte with personal / professional / preferences /
security sections) on Supabase Auth + `profiles` + `profile_roles`, language
synced with `profiles.locale` (`docs/development/IDENTITY.md`). The local tool
routes stay unauthenticated.
MVP species: equine only. Open-source MIT.
---
@@ -161,31 +166,41 @@ faunosteo/
│ ├─ app/
│ │ ├─ App.tsx ← root router
│ │ ├─ routes/{Home,NewReport,Editor,NotFound}Route.tsx
│ │ └─ providers/ConfigProvider.tsx ← AppConfig context
│ │ ├─ routes/auth/{Login,Signup,ForgotPassword,ResetPassword,AuthCallback}Route.tsx
│ │ ├─ routes/app/{Dashboard,Account}Route.tsx ← behind RequireAuth, inside AppLayout
│ │ ├─ guards/{RequireAuth,RedirectIfSignedIn,SessionLoading}.tsx
│ │ └─ providers/{ConfigProvider,AuthProvider}.tsx ← AppConfig context; session + locale sync start
│ ├─ auth/{validation,redirects,useAuthFailureMessage}.ts ← Zod schemas (i18n keys), safe next path, failure phrasing
│ ├─ account/{validation,useProfileForm}.ts ← account section schemas + one-save form hook
│ ├─ config/env.ts ← runtime config resolution
│ ├─ sheets/{provider,useSheet}.ts ← SheetProvider interface, bundled implementation, per-species hook
│ ├─ services/
│ │ ├─ sheetIndex.ts ← read-only lookups over the loaded sheet (ids, never labels)
│ │ └─ zoneInteraction.ts ← pure click decision + observation reducers (zones, sides, vertebrae)
│ │ ├─ zoneInteraction.ts ← pure click decision + observation reducers (zones, sides, vertebrae)
│ │ └─ localeSync.ts ← profiles.locale ↔ localeStore (account wins on sign-in)
│ ├─ i18n/
│ │ ├─ types.ts ← Locale type + Dict type
│ │ ├─ fr.ts + en.ts ← translation dicts (flat key → string)
│ │ ├─ index.ts ← getDict(locale)
│ │ └─ useT.ts ← useT() hook (reads localeStore)
│ ├─ state/
│ │ ├─ authStore.ts ← session, user, profile, roles, recovery flag (onAuthStateChange)
│ │ ├─ reportStore.ts ← Zustand store (Report v3) + persistence.ts (sessionStorage adapter, v2 draft migration)
│ │ ├─ localeStore.ts ← locale Zustand store (persisted to localStorage)
│ │ └─ practitionerCache.ts ← localStorage prefill
│ ├─ anatomy/drawing.ts ← sanitised asset + generated annotation layer → inline <svg> per view
│ ├─ components/
│ │ ├─ ui/{Button,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip}.tsx
│ │ ├─ ui/{Button,ButtonLink,Card,Dialog,Input,Label,Select,Textarea,Badge,Chip,Icon,FormField,Notice}.tsx
│ │ ├─ canvas/{AnatomyCanvas,DetailModal}.tsx
│ │ ├─ observation/{ObservationList,ObservationCard,ObservationPickers,FindingsTreePicker,
│ │ │ VertebraPicker,SeveritySelector,LateralityPicker,
│ │ │ FreeTextFindingInput}.tsx
│ │ ├─ report/{ReportHeader,PractitionerForm,AnimalForm,EditInfosDialog,DisclaimerDialog,
│ │ │ ConclusionPanel,NextAppointmentPicker}.tsx
│ │ └─ brand/{Brand,AppHeader,Footer,LanguageSwitcher}.tsx
│ │ ├─ brand/{Brand,AppHeader,Footer,LanguageSwitcher,HomeSpaceLink}.tsx
│ │ ├─ auth/{AuthLayout,OAuthButtons,PasswordField,UnavailableNotice,AuthLink}.tsx
│ │ ├─ shell/{AppLayout,SidebarNav,MobileDrawer,UserBadge,SignOutButton}.tsx
│ │ └─ account/{SectionCard,SaveRow,PersonalInfoForm,ProfessionalInfoForm,PreferencesForm,SecurityPanel,RoleBadges}.tsx
│ ├─ pdf/ ← app side of @faunosteo/pdf (engine in packages/pdf)
│ │ ├─ export.ts + import.ts ← exportReportToPdf (sheet snapshot + branding + browser rasterizer → engine), importReportFromPdf (ArchiveReadOutcome, ImportError kinds)
│ │ └─ branding.ts + browserRasterizer.ts ← bundled src/assets/brand logos (?inline / ?raw) → Branding; Image/canvas Rasterizer adapter
@@ -201,6 +216,7 @@ faunosteo/
├─ docs/
│ ├─ ANNOTATION-RENDERING.md ← annotation layer contract (attributes, styles, colours)
│ ├─ PDF-FORMAT.md
│ ├─ design/ ← VALIDATED graphic references (README.md + faunosteo-etape7-maquettes-validees.png); follow before proposing UI
│ ├─ faunosteo-audit/ ← audit of the current system (frozen at 83e40af)
│ ├─ development/ ← SaaS implementation plan, WORKSPACE.md
│ └─ history/superpowers/{specs,plans}/ ← 2026-05 design records (docs/superpowers is purged by gitflow finish)
@@ -275,6 +291,13 @@ PDF import
→ rebaseReportOnSheet(report, index, archivedSnapshot) when the loaded sheet differs (unresolved flags, labels kept)
→ hydrateImport({ report, archive }) → one alert (archive_ok / snapshot_rejected / rebased / migrated) → navigate /editor
Identity (Step 7, docs/development/IDENTITY.md)
→ AuthProvider: authStore.start() = client.auth.initialize() (PKCE code in URL) + onAuthStateChange
→ signed_in → fetchOwnProfile + fetchOwnPlatformRoles; localeSync applies profiles.locale, saves switches
→ /login /signup /forgot-password /reset-password /auth/callback (packages/supabase auth wrappers, AuthFailure kinds)
→ RequireAuth guards /app/* (→ /login?next=), AppLayout (sidebar / top bar / drawer), Dashboard, Account (updateOwnProfile)
→ no Supabase configured: status unavailable, auth screens show a notice, local tool unchanged
Runtime config
→ Docker entrypoint writes env.js (window.__APP_CONFIG__)
→ index.html loads env.js before bundle
@@ -304,7 +327,8 @@ Database (Supabase)
- Key convention: `<area>.<key>` — e.g. `common.cancel`, `home.new_report.title`, `pdf.subject`
- Both dicts must share the exact same key set; a key missing in one dict logs a warning in DEV
- Get the translate function in any component: `const t = useT()` then `t('common.cancel')`
- `src/state/localeStore.ts` holds current `Locale` (`'fr' | 'en'`), persisted to `localStorage` key `osteo:locale`; default: navigator-detected `fr`/`en`, or `'fr'` if no match
- `src/state/localeStore.ts` holds current `Locale` (`'fr' | 'en'`), persisted to `localStorage` key `osteo:locale`; default: navigator-detected `fr`/`en`, or `'fr'` if no match; while signed in, `services/localeSync.ts` writes it to `profiles.locale` and applies the account locale on sign-in
- Form validation messages are i18n keys returned by the Zod schemas (`src/auth/validation.ts`, `src/account/validation.ts`), translated next to the field; GoTrue messages never reach the screen (`auth.failure.*`)
- Zone and finding names shown in the editor and the PDF come from the sheet document (`{ fr, en }` labels) and from the report's snapshots, not from the dict
- PDF static labels (section headings, metadata) live in the engine (`packages/pdf/src/i18n`, `defaultPdfLabels`, 25 keys) and are archived in the envelope; the app dicts hold no `pdf.*` key
@@ -313,6 +337,9 @@ Database (Supabase)
- Always read from ConfigProvider via useConfig()
- src/config/env.ts is the only place with defaults
### Design references
- `docs/design/` holds the owner-validated mockups (Step 7 file = target for the whole SaaS shell: sidebar entries, dashboard tiles, Mon compte tabs, mobile tab bar). Any new screen follows them; elements they show that no step has built yet are listed in `docs/design/README.md` with their owning step. A redesign needs a new validated file there first.
### Annotation rendering
- docs/ANNOTATION-RENDERING.md is the source of truth: the drawing carries no annotation element, the app draws
the markers from the document (`@faunosteo/anatomy/render`), with the attributes listed there
@@ -351,6 +378,7 @@ Database (Supabase)
validated and a production build carries no sheet unless that flag is set on purpose
### Database (Supabase)
- The auth session lives in the Supabase client (localStorage, PKCE); the app reads it through `state/authStore.ts` only. Profile columns the user may edit are the column grants in the profiles migrations; never widen them from the client.
- 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`.
+1
View File
@@ -82,6 +82,7 @@ each one explicitly.
| `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. |
| `APP_AUTH_PROVIDERS` | no | empty | OAuth buttons on the auth screens, comma-separated (`google,apple`). The Supabase project must enable the same providers; empty = email/password only. |
| `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 in this file: the anon key is public by design and
+55
View File
@@ -0,0 +1,55 @@
import { useState, type ChangeEvent, type FormEvent } from 'react'
import type { z, ZodType } from 'zod'
import type { OwnProfilePatch } from '@faunosteo/supabase'
import { fieldErrors, type FieldErrors } from '@/auth/validation'
import { useAuthStore } from '@/state/authStore'
export type SaveState = 'idle' | 'saving' | 'saved' | 'failed'
export interface ProfileForm<T extends Record<string, string>> {
values: T
errors: FieldErrors<T>
state: SaveState
field: (key: keyof T) => (e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) => void
submit: (e: FormEvent) => Promise<void>
}
/**
* One account section = one form: local values seeded from the profile,
* Zod validation (i18n keys), one save into profiles. The values stay what
* the user typed after a save; a failure keeps them for correction.
*/
export function useProfileForm<T extends Record<string, string>>(
initial: T,
schema: ZodType<T, z.ZodTypeDef, unknown>,
toPatch: (values: T) => OwnProfilePatch,
): ProfileForm<T> {
const updateProfile = useAuthStore((s) => s.updateProfile)
const [values, setValues] = useState<T>(initial)
const [errors, setErrors] = useState<FieldErrors<T>>({})
const [state, setState] = useState<SaveState>('idle')
const field = (key: keyof T) => (e: ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
setValues((v) => ({ ...v, [key]: e.target.value }))
if (state === 'saved') setState('idle')
}
async function submit(e: FormEvent) {
e.preventDefault()
const parsed = schema.safeParse(values)
if (!parsed.success) {
setErrors(fieldErrors(parsed.error))
return
}
setErrors({})
setState('saving')
try {
await updateProfile(toPatch(parsed.data))
setState('saved')
} catch {
setState('failed')
}
}
return { values, errors, state, field, submit }
}
+80
View File
@@ -0,0 +1,80 @@
import { z } from 'zod'
import type { OwnProfilePatch } from '@faunosteo/supabase'
/**
* Account forms. Messages are i18n keys; a `|value` suffix carries the
* placeholder (`account.error.too_long|80` → {max} = 80).
*/
function optionalText(max: number) {
return z.string().trim().max(max, `account.error.too_long|${max}`)
}
export const personalSchema = z.object({
display_name: z
.string()
.trim()
.min(1, 'account.error.required')
.max(80, 'account.error.too_long|80'),
first_name: optionalText(80),
last_name: optionalText(80),
phone: z
.string()
.trim()
.refine((v) => v === '' || /^\+[1-9][0-9]{6,14}$/.test(v), 'account.error.phone_format'),
})
export type PersonalValues = z.infer<typeof personalSchema>
export const professionalSchema = z.object({
professional_title: optionalText(80),
practice_name: optionalText(120),
siret: z
.string()
.transform((v) => v.replace(/\s+/g, ''))
.refine((v) => v === '' || /^[0-9]{14}$/.test(v), 'account.error.siret_format'),
})
export type ProfessionalValues = z.infer<typeof professionalSchema>
export const preferencesSchema = z.object({
timezone: z
.string()
.trim()
.min(1, 'account.error.required')
.max(64, 'account.error.too_long|64'),
})
export type PreferencesValues = z.infer<typeof preferencesSchema>
/** '' → null: the columns are nullable and refuse empty strings. */
function orNull(value: string): string | null {
return value === '' ? null : value
}
export function personalPatch(v: PersonalValues): OwnProfilePatch {
return {
display_name: v.display_name,
first_name: orNull(v.first_name),
last_name: orNull(v.last_name),
phone: orNull(v.phone),
}
}
export function professionalPatch(v: ProfessionalValues): OwnProfilePatch {
return {
professional_title: orNull(v.professional_title),
practice_name: orNull(v.practice_name),
siret: orNull(v.siret),
}
}
export function preferencesPatch(v: PreferencesValues): OwnProfilePatch {
return { timezone: v.timezone }
}
/** Splits `key|value` and fills {max}. */
export function translateFieldError(
t: (key: string) => string,
message: string | undefined,
): string | undefined {
if (!message) return undefined
const [key, value] = message.split('|')
return value ? t(key).replace('{max}', value) : t(key)
}
+41 -4
View File
@@ -1,12 +1,24 @@
import { BrowserRouter, Routes, Route } from 'react-router-dom'
import { ConfigProvider } from './providers/ConfigProvider'
import { AuthProvider } from './providers/AuthProvider'
import Footer from '@/components/brand/Footer'
import AppLayout from '@/components/shell/AppLayout'
import RequireAuth from './guards/RequireAuth'
import RedirectIfSignedIn from './guards/RedirectIfSignedIn'
import HomeRoute from './routes/HomeRoute'
import NewReportRoute from './routes/NewReportRoute'
import EditorRoute from './routes/EditorRoute'
import NotFoundRoute from './routes/NotFoundRoute'
import LoginRoute from './routes/auth/LoginRoute'
import SignupRoute from './routes/auth/SignupRoute'
import ForgotPasswordRoute from './routes/auth/ForgotPasswordRoute'
import ResetPasswordRoute from './routes/auth/ResetPasswordRoute'
import AuthCallbackRoute from './routes/auth/AuthCallbackRoute'
import DashboardRoute from './routes/app/DashboardRoute'
import AccountRoute from './routes/app/AccountRoute'
function AppShell() {
/** The local tool: unchanged routes, no account needed, shared footer. */
function LocalToolShell() {
return (
<div className="flex min-h-screen flex-col">
<main className="flex-1 flex flex-col">
@@ -22,12 +34,37 @@ function AppShell() {
)
}
/** Auth screens and the signed-in /app shell sit beside the local tool. */
export function AppRoutes() {
return (
<Routes>
<Route element={<RedirectIfSignedIn />}>
<Route path="/login" element={<LoginRoute />} />
<Route path="/signup" element={<SignupRoute />} />
<Route path="/forgot-password" element={<ForgotPasswordRoute />} />
</Route>
<Route path="/reset-password" element={<ResetPasswordRoute />} />
<Route path="/auth/callback" element={<AuthCallbackRoute />} />
<Route path="/app" element={<RequireAuth />}>
<Route element={<AppLayout />}>
<Route index element={<DashboardRoute />} />
<Route path="account" element={<AccountRoute />} />
<Route path="*" element={<NotFoundRoute />} />
</Route>
</Route>
<Route path="*" element={<LocalToolShell />} />
</Routes>
)
}
export default function App() {
return (
<ConfigProvider>
<BrowserRouter>
<AppShell />
</BrowserRouter>
<AuthProvider>
<BrowserRouter>
<AppRoutes />
</BrowserRouter>
</AuthProvider>
</ConfigProvider>
)
}
@@ -0,0 +1,14 @@
import { Navigate, Outlet, useSearchParams } from 'react-router-dom'
import { useAuthStore } from '@/state/authStore'
import { safeNextPath } from '@/auth/redirects'
/** Wraps login / signup / forgot: a signed-in user goes straight to the app. */
export default function RedirectIfSignedIn() {
const status = useAuthStore((s) => s.status)
const recovery = useAuthStore((s) => s.recovery)
const [params] = useSearchParams()
if (status === 'signed_in' && !recovery) {
return <Navigate to={safeNextPath(params.get('next'))} replace />
}
return <Outlet />
}
+13
View File
@@ -0,0 +1,13 @@
import { Navigate, Outlet, useLocation } from 'react-router-dom'
import { useAuthStore } from '@/state/authStore'
import SessionLoading from './SessionLoading'
/** Wraps /app/*: waits for the session, else sends to /login with a return path. */
export default function RequireAuth() {
const status = useAuthStore((s) => s.status)
const location = useLocation()
if (status === 'loading') return <SessionLoading />
if (status === 'signed_in') return <Outlet />
const next = encodeURIComponent(location.pathname + location.search)
return <Navigate to={`/login?next=${next}`} replace />
}
@@ -0,0 +1,19 @@
import Brand from '@/components/brand/Brand'
import { useT } from '@/i18n/useT'
/** Full-screen wait while the client reads the persisted session. */
export default function SessionLoading() {
const t = useT()
return (
<div
role="status"
aria-live="polite"
className="flex min-h-dvh flex-col items-center justify-center gap-4"
>
<Brand size="lg" />
<p className="text-sm text-[var(--color-ink-muted)]">
{t('shell.loading_session')}
</p>
</div>
)
}
@@ -0,0 +1,16 @@
import { useEffect, type ReactNode } from 'react'
import { useAuthStore } from '@/state/authStore'
import { startLocaleSync } from '@/services/localeSync'
/** Starts the session subscription and the locale sync for the app lifetime. */
export function AuthProvider({ children }: { children: ReactNode }) {
useEffect(() => {
const stopAuth = useAuthStore.getState().start()
const stopSync = startLocaleSync()
return () => {
stopAuth()
stopSync()
}
}, [])
return <>{children}</>
}
+4 -1
View File
@@ -6,6 +6,7 @@ import {
type RebaseOutcome,
} from '@faunosteo/domain'
import AppHeader from '@/components/brand/AppHeader'
import HomeSpaceLink from '@/components/brand/HomeSpaceLink'
import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card'
import { importReportFromPdf, ImportError, MAX_PDF_BYTES } from '@/pdf/import'
@@ -147,7 +148,9 @@ export default function HomeRoute() {
return (
<main className="flex-1 flex flex-col">
<AppHeader />
<AppHeader>
<HomeSpaceLink />
</AppHeader>
<section className="flex-1 grid place-items-center px-4 sm:px-6">
<div className="grid gap-4 md:grid-cols-2 max-w-3xl w-full">
{noSheet && (
@@ -0,0 +1,35 @@
import PersonalInfoForm from '@/components/account/PersonalInfoForm'
import PreferencesForm from '@/components/account/PreferencesForm'
import ProfessionalInfoForm from '@/components/account/ProfessionalInfoForm'
import RoleBadges from '@/components/account/RoleBadges'
import SecurityPanel from '@/components/account/SecurityPanel'
import Notice from '@/components/ui/Notice'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
/** "Mon compte": four sections, each with its own save. */
export default function AccountRoute() {
const t = useT()
const profile = useAuthStore((s) => s.profile)
return (
<div className="space-y-6">
<header className="space-y-2">
<h1 className="font-serif text-2xl sm:text-3xl text-[var(--color-ink)]">
{t('account.title')}
</h1>
<RoleBadges />
</header>
{profile ? (
<>
<PersonalInfoForm key={`p-${profile.id}`} profile={profile} />
<ProfessionalInfoForm key={`pro-${profile.id}`} profile={profile} />
<PreferencesForm key={`pref-${profile.id}`} profile={profile} />
</>
) : (
<Notice tone="info">{t('auth.loading')}</Notice>
)}
<SecurityPanel />
</div>
)
}
@@ -0,0 +1,136 @@
import type { Profile } from '@faunosteo/supabase'
import RoleBadges from '@/components/account/RoleBadges'
import ButtonLink from '@/components/ui/ButtonLink'
import Card from '@/components/ui/Card'
import Icon from '@/components/ui/Icon'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
type Translate = ReturnType<typeof useT>
/** Profile fields the dashboard asks to complete, with their label keys. */
const COMPLETENESS: readonly { key: keyof Profile; labelKey: string }[] = [
{ key: 'first_name', labelKey: 'account.personal.first_name' },
{ key: 'last_name', labelKey: 'account.personal.last_name' },
{ key: 'professional_title', labelKey: 'account.professional.professional_title' },
{ key: 'practice_name', labelKey: 'account.professional.practice_name' },
]
function missingFields(profile: Profile | null, t: Translate): string[] {
if (!profile) return []
return COMPLETENESS.filter((f) => !profile[f.key]).map((f) => t(f.labelKey))
}
function greeting(profile: Profile | null, t: Translate): string {
const name = profile?.first_name ?? profile?.display_name
return name
? t('dashboard.greeting').replace('{name}', name)
: t('dashboard.greeting_fallback')
}
function ProfileCard({ missing }: { missing: string[] }) {
const t = useT()
const complete = missing.length === 0
return (
<Card as="section" className="p-5 sm:p-6 space-y-3">
<h2 className="font-serif text-xl">{t('dashboard.profile.title')}</h2>
<p className="text-sm text-[var(--color-ink-muted)]">
{complete ? t('dashboard.profile.complete') : t('dashboard.profile.incomplete')}
</p>
{!complete && (
<p className="text-sm">
<span className="text-[var(--color-ink-muted)]">
{t('dashboard.profile.missing_label')}
</span>{' '}
{missing.join(', ')}
</p>
)}
<ButtonLink to="/app/account" variant={complete ? 'secondary' : 'primary'}>
{complete ? t('dashboard.profile.cta_view') : t('dashboard.profile.cta_complete')}
</ButtonLink>
</Card>
)
}
function ToolCard() {
const t = useT()
return (
<Card as="section" className="p-5 sm:p-6 space-y-3">
<h2 className="font-serif text-xl">{t('dashboard.tool.title')}</h2>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('dashboard.tool.description')}
</p>
<div className="flex flex-wrap gap-2">
<ButtonLink to="/new" variant="secondary">
{t('dashboard.tool.cta_new')}
</ButtonLink>
<ButtonLink to="/" variant="ghost">
{t('dashboard.tool.cta_import')}
</ButtonLink>
</div>
</Card>
)
}
function AccountCard() {
const t = useT()
const user = useAuthStore((s) => s.user)
const roles = useAuthStore((s) => s.roles)
const locale = useLocaleStore((s) => s.locale)
const verified = Boolean(user?.email_confirmed_at)
const created = user?.created_at
? new Date(user.created_at).toLocaleDateString(locale)
: null
return (
<Card as="section" className="p-5 sm:p-6 space-y-3">
<h2 className="font-serif text-xl">{t('dashboard.account.title')}</h2>
<dl className="grid gap-2 text-sm">
<div className="flex justify-between gap-4">
<dt className="text-[var(--color-ink-muted)]">{t('dashboard.account.email')}</dt>
<dd className="truncate">{user?.email}</dd>
</div>
<div className="flex items-center justify-end gap-1.5 text-[var(--color-ink-muted)]">
<Icon name={verified ? 'check' : 'alert'} size={16} />
<span>{verified ? t('dashboard.account.verified') : t('dashboard.account.unverified')}</span>
</div>
<div className="flex justify-between gap-4">
<dt className="text-[var(--color-ink-muted)]">{t('dashboard.account.language')}</dt>
<dd>{t(`lang.${locale}`)}</dd>
</div>
<div className="flex justify-between gap-4">
<dt className="text-[var(--color-ink-muted)]">{t('dashboard.account.roles')}</dt>
<dd>{roles.length ? <RoleBadges /> : t('dashboard.account.no_roles')}</dd>
</div>
</dl>
{created && (
<p className="text-xs text-[var(--color-ink-muted)]">
{t('dashboard.account.member_since').replace('{date}', created)}
</p>
)}
</Card>
)
}
export default function DashboardRoute() {
const t = useT()
const profile = useAuthStore((s) => s.profile)
const missing = missingFields(profile, t)
return (
<div className="space-y-6">
<header className="space-y-1">
<h1 className="font-serif text-2xl sm:text-3xl text-[var(--color-ink)]">
{greeting(profile, t)}
</h1>
<p className="max-w-prose text-sm text-[var(--color-ink-muted)]">
{t('dashboard.intro')}
</p>
</header>
<div className="grid gap-4 md:grid-cols-2">
<ProfileCard missing={missing} />
<ToolCard />
<AccountCard />
</div>
</div>
)
}
@@ -0,0 +1,34 @@
import { Navigate, useSearchParams } from 'react-router-dom'
import AuthLayout from '@/components/auth/AuthLayout'
import AuthLink from '@/components/auth/AuthLink'
import Notice from '@/components/ui/Notice'
import SessionLoading from '@/app/guards/SessionLoading'
import { APP_HOME_PATH, safeNextPath } from '@/auth/redirects'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
/**
* Landing of OAuth redirects and email confirmation links. The client reads
* the URL on start; this route only waits for the outcome.
*/
export default function AuthCallbackRoute() {
const t = useT()
const status = useAuthStore((s) => s.status)
const urlFailure = useAuthStore((s) => s.urlFailure)
const [params] = useSearchParams()
if (status === 'signed_in') {
return <Navigate to={safeNextPath(params.get('next'), APP_HOME_PATH)} replace />
}
const providerError = params.get('error_description') ?? params.get('error')
if (status === 'loading' && !urlFailure && !providerError) {
return <SessionLoading />
}
// Landing here without a session means the exchange failed, whatever the client reported.
return (
<AuthLayout title={t('auth.callback.failed_title')}>
<Notice tone="error">{t('auth.callback.failed_description')}</Notice>
<AuthLink to="/login">{t('auth.callback.retry')}</AuthLink>
</AuthLayout>
)
}
@@ -0,0 +1,97 @@
import { useState, type FormEvent } from 'react'
import { sendPasswordReset } from '@faunosteo/supabase'
import AuthLayout from '@/components/auth/AuthLayout'
import AuthLink from '@/components/auth/AuthLink'
import UnavailableNotice from '@/components/auth/UnavailableNotice'
import Button from '@/components/ui/Button'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Input from '@/components/ui/Input'
import Notice from '@/components/ui/Notice'
import { absoluteUrl, RESET_PASSWORD_PATH } from '@/auth/redirects'
import { emailSchema } from '@/auth/validation'
import { useAuthFailureMessage } from '@/auth/useAuthFailureMessage'
import { getSupabaseClient } from '@/lib/supabase'
import { useT } from '@/i18n/useT'
export default function ForgotPasswordRoute() {
const t = useT()
const describe = useAuthFailureMessage()
const client = getSupabaseClient()
const [email, setEmail] = useState('')
const [error, setError] = useState<string | null>(null)
const [failure, setFailure] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [sentTo, setSentTo] = useState<string | null>(null)
async function submit(e: FormEvent) {
e.preventDefault()
if (!client) return
const parsed = emailSchema.safeParse(email)
if (!parsed.success) {
setError(parsed.error.issues[0]?.message ?? 'auth.error.email_invalid')
return
}
setError(null)
setFailure(null)
setBusy(true)
try {
await sendPasswordReset(client, parsed.data, absoluteUrl(RESET_PASSWORD_PATH))
setSentTo(parsed.data)
} catch (err) {
setFailure(describe(err))
setBusy(false)
}
}
const footer = (
<p>
<AuthLink to="/login">{t('auth.forgot.back_to_login')}</AuthLink>
</p>
)
if (sentTo) {
return (
<AuthLayout title={t('auth.forgot.sent_title')} footer={footer}>
<Notice tone="success">
{t('auth.forgot.sent_description').replace('{email}', sentTo)}
</Notice>
</AuthLayout>
)
}
return (
<AuthLayout
title={t('auth.forgot.title')}
subtitle={t('auth.forgot.subtitle')}
footer={client ? footer : undefined}
>
{!client ? (
<UnavailableNotice />
) : (
<form onSubmit={submit} noValidate className="space-y-4">
<FormField
id="forgot-email"
label={t('auth.email')}
error={error ? t(error) : undefined}
>
<Input
id="forgot-email"
type="email"
autoComplete="email"
inputMode="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
aria-invalid={Boolean(error)}
aria-describedby={fieldDescribedBy('forgot-email', undefined, error ?? undefined)}
required
/>
</FormField>
{failure && <Notice tone="error">{failure}</Notice>}
<Button type="submit" size="lg" className="w-full" disabled={busy}>
{busy ? t('auth.forgot.submitting') : t('auth.forgot.submit')}
</Button>
</form>
)}
</AuthLayout>
)
}
+115
View File
@@ -0,0 +1,115 @@
import { useState, type FormEvent } from 'react'
import { useNavigate, useSearchParams } from 'react-router-dom'
import { signInWithPassword } from '@faunosteo/supabase'
import AuthLayout from '@/components/auth/AuthLayout'
import AuthLink from '@/components/auth/AuthLink'
import OAuthButtons from '@/components/auth/OAuthButtons'
import PasswordField from '@/components/auth/PasswordField'
import UnavailableNotice from '@/components/auth/UnavailableNotice'
import Button from '@/components/ui/Button'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Input from '@/components/ui/Input'
import Notice from '@/components/ui/Notice'
import { safeNextPath } from '@/auth/redirects'
import { fieldErrors, loginSchema, type FieldErrors } from '@/auth/validation'
import { useAuthFailureMessage } from '@/auth/useAuthFailureMessage'
import { getSupabaseClient } from '@/lib/supabase'
import { useT } from '@/i18n/useT'
type LoginValues = { email: string; password: string }
export default function LoginRoute() {
const t = useT()
const navigate = useNavigate()
const [params] = useSearchParams()
const describe = useAuthFailureMessage()
const client = getSupabaseClient()
const [values, setValues] = useState<LoginValues>({ email: '', password: '' })
const [errors, setErrors] = useState<FieldErrors<LoginValues>>({})
const [failure, setFailure] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
async function submit(e: FormEvent) {
e.preventDefault()
if (!client) return
const parsed = loginSchema.safeParse(values)
if (!parsed.success) {
setErrors(fieldErrors(parsed.error))
return
}
setErrors({})
setFailure(null)
setBusy(true)
try {
await signInWithPassword(client, parsed.data)
navigate(safeNextPath(params.get('next')), { replace: true })
} catch (err) {
setFailure(describe(err))
setBusy(false)
}
}
const footer = (
<p>
{t('auth.login.no_account')}{' '}
<AuthLink to="/signup">{t('auth.login.signup_link')}</AuthLink>
</p>
)
return (
<AuthLayout
title={t('auth.login.title')}
subtitle={t('auth.login.subtitle')}
footer={client ? footer : undefined}
>
{!client ? (
<UnavailableNotice />
) : (
<>
<OAuthButtons />
<form onSubmit={submit} noValidate className="space-y-4">
<FormField
id="login-email"
label={t('auth.email')}
error={errors.email && t(errors.email)}
>
<Input
id="login-email"
type="email"
autoComplete="email"
inputMode="email"
value={values.email}
onChange={(e) => setValues({ ...values, email: e.target.value })}
aria-invalid={Boolean(errors.email)}
aria-describedby={fieldDescribedBy('login-email', undefined, errors.email)}
required
/>
</FormField>
<FormField
id="login-password"
label={t('auth.password')}
error={errors.password && t(errors.password)}
>
<PasswordField
id="login-password"
autoComplete="current-password"
value={values.password}
onChange={(e) => setValues({ ...values, password: e.target.value })}
aria-invalid={Boolean(errors.password)}
aria-describedby={fieldDescribedBy('login-password', undefined, errors.password)}
required
/>
</FormField>
{failure && <Notice tone="error">{failure}</Notice>}
<Button type="submit" size="lg" className="w-full" disabled={busy}>
{busy ? t('auth.login.submitting') : t('auth.login.submit')}
</Button>
<p className="text-center text-sm">
<AuthLink to="/forgot-password">{t('auth.login.forgot')}</AuthLink>
</p>
</form>
</>
)}
</AuthLayout>
)
}
@@ -0,0 +1,131 @@
import { useState, type FormEvent } from 'react'
import { useNavigate } from 'react-router-dom'
import { updatePassword } from '@faunosteo/supabase'
import AuthLayout from '@/components/auth/AuthLayout'
import AuthLink from '@/components/auth/AuthLink'
import PasswordField from '@/components/auth/PasswordField'
import UnavailableNotice from '@/components/auth/UnavailableNotice'
import Button from '@/components/ui/Button'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Notice from '@/components/ui/Notice'
import SessionLoading from '@/app/guards/SessionLoading'
import { APP_HOME_PATH } from '@/auth/redirects'
import {
fieldErrors,
newPasswordSchema,
PASSWORD_MIN_LENGTH,
type FieldErrors,
} from '@/auth/validation'
import { useAuthFailureMessage } from '@/auth/useAuthFailureMessage'
import { getSupabaseClient } from '@/lib/supabase'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
type Values = { password: string; passwordConfirm: string }
function NoSession() {
const t = useT()
return (
<AuthLayout
title={t('auth.reset.no_session_title')}
footer={
<p>
<AuthLink to="/login">{t('auth.forgot.back_to_login')}</AuthLink>
</p>
}
>
<Notice tone="error">{t('auth.reset.no_session_description')}</Notice>
<AuthLink to="/forgot-password">{t('auth.reset.request_again')}</AuthLink>
</AuthLayout>
)
}
/**
* Landing of the recovery link. The client exchanges the code on load and
* emits PASSWORD_RECOVERY; any signed-in user may also change their password here.
*/
export default function ResetPasswordRoute() {
const t = useT()
const navigate = useNavigate()
const describe = useAuthFailureMessage()
const client = getSupabaseClient()
const status = useAuthStore((s) => s.status)
const clearRecovery = useAuthStore((s) => s.clearRecovery)
const [values, setValues] = useState<Values>({ password: '', passwordConfirm: '' })
const [errors, setErrors] = useState<FieldErrors<Values>>({})
const [failure, setFailure] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
async function submit(e: FormEvent) {
e.preventDefault()
if (!client) return
const parsed = newPasswordSchema.safeParse(values)
if (!parsed.success) {
setErrors(fieldErrors(parsed.error))
return
}
setErrors({})
setFailure(null)
setBusy(true)
try {
await updatePassword(client, parsed.data.password)
clearRecovery()
navigate(APP_HOME_PATH, { replace: true })
} catch (err) {
setFailure(describe(err))
setBusy(false)
}
}
if (!client) {
return (
<AuthLayout title={t('auth.reset.title')}>
<UnavailableNotice />
</AuthLayout>
)
}
if (status === 'loading') return <SessionLoading />
if (status !== 'signed_in') return <NoSession />
return (
<AuthLayout title={t('auth.reset.title')} subtitle={t('auth.reset.subtitle')}>
<form onSubmit={submit} noValidate className="space-y-4">
<FormField
id="reset-password"
label={t('auth.password')}
hint={t('auth.password_hint').replace('{min}', String(PASSWORD_MIN_LENGTH))}
error={errors.password && t(errors.password)}
>
<PasswordField
id="reset-password"
autoComplete="new-password"
value={values.password}
onChange={(e) => setValues({ ...values, password: e.target.value })}
aria-invalid={Boolean(errors.password)}
aria-describedby={fieldDescribedBy('reset-password', 'hint', errors.password)}
required
/>
</FormField>
<FormField
id="reset-password-confirm"
label={t('auth.password_confirm')}
error={errors.passwordConfirm && t(errors.passwordConfirm)}
>
<PasswordField
id="reset-password-confirm"
autoComplete="new-password"
value={values.passwordConfirm}
onChange={(e) => setValues({ ...values, passwordConfirm: e.target.value })}
aria-invalid={Boolean(errors.passwordConfirm)}
aria-describedby={fieldDescribedBy('reset-password-confirm', undefined, errors.passwordConfirm)}
required
/>
</FormField>
{failure && <Notice tone="error">{failure}</Notice>}
<Button type="submit" size="lg" className="w-full" disabled={busy}>
{busy ? t('auth.reset.submitting') : t('auth.reset.submit')}
</Button>
</form>
</AuthLayout>
)
}
@@ -0,0 +1,200 @@
import { useState, type FormEvent } from 'react'
import { signUpWithPassword } from '@faunosteo/supabase'
import AuthLayout from '@/components/auth/AuthLayout'
import AuthLink from '@/components/auth/AuthLink'
import OAuthButtons from '@/components/auth/OAuthButtons'
import PasswordField from '@/components/auth/PasswordField'
import UnavailableNotice from '@/components/auth/UnavailableNotice'
import Button from '@/components/ui/Button'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Input from '@/components/ui/Input'
import Notice from '@/components/ui/Notice'
import { absoluteUrl, AUTH_CALLBACK_PATH } from '@/auth/redirects'
import {
fieldErrors,
PASSWORD_MIN_LENGTH,
signupSchema,
type FieldErrors,
} from '@/auth/validation'
import { useAuthFailureMessage } from '@/auth/useAuthFailureMessage'
import { getSupabaseClient } from '@/lib/supabase'
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
type SignupValues = {
displayName: string
email: string
password: string
passwordConfirm: string
}
const EMPTY: SignupValues = {
displayName: '',
email: '',
password: '',
passwordConfirm: '',
}
function CheckInbox({ email }: { email: string }) {
const t = useT()
return (
<AuthLayout
title={t('auth.signup.check_inbox_title')}
footer={
<p>
<AuthLink to="/login">{t('auth.signup.login_link')}</AuthLink>
</p>
}
>
<Notice tone="success">
{t('auth.signup.check_inbox_description').replace('{email}', email)}
</Notice>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('auth.signup.check_inbox_spam')}
</p>
</AuthLayout>
)
}
export default function SignupRoute() {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const describe = useAuthFailureMessage()
const client = getSupabaseClient()
const [values, setValues] = useState<SignupValues>(EMPTY)
const [errors, setErrors] = useState<FieldErrors<SignupValues>>({})
const [failure, setFailure] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [sentTo, setSentTo] = useState<string | null>(null)
function field<K extends keyof SignupValues>(key: K) {
return (e: React.ChangeEvent<HTMLInputElement>) =>
setValues((v) => ({ ...v, [key]: e.target.value }))
}
async function submit(e: FormEvent) {
e.preventDefault()
if (!client) return
const parsed = signupSchema.safeParse(values)
if (!parsed.success) {
setErrors(fieldErrors(parsed.error))
return
}
setErrors({})
setFailure(null)
setBusy(true)
try {
await signUpWithPassword(client, {
email: parsed.data.email,
password: parsed.data.password,
displayName: parsed.data.displayName,
locale,
emailRedirectTo: absoluteUrl(AUTH_CALLBACK_PATH),
})
setSentTo(parsed.data.email)
} catch (err) {
setFailure(describe(err))
setBusy(false)
}
}
if (sentTo) return <CheckInbox email={sentTo} />
const footer = (
<p>
{t('auth.signup.have_account')}{' '}
<AuthLink to="/login">{t('auth.signup.login_link')}</AuthLink>
</p>
)
const passwordHint = t('auth.password_hint').replace(
'{min}',
String(PASSWORD_MIN_LENGTH),
)
return (
<AuthLayout
title={t('auth.signup.title')}
subtitle={t('auth.signup.subtitle')}
footer={client ? footer : undefined}
>
{!client ? (
<UnavailableNotice />
) : (
<>
<OAuthButtons />
<form onSubmit={submit} noValidate className="space-y-4">
<FormField
id="signup-name"
label={t('auth.signup.display_name')}
hint={t('auth.signup.display_name_hint')}
error={errors.displayName && t(errors.displayName)}
>
<Input
id="signup-name"
autoComplete="name"
value={values.displayName}
onChange={field('displayName')}
aria-invalid={Boolean(errors.displayName)}
aria-describedby={fieldDescribedBy('signup-name', 'hint', errors.displayName)}
required
maxLength={80}
/>
</FormField>
<FormField
id="signup-email"
label={t('auth.email')}
error={errors.email && t(errors.email)}
>
<Input
id="signup-email"
type="email"
autoComplete="email"
inputMode="email"
value={values.email}
onChange={field('email')}
aria-invalid={Boolean(errors.email)}
aria-describedby={fieldDescribedBy('signup-email', undefined, errors.email)}
required
/>
</FormField>
<FormField
id="signup-password"
label={t('auth.password')}
hint={passwordHint}
error={errors.password && t(errors.password)}
>
<PasswordField
id="signup-password"
autoComplete="new-password"
value={values.password}
onChange={field('password')}
aria-invalid={Boolean(errors.password)}
aria-describedby={fieldDescribedBy('signup-password', 'hint', errors.password)}
required
/>
</FormField>
<FormField
id="signup-password-confirm"
label={t('auth.password_confirm')}
error={errors.passwordConfirm && t(errors.passwordConfirm)}
>
<PasswordField
id="signup-password-confirm"
autoComplete="new-password"
value={values.passwordConfirm}
onChange={field('passwordConfirm')}
aria-invalid={Boolean(errors.passwordConfirm)}
aria-describedby={fieldDescribedBy('signup-password-confirm', undefined, errors.passwordConfirm)}
required
/>
</FormField>
{failure && <Notice tone="error">{failure}</Notice>}
<Button type="submit" size="lg" className="w-full" disabled={busy}>
{busy ? t('auth.signup.submitting') : t('auth.signup.submit')}
</Button>
</form>
</>
)}
</AuthLayout>
)
}
+29
View File
@@ -0,0 +1,29 @@
/** Absolute URLs the auth emails and OAuth providers come back to. */
export const AUTH_CALLBACK_PATH = '/auth/callback'
export const RESET_PASSWORD_PATH = '/reset-password'
export const APP_HOME_PATH = '/app'
export function absoluteUrl(path: string): string {
return new URL(path, window.location.origin).toString()
}
/** Sentinel origin: anything that resolves elsewhere is not a path. */
const PROBE_ORIGIN = 'http://next.invalid'
/**
* The `next` query value is only honoured when it is a same-origin path.
* Resolving it against a sentinel origin catches every escape the URL
* parser knows (scheme, `//host`, `/\host`, tab/newline-stripped forms);
* the returned value is rebuilt from the parsed parts, never the raw string.
*/
export function safeNextPath(raw: string | null, fallback = APP_HOME_PATH) {
if (!raw || !raw.startsWith('/')) return fallback
let url: URL
try {
url = new URL(raw, PROBE_ORIGIN)
} catch {
return fallback
}
if (url.origin !== PROBE_ORIGIN) return fallback
return url.pathname + url.search + url.hash
}
@@ -0,0 +1,12 @@
import { AuthFailure, ProfileError } from '@faunosteo/supabase'
import { useT } from '@/i18n/useT'
/** One sentence per failure kind; anything else is the generic line. */
export function useAuthFailureMessage(): (error: unknown) => string {
const t = useT()
return (error) => {
if (error instanceof AuthFailure) return t(`auth.failure.${error.kind}`)
if (error instanceof ProfileError) return t('account.error.save_failed')
return t('auth.failure.unknown')
}
}
+63
View File
@@ -0,0 +1,63 @@
import { z } from 'zod'
/**
* Mirrors supabase/config.toml: minimum_password_length = 12,
* password_requirements = "lower_upper_letters_digits". Issue messages are
* i18n keys; the forms translate them next to the field.
*/
export const PASSWORD_MIN_LENGTH = 12
export const emailSchema = z
.string()
.trim()
.min(1, 'auth.error.email_required')
.email('auth.error.email_invalid')
export const passwordSchema = z
.string()
.min(PASSWORD_MIN_LENGTH, 'auth.error.password_rules')
.regex(/[a-z]/, 'auth.error.password_rules')
.regex(/[A-Z]/, 'auth.error.password_rules')
.regex(/[0-9]/, 'auth.error.password_rules')
export const displayNameSchema = z
.string()
.trim()
.min(1, 'auth.error.display_name_required')
.max(80, 'auth.error.display_name_too_long')
export const loginSchema = z.object({
email: emailSchema,
password: z.string().min(1, 'auth.error.password_required'),
})
export const signupSchema = z
.object({
displayName: displayNameSchema,
email: emailSchema,
password: passwordSchema,
passwordConfirm: z.string(),
})
.refine((v) => v.password === v.passwordConfirm, {
message: 'auth.error.password_mismatch',
path: ['passwordConfirm'],
})
export const newPasswordSchema = z
.object({ password: passwordSchema, passwordConfirm: z.string() })
.refine((v) => v.password === v.passwordConfirm, {
message: 'auth.error.password_mismatch',
path: ['passwordConfirm'],
})
export type FieldErrors<T> = Partial<Record<keyof T & string, string>>
/** First issue per field, as an i18n key. */
export function fieldErrors<T>(error: z.ZodError<T>): FieldErrors<T> {
const out: Record<string, string> = {}
for (const issue of error.issues) {
const field = String(issue.path[0] ?? '')
if (field && !out[field]) out[field] = issue.message
}
return out as FieldErrors<T>
}
@@ -0,0 +1,74 @@
import type { Profile } from '@faunosteo/supabase'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Input from '@/components/ui/Input'
import SaveRow from './SaveRow'
import SectionCard from './SectionCard'
import { personalPatch, personalSchema, translateFieldError, type PersonalValues } from '@/account/validation'
import { useProfileForm } from '@/account/useProfileForm'
import { useT } from '@/i18n/useT'
function initialValues(profile: Profile): PersonalValues {
return {
display_name: profile.display_name,
first_name: profile.first_name ?? '',
last_name: profile.last_name ?? '',
phone: profile.phone ?? '',
}
}
export default function PersonalInfoForm({ profile }: { profile: Profile }) {
const t = useT()
const form = useProfileForm(initialValues(profile), personalSchema, personalPatch)
const err = (key: keyof PersonalValues) => translateFieldError(t, form.errors[key])
return (
<SectionCard
id="personal"
title={t('account.personal.title')}
description={t('account.personal.description')}
>
<form onSubmit={form.submit} noValidate className="space-y-4">
<FormField id="display_name" label={t('account.personal.display_name')} error={err('display_name')}>
<Input
id="display_name"
value={form.values.display_name}
onChange={form.field('display_name')}
autoComplete="nickname"
maxLength={80}
aria-invalid={Boolean(form.errors.display_name)}
aria-describedby={fieldDescribedBy('display_name', undefined, form.errors.display_name)}
required
/>
</FormField>
<div className="grid gap-4 sm:grid-cols-2">
<FormField id="first_name" label={t('account.personal.first_name')} optional={t('account.optional')} error={err('first_name')}>
<Input id="first_name" value={form.values.first_name} onChange={form.field('first_name')} autoComplete="given-name" maxLength={80} />
</FormField>
<FormField id="last_name" label={t('account.personal.last_name')} optional={t('account.optional')} error={err('last_name')}>
<Input id="last_name" value={form.values.last_name} onChange={form.field('last_name')} autoComplete="family-name" maxLength={80} />
</FormField>
</div>
<FormField
id="phone"
label={t('account.personal.phone')}
optional={t('account.optional')}
hint={t('account.personal.phone_hint')}
error={err('phone')}
>
<Input
id="phone"
type="tel"
inputMode="tel"
autoComplete="tel"
placeholder="+33612345678"
value={form.values.phone}
onChange={form.field('phone')}
aria-invalid={Boolean(form.errors.phone)}
aria-describedby={fieldDescribedBy('phone', 'hint', form.errors.phone)}
/>
</FormField>
<SaveRow state={form.state} />
</form>
</SectionCard>
)
}
@@ -0,0 +1,80 @@
import type { Profile } from '@faunosteo/supabase'
import FormField from '@/components/ui/FormField'
import Select from '@/components/ui/Select'
import SaveRow from './SaveRow'
import SectionCard from './SectionCard'
import {
preferencesPatch,
preferencesSchema,
translateFieldError,
} from '@/account/validation'
import { useProfileForm } from '@/account/useProfileForm'
import { useLocaleStore } from '@/state/localeStore'
import type { Locale } from '@/i18n/types'
import { useT } from '@/i18n/useT'
const LOCALES: { value: Locale; labelKey: string }[] = [
{ value: 'fr', labelKey: 'lang.switch_to_fr' },
{ value: 'en', labelKey: 'lang.switch_to_en' },
]
/** Browser list when available, else the current value alone. */
function timezoneOptions(current: string): string[] {
const intl = Intl as unknown as { supportedValuesOf?: (key: string) => string[] }
const list = intl.supportedValuesOf?.('timeZone') ?? []
return list.includes(current) ? list : [current, ...list]
}
/**
* Language is saved through the locale store (the sync writes profiles.locale)
* so switching here and in the header behave the same. Timezone saves directly.
*/
export default function PreferencesForm({ profile }: { profile: Profile }) {
const t = useT()
const locale = useLocaleStore((s) => s.locale)
const setLocale = useLocaleStore((s) => s.setLocale)
const form = useProfileForm(
{ timezone: profile.timezone },
preferencesSchema,
preferencesPatch,
)
return (
<SectionCard
id="preferences"
title={t('account.preferences.title')}
description={t('account.preferences.description')}
>
<form onSubmit={form.submit} noValidate className="space-y-4">
<FormField id="locale" label={t('account.preferences.language')}>
<Select
id="locale"
value={locale}
onChange={(e) => setLocale(e.target.value as Locale)}
>
{LOCALES.map((item) => (
<option key={item.value} value={item.value}>
{t(item.labelKey)}
</option>
))}
</Select>
</FormField>
<FormField
id="timezone"
label={t('account.preferences.timezone')}
hint={t('account.preferences.timezone_hint')}
error={translateFieldError(t, form.errors.timezone)}
>
<Select id="timezone" value={form.values.timezone} onChange={form.field('timezone')}>
{timezoneOptions(form.values.timezone).map((tz) => (
<option key={tz} value={tz}>
{tz}
</option>
))}
</Select>
</FormField>
<SaveRow state={form.state} />
</form>
</SectionCard>
)
}
@@ -0,0 +1,85 @@
import type { Profile } from '@faunosteo/supabase'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Input from '@/components/ui/Input'
import SaveRow from './SaveRow'
import SectionCard from './SectionCard'
import {
professionalPatch,
professionalSchema,
translateFieldError,
type ProfessionalValues,
} from '@/account/validation'
import { useProfileForm } from '@/account/useProfileForm'
import { useT } from '@/i18n/useT'
function initialValues(profile: Profile): ProfessionalValues {
return {
professional_title: profile.professional_title ?? '',
practice_name: profile.practice_name ?? '',
siret: profile.siret ?? '',
}
}
export default function ProfessionalInfoForm({ profile }: { profile: Profile }) {
const t = useT()
const form = useProfileForm(initialValues(profile), professionalSchema, professionalPatch)
const err = (key: keyof ProfessionalValues) => translateFieldError(t, form.errors[key])
return (
<SectionCard
id="professional"
title={t('account.professional.title')}
description={t('account.professional.description')}
>
<form onSubmit={form.submit} noValidate className="space-y-4">
<FormField
id="professional_title"
label={t('account.professional.professional_title')}
optional={t('account.optional')}
error={err('professional_title')}
>
<Input
id="professional_title"
value={form.values.professional_title}
onChange={form.field('professional_title')}
placeholder={t('account.professional.professional_title_placeholder')}
autoComplete="organization-title"
maxLength={80}
/>
</FormField>
<FormField
id="practice_name"
label={t('account.professional.practice_name')}
optional={t('account.optional')}
error={err('practice_name')}
>
<Input
id="practice_name"
value={form.values.practice_name}
onChange={form.field('practice_name')}
autoComplete="organization"
maxLength={120}
/>
</FormField>
<FormField
id="siret"
label={t('account.professional.siret')}
optional={t('account.optional')}
hint={t('account.professional.siret_hint')}
error={err('siret')}
>
<Input
id="siret"
inputMode="numeric"
value={form.values.siret}
onChange={form.field('siret')}
aria-invalid={Boolean(form.errors.siret)}
aria-describedby={fieldDescribedBy('siret', 'hint', form.errors.siret)}
className="tabular-nums"
/>
</FormField>
<SaveRow state={form.state} />
</form>
</SectionCard>
)
}
@@ -0,0 +1,19 @@
import Badge from '@/components/ui/Badge'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
/** Platform roles, read-only. Nothing when the account has none. */
export default function RoleBadges() {
const roles = useAuthStore((s) => s.roles)
const t = useT()
if (roles.length === 0) return null
return (
<ul className="flex flex-wrap gap-2" aria-label={t('dashboard.account.roles')}>
{roles.map((role) => (
<li key={role}>
<Badge>{t(`shell.role.${role}`)}</Badge>
</li>
))}
</ul>
)
}
@@ -0,0 +1,20 @@
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import type { SaveState } from '@/account/useProfileForm'
import { useT } from '@/i18n/useT'
/** Save button plus the outcome line of a section form. */
export default function SaveRow({ state }: { state: SaveState }) {
const t = useT()
return (
<div className="flex flex-wrap items-center gap-3 pt-1">
<Button type="submit" disabled={state === 'saving'}>
{state === 'saving' ? t('account.saving') : t('account.save')}
</Button>
{state === 'saved' && <Notice tone="success">{t('account.saved')}</Notice>}
{state === 'failed' && (
<Notice tone="error">{t('account.error.save_failed')}</Notice>
)}
</div>
)
}
@@ -0,0 +1,28 @@
import type { ReactNode } from 'react'
import Card from '@/components/ui/Card'
export interface SectionCardProps {
id: string
title: string
description?: string
children: ReactNode
}
/** One account section: heading column on large screens, content beside it. */
export default function SectionCard({ id, title, description, children }: SectionCardProps) {
return (
<Card as="section" aria-labelledby={`${id}-title`} className="p-5 sm:p-6">
<div className="grid gap-5 md:grid-cols-[14rem_1fr] md:gap-8">
<header className="space-y-1">
<h2 id={`${id}-title`} className="font-serif text-xl text-[var(--color-ink)]">
{title}
</h2>
{description && (
<p className="text-sm text-[var(--color-ink-muted)]">{description}</p>
)}
</header>
<div className="min-w-0">{children}</div>
</div>
</Card>
)
}
@@ -0,0 +1,133 @@
import { useState, type FormEvent } from 'react'
import { updatePassword } from '@faunosteo/supabase'
import PasswordField from '@/components/auth/PasswordField'
import Button from '@/components/ui/Button'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
import Notice from '@/components/ui/Notice'
import SignOutButton from '@/components/shell/SignOutButton'
import SectionCard from './SectionCard'
import {
fieldErrors,
newPasswordSchema,
PASSWORD_MIN_LENGTH,
type FieldErrors,
} from '@/auth/validation'
import { useAuthFailureMessage } from '@/auth/useAuthFailureMessage'
import { getSupabaseClient } from '@/lib/supabase'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
type Values = { password: string; passwordConfirm: string }
type State = 'idle' | 'saving' | 'saved'
function ChangePasswordForm() {
const t = useT()
const describe = useAuthFailureMessage()
const [values, setValues] = useState<Values>({ password: '', passwordConfirm: '' })
const [errors, setErrors] = useState<FieldErrors<Values>>({})
const [failure, setFailure] = useState<string | null>(null)
const [state, setState] = useState<State>('idle')
async function submit(e: FormEvent) {
e.preventDefault()
const client = getSupabaseClient()
const parsed = newPasswordSchema.safeParse(values)
if (!client) return
if (!parsed.success) {
setErrors(fieldErrors(parsed.error))
return
}
setErrors({})
setFailure(null)
setState('saving')
try {
await updatePassword(client, parsed.data.password)
setValues({ password: '', passwordConfirm: '' })
setState('saved')
} catch (err) {
setFailure(describe(err))
setState('idle')
}
}
return (
<form onSubmit={submit} noValidate className="space-y-4">
<FormField
id="new-password"
label={t('account.security.new_password')}
hint={t('auth.password_hint').replace('{min}', String(PASSWORD_MIN_LENGTH))}
error={errors.password && t(errors.password)}
>
<PasswordField
id="new-password"
autoComplete="new-password"
value={values.password}
onChange={(e) => setValues({ ...values, password: e.target.value })}
aria-invalid={Boolean(errors.password)}
aria-describedby={fieldDescribedBy('new-password', 'hint', errors.password)}
/>
</FormField>
<FormField
id="new-password-confirm"
label={t('auth.password_confirm')}
error={errors.passwordConfirm && t(errors.passwordConfirm)}
>
<PasswordField
id="new-password-confirm"
autoComplete="new-password"
value={values.passwordConfirm}
onChange={(e) => setValues({ ...values, passwordConfirm: e.target.value })}
aria-invalid={Boolean(errors.passwordConfirm)}
aria-describedby={fieldDescribedBy('new-password-confirm', undefined, errors.passwordConfirm)}
/>
</FormField>
<div className="flex flex-wrap items-center gap-3">
<Button type="submit" variant="secondary" disabled={state === 'saving'}>
{state === 'saving'
? t('account.security.changing_password')
: t('account.security.change_password')}
</Button>
{state === 'saved' && (
<Notice tone="success">{t('account.security.password_changed')}</Notice>
)}
{failure && <Notice tone="error">{failure}</Notice>}
</div>
</form>
)
}
export default function SecurityPanel() {
const t = useT()
const email = useAuthStore((s) => s.user?.email)
return (
<SectionCard
id="security"
title={t('account.security.title')}
description={t('account.security.description')}
>
<div className="space-y-6">
<div>
<p className="text-sm font-medium text-[var(--color-ink)]">
{t('account.security.email_label')}
</p>
<p className="text-sm text-[var(--color-ink-muted)]">{email}</p>
</div>
<ChangePasswordForm />
<div className="rounded-lg border border-dashed border-[var(--color-border)] p-4">
<p className="text-sm font-medium text-[var(--color-ink)]">
{t('account.security.mfa_title')}
</p>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('account.security.mfa_note')}
</p>
</div>
<div className="space-y-2 border-t border-[var(--color-border)] pt-4">
<p className="text-xs text-[var(--color-ink-muted)]">
{t('account.security.sign_out_everywhere_note')}
</p>
<SignOutButton className="-ml-3" />
</div>
</div>
</SectionCard>
)
}
@@ -0,0 +1,78 @@
import type { ReactNode } from 'react'
import { Link } from 'react-router-dom'
import Brand from '@/components/brand/Brand'
import LanguageSwitcher from '@/components/brand/LanguageSwitcher'
import Card from '@/components/ui/Card'
import { useConfig } from '@/app/providers/ConfigProvider'
import { useT } from '@/i18n/useT'
export interface AuthLayoutProps {
title: string
subtitle?: string
children: ReactNode
/** Links under the card (switch between login / signup, back links). */
footer?: ReactNode
}
/**
* Two columns on large screens: a warm brand panel and the form card. On
* small screens the panel collapses to the logo above the card.
*/
export default function AuthLayout({
title,
subtitle,
children,
footer,
}: AuthLayoutProps) {
const cfg = useConfig()
const t = useT()
return (
<div className="flex min-h-dvh flex-col lg:flex-row">
<aside className="hidden lg:flex lg:w-[42%] lg:flex-col lg:justify-between bg-[var(--color-surface-strong)] px-12 py-10">
<Link to="/" aria-label={t('common.home')} className="w-fit">
<Brand size="lg" />
</Link>
<div className="max-w-md space-y-4">
<p className="font-serif text-3xl leading-tight text-[var(--color-ink)]">
{t('auth.brand_claim')}
</p>
<p className="text-sm leading-relaxed text-[var(--color-ink-muted)]">
{t('auth.brand_note')}
</p>
</div>
<p className="text-xs text-[var(--color-ink-muted)]">{cfg.tagline}</p>
</aside>
<main className="flex flex-1 flex-col px-4 py-6 sm:px-8 sm:py-10">
<div className="flex items-center justify-between lg:justify-end">
<Link to="/" aria-label={t('common.home')} className="lg:hidden">
<Brand size="md" />
</Link>
<LanguageSwitcher />
</div>
<div className="flex flex-1 items-center justify-center py-8">
<div className="w-full max-w-md space-y-5">
<Card as="section" className="p-6 sm:p-8 space-y-6">
<header className="space-y-1">
<h1 className="font-serif text-2xl sm:text-3xl text-[var(--color-ink)] [text-wrap:balance]">
{title}
</h1>
{subtitle && (
<p className="text-sm text-[var(--color-ink-muted)]">
{subtitle}
</p>
)}
</header>
{children}
</Card>
{footer && (
<div className="text-center text-sm text-[var(--color-ink-muted)] space-y-1">
{footer}
</div>
)}
</div>
</div>
</main>
</div>
)
}
+11
View File
@@ -0,0 +1,11 @@
import { Link, type LinkProps } from 'react-router-dom'
/** Accent link used under the auth cards. */
export default function AuthLink({ className = '', ...rest }: LinkProps) {
return (
<Link
className={`font-medium text-[var(--color-accent)] underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] rounded ${className}`}
{...rest}
/>
)
}
@@ -0,0 +1,65 @@
import { useState } from 'react'
import { signInWithOAuth, type OAuthProvider } from '@faunosteo/supabase'
import Button from '@/components/ui/Button'
import Icon from '@/components/ui/Icon'
import Notice from '@/components/ui/Notice'
import { useConfig } from '@/app/providers/ConfigProvider'
import { getSupabaseClient } from '@/lib/supabase'
import { absoluteUrl, AUTH_CALLBACK_PATH } from '@/auth/redirects'
import { useAuthFailureMessage } from '@/auth/useAuthFailureMessage'
import { useT } from '@/i18n/useT'
const LABEL: Record<OAuthProvider, string> = {
google: 'auth.continue_with_google',
apple: 'auth.continue_with_apple',
}
/** One button per configured provider, with the "or" rule under them. Nothing when none is configured. */
export default function OAuthButtons() {
const { authProviders } = useConfig()
const t = useT()
const describe = useAuthFailureMessage()
const [error, setError] = useState<string | null>(null)
const [pending, setPending] = useState<OAuthProvider | null>(null)
if (authProviders.length === 0) return null
async function start(provider: OAuthProvider) {
const client = getSupabaseClient()
if (!client) return
setPending(provider)
setError(null)
try {
await signInWithOAuth(client, provider, absoluteUrl(AUTH_CALLBACK_PATH))
} catch (err) {
setError(describe(err))
setPending(null)
}
}
return (
<div className="space-y-3">
<div className="grid gap-2">
{authProviders.map((provider) => (
<Button
key={provider}
type="button"
variant="secondary"
onClick={() => start(provider)}
disabled={pending !== null}
className="gap-2"
>
<Icon name={provider} size={18} />
{t(LABEL[provider])}
</Button>
))}
</div>
{error && <Notice tone="error">{error}</Notice>}
<div className="flex items-center gap-3 text-xs text-[var(--color-ink-muted)]">
<span className="h-px flex-1 bg-[var(--color-border)]" />
{t('auth.or')}
<span className="h-px flex-1 bg-[var(--color-border)]" />
</div>
</div>
)
}
@@ -0,0 +1,30 @@
import { useState, type InputHTMLAttributes } from 'react'
import Input from '@/components/ui/Input'
import Icon from '@/components/ui/Icon'
import { useT } from '@/i18n/useT'
type Props = Omit<InputHTMLAttributes<HTMLInputElement>, 'type'>
/** Password input with a show/hide toggle; the toggle is a labelled button. */
export default function PasswordField({ className = '', ...rest }: Props) {
const [visible, setVisible] = useState(false)
const t = useT()
return (
<div className="relative">
<Input
type={visible ? 'text' : 'password'}
className={`pr-11 ${className}`}
{...rest}
/>
<button
type="button"
onClick={() => setVisible((v) => !v)}
aria-label={visible ? t('auth.hide_password') : t('auth.show_password')}
aria-pressed={visible}
className="absolute inset-y-0 right-0 flex w-11 items-center justify-center rounded-r-lg text-[var(--color-ink-muted)] hover:text-[var(--color-ink)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
<Icon name={visible ? 'eye-off' : 'eye'} />
</button>
</div>
)
}
@@ -0,0 +1,21 @@
import { useNavigate } from 'react-router-dom'
import Button from '@/components/ui/Button'
import Notice from '@/components/ui/Notice'
import { useT } from '@/i18n/useT'
/** Shown on the auth screens when the deployment has no Supabase. */
export default function UnavailableNotice() {
const t = useT()
const navigate = useNavigate()
return (
<div className="space-y-4">
<Notice tone="info">
<p className="font-medium">{t('auth.unavailable_title')}</p>
<p>{t('auth.unavailable_description')}</p>
</Notice>
<Button variant="secondary" onClick={() => navigate('/')}>
{t('auth.back_to_tool')}
</Button>
</div>
)
}
@@ -0,0 +1,25 @@
import ButtonLink from '@/components/ui/ButtonLink'
import { useConfig } from '@/app/providers/ConfigProvider'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
/**
* Header entry to the signed-in space, only when a backend is configured:
* "Mon espace" for a signed-in user, "Se connecter" otherwise.
*/
export default function HomeSpaceLink() {
const { supabase } = useConfig()
const status = useAuthStore((s) => s.status)
const t = useT()
if (!supabase) return null
const signedIn = status === 'signed_in'
return (
<ButtonLink
to={signedIn ? '/app' : '/login'}
variant={signedIn ? 'primary' : 'secondary'}
size="sm"
>
{signedIn ? t('home.space.open') : t('home.space.signin')}
</ButtonLink>
)
}
@@ -0,0 +1,77 @@
import { useState } from 'react'
import { Link, Outlet, useLocation } from 'react-router-dom'
import Brand from '@/components/brand/Brand'
import LanguageSwitcher from '@/components/brand/LanguageSwitcher'
import Icon from '@/components/ui/Icon'
import MobileDrawer from './MobileDrawer'
import SidebarNav, { NAV_ITEMS } from './SidebarNav'
import SignOutButton from './SignOutButton'
import UserBadge from './UserBadge'
import { useT } from '@/i18n/useT'
/** Title of the current /app page for the top bar, from the nav table. */
function pageTitleKey(pathname: string): string {
const match = NAV_ITEMS.find((item) =>
item.end ? item.to === pathname : pathname.startsWith(item.to) && item.to !== '/',
)
return match?.labelKey ?? 'shell.nav.dashboard'
}
/**
* Authenticated shell: fixed sidebar on large screens, light top bar with a
* drawer button below. The page content scrolls on its own.
*/
export default function AppLayout() {
const t = useT()
const location = useLocation()
const [drawerOpen, setDrawerOpen] = useState(false)
return (
<div className="flex min-h-dvh bg-[var(--color-bg)]">
<aside className="hidden lg:flex lg:w-64 lg:shrink-0 lg:flex-col border-r border-[var(--color-border)] bg-[var(--color-surface)]">
<div className="px-5 py-5">
<Link to="/app" aria-label={t('shell.nav.dashboard')} className="inline-block">
<Brand size="md" />
</Link>
</div>
<div className="flex-1 px-3">
<SidebarNav />
</div>
<div className="space-y-3 border-t border-[var(--color-border)] px-4 py-4">
<UserBadge />
<SignOutButton className="w-full" />
</div>
</aside>
<div className="flex min-w-0 flex-1 flex-col">
<header className="sticky top-0 z-30 flex h-14 items-center gap-3 border-b border-[var(--color-border)] bg-[var(--color-surface)]/95 px-3 backdrop-blur-sm sm:px-6 pt-[env(safe-area-inset-top)]">
<button
type="button"
onClick={() => setDrawerOpen(true)}
aria-label={t('shell.open_menu')}
aria-expanded={drawerOpen}
className="grid h-11 w-11 place-items-center rounded-lg text-[var(--color-ink)] hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)] lg:hidden"
>
<Icon name="menu" />
</button>
<Link to="/app" className="lg:hidden" aria-label={t('shell.nav.dashboard')}>
<Brand size="sm" />
</Link>
<h1 className="hidden lg:block text-sm font-medium text-[var(--color-ink-muted)]">
{t(pageTitleKey(location.pathname))}
</h1>
<div className="ml-auto flex items-center gap-2">
<LanguageSwitcher />
</div>
</header>
<main className="flex-1 px-4 py-6 sm:px-8 sm:py-8">
<div className="mx-auto w-full max-w-4xl">
<Outlet />
</div>
</main>
</div>
<MobileDrawer open={drawerOpen} onClose={() => setDrawerOpen(false)} />
</div>
)
}
@@ -0,0 +1,76 @@
import { useEffect } from 'react'
import { Link } from 'react-router-dom'
import { AnimatePresence, motion, useReducedMotion } from 'motion/react'
import Brand from '@/components/brand/Brand'
import Icon from '@/components/ui/Icon'
import SidebarNav from './SidebarNav'
import SignOutButton from './SignOutButton'
import UserBadge from './UserBadge'
import { useT } from '@/i18n/useT'
export interface MobileDrawerProps {
open: boolean
onClose: () => void
}
/** Left-side navigation drawer for small screens (transform + opacity only). */
export default function MobileDrawer({ open, onClose }: MobileDrawerProps) {
const t = useT()
const reduced = useReducedMotion()
const slide = reduced ? { x: 0 } : { x: '-100%' }
useEffect(() => {
if (!open) return
const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose()
window.addEventListener('keydown', onKey)
return () => window.removeEventListener('keydown', onKey)
}, [open, onClose])
return (
<AnimatePresence>
{open && (
<div className="fixed inset-0 z-50 lg:hidden">
<motion.div
data-testid="drawer-backdrop"
className="absolute inset-0 bg-black/40"
initial={{ opacity: 0 }}
animate={{ opacity: 1 }}
exit={{ opacity: 0 }}
transition={{ duration: 0.15 }}
onClick={onClose}
/>
<motion.aside
role="dialog"
aria-modal="true"
aria-label={t('shell.nav_label')}
initial={slide}
animate={{ x: 0 }}
exit={slide}
transition={{ duration: reduced ? 0 : 0.2, ease: 'easeOut' }}
className="absolute inset-y-0 left-0 flex w-[min(20rem,85vw)] flex-col bg-[var(--color-surface)] shadow-xl pt-[env(safe-area-inset-top)] pb-[env(safe-area-inset-bottom)]"
>
<div className="flex items-center justify-between px-4 py-3 border-b border-[var(--color-border)]">
<Link to="/app" onClick={onClose} aria-label={t('shell.nav.dashboard')}>
<Brand size="md" />
</Link>
<button
type="button"
onClick={onClose}
aria-label={t('shell.close_menu')}
className="grid h-11 w-11 place-items-center rounded-lg text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]"
>
<Icon name="close" />
</button>
</div>
<div className="flex-1 overflow-y-auto px-3 py-4">
<SidebarNav onNavigate={onClose} />
</div>
<div className="space-y-3 border-t border-[var(--color-border)] px-4 py-4">
<UserBadge />
<SignOutButton className="w-full" />
</div>
</motion.aside>
</div>
)}
</AnimatePresence>
)
}
@@ -0,0 +1,60 @@
import { NavLink } from 'react-router-dom'
import Icon, { type IconName } from '@/components/ui/Icon'
import { useT } from '@/i18n/useT'
interface NavItem {
to: string
icon: IconName
labelKey: string
hintKey?: string
end?: boolean
}
export const NAV_ITEMS: readonly NavItem[] = [
{ to: '/app', icon: 'dashboard', labelKey: 'shell.nav.dashboard', end: true },
{ to: '/app/account', icon: 'user', labelKey: 'shell.nav.account' },
{
to: '/',
icon: 'tool',
labelKey: 'shell.nav.local_tool',
hintKey: 'shell.nav.local_tool_hint',
},
]
function linkClass(active: boolean): string {
return [
'relative flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm transition-colors min-h-11',
'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent)]',
active
? 'bg-[var(--color-surface-strong)] text-[var(--color-ink)] font-medium before:absolute before:left-0 before:top-2 before:bottom-2 before:w-0.5 before:rounded-full before:bg-[var(--color-accent)]'
: 'text-[var(--color-ink-muted)] hover:bg-[var(--color-surface-strong)] hover:text-[var(--color-ink)]',
].join(' ')
}
/** The three destinations of the shell; `onNavigate` closes the mobile drawer. */
export default function SidebarNav({ onNavigate }: { onNavigate?: () => void }) {
const t = useT()
return (
<nav aria-label={t('shell.nav_label')} className="space-y-1">
{NAV_ITEMS.map((item) => (
<NavLink
key={item.to}
to={item.to}
end={item.end}
onClick={onNavigate}
className={({ isActive }) => linkClass(isActive)}
>
<Icon name={item.icon} size={20} className="shrink-0" />
<span className="flex min-w-0 flex-col leading-tight">
<span className="truncate">{t(item.labelKey)}</span>
{item.hintKey && (
<span className="truncate text-xs font-normal text-[var(--color-ink-muted)]">
{t(item.hintKey)}
</span>
)}
</span>
</NavLink>
))}
</nav>
)
}
@@ -0,0 +1,39 @@
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import Button from '@/components/ui/Button'
import Icon from '@/components/ui/Icon'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
export default function SignOutButton({ className = '' }: { className?: string }) {
const t = useT()
const navigate = useNavigate()
const signOut = useAuthStore((s) => s.signOut)
const [busy, setBusy] = useState(false)
async function onClick() {
setBusy(true)
try {
await signOut()
} catch {
// The local session is cleared either way; the server may not have revoked the others.
window.alert(t('shell.sign_out_failed'))
} finally {
// The guard would redirect anyway; going home keeps the local tool one step away.
navigate('/', { replace: true })
}
}
return (
<Button
type="button"
variant="ghost"
onClick={onClick}
disabled={busy}
className={`justify-start gap-3 text-[var(--color-ink-muted)] hover:text-[var(--color-ink)] ${className}`}
>
<Icon name="logout" size={20} />
{busy ? t('shell.signing_out') : t('shell.sign_out')}
</Button>
)
}
@@ -0,0 +1,38 @@
import { useAuthStore } from '@/state/authStore'
/** Two-letter monogram from the display name, else the email. */
export function monogram(name: string | undefined, email: string | undefined) {
const source = (name ?? '').trim() || (email ?? '').trim()
if (!source) return '?'
const parts = source.split(/\s+/).filter(Boolean)
const letters =
parts.length >= 2 ? parts[0][0] + parts[1][0] : source.slice(0, 2)
return letters.toUpperCase()
}
/** Avatar monogram + display name + email, as shown at the bottom of the sidebar. */
export default function UserBadge() {
const profile = useAuthStore((s) => s.profile)
const user = useAuthStore((s) => s.user)
const name = profile?.display_name ?? user?.email ?? ''
return (
<div className="flex items-center gap-3 min-w-0">
<span
aria-hidden="true"
className="grid h-9 w-9 shrink-0 place-items-center rounded-full bg-[var(--color-accent)] text-sm font-semibold text-white"
>
{monogram(profile?.display_name, user?.email)}
</span>
<span className="flex min-w-0 flex-col leading-tight">
<span className="truncate text-sm font-medium text-[var(--color-ink)]">
{name}
</span>
{user?.email && profile?.display_name && (
<span className="truncate text-xs text-[var(--color-ink-muted)]">
{user.email}
</span>
)}
</span>
</div>
)
}
+15 -6
View File
@@ -23,6 +23,20 @@ const SIZES: Record<NonNullable<ButtonProps['size']>, string> = {
lg: 'h-12 px-5 sm:px-6 text-base rounded-lg',
}
/** The button look, reusable by links that act as buttons (ButtonLink). */
export function buttonClassName(
variant: NonNullable<ButtonProps['variant']> = 'primary',
size: NonNullable<ButtonProps['size']> = 'md',
className = '',
): string {
return [
'inline-flex items-center justify-center font-medium transition disabled:opacity-50 disabled:cursor-not-allowed focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2',
VARIANTS[variant],
SIZES[size],
className,
].join(' ')
}
export default function Button({
variant = 'primary',
size = 'md',
@@ -32,12 +46,7 @@ export default function Button({
}: ButtonProps) {
return (
<button
className={[
'inline-flex items-center justify-center font-medium transition disabled:opacity-50 disabled:cursor-not-allowed focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-offset-2',
VARIANTS[variant],
SIZES[size],
className,
].join(' ')}
className={buttonClassName(variant, size, className)}
{...rest}
>
{children}
+17
View File
@@ -0,0 +1,17 @@
import { Link, type LinkProps } from 'react-router-dom'
import { buttonClassName, type ButtonProps } from './Button'
export interface ButtonLinkProps extends LinkProps {
variant?: ButtonProps['variant']
size?: ButtonProps['size']
}
/** A router link that looks like a Button: navigation stays a link for the browser and assistive tech. */
export default function ButtonLink({
variant = 'primary',
size = 'md',
className = '',
...rest
}: ButtonLinkProps) {
return <Link className={buttonClassName(variant, size, className)} {...rest} />
}
+54
View File
@@ -0,0 +1,54 @@
import type { ReactNode } from 'react'
import Label from './Label'
export interface FormFieldProps {
id: string
label: string
/** Rendered under the control, greyed; the error replaces it when present. */
hint?: string
error?: string
optional?: string
children: ReactNode
}
/** Describes a field for assistive tech: ids for hint and error, wired through aria-describedby. */
export function fieldDescribedBy(id: string, hint?: string, error?: string) {
const ids: string[] = []
if (error) ids.push(`${id}-error`)
else if (hint) ids.push(`${id}-hint`)
return ids.length ? ids.join(' ') : undefined
}
export default function FormField({
id,
label,
hint,
error,
optional,
children,
}: FormFieldProps) {
return (
<div className="space-y-1">
<Label htmlFor={id} className="flex items-baseline justify-between">
<span>{label}</span>
{optional && (
<span className="text-xs font-normal text-[var(--color-ink-muted)]">
{optional}
</span>
)}
</Label>
{children}
{error ? (
<p id={`${id}-error`} role="alert" className="text-sm text-[var(--color-danger)]">
{error}
</p>
) : (
hint && (
<p id={`${id}-hint`} className="text-xs text-[var(--color-ink-muted)]">
{hint}
</p>
)
)}
</div>
)
}
+63
View File
@@ -0,0 +1,63 @@
import type { SVGProps } from 'react'
export type IconName =
| 'menu'
| 'close'
| 'dashboard'
| 'user'
| 'tool'
| 'logout'
| 'eye'
| 'eye-off'
| 'check'
| 'alert'
| 'google'
| 'apple'
/** Stroke paths on a 24-unit grid; decorative by default (aria-hidden). */
const PATHS: Record<IconName, string> = {
menu: 'M4 7h16M4 12h16M4 17h16',
close: 'M6 6l12 12M18 6L6 18',
dashboard: 'M4 4h7v7H4zM13 4h7v4h-7zM13 11h7v9h-7zM4 14h7v6H4z',
user: 'M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0',
tool: 'M14 3l7 7-4 4-7-7zM10 10l-6 6 4 4 6-6M3 21l3-3',
logout: 'M10 4H5v16h5M15 8l5 4-5 4M20 12H9',
eye: 'M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z',
'eye-off':
'M3 3l18 18M10.6 10.6A3 3 0 0 0 13.4 13.4M9.9 5.2A10.5 10.5 0 0 1 12 5c6 0 10 7 10 7a17 17 0 0 1-3.2 3.9M6.1 6.1A17 17 0 0 0 2 12s4 7 10 7a10 10 0 0 0 4-.8',
check: 'M5 12l5 5L20 7',
alert: 'M12 9v4M12 17h.01M10.3 3.9L2.8 17a2 2 0 0 0 1.7 3h15a2 2 0 0 0 1.7-3L13.7 3.9a2 2 0 0 0-3.4 0z',
google:
'M21 12.2c0-.7-.1-1.3-.2-1.9H12v3.6h5.1a4.4 4.4 0 0 1-1.9 2.9v2.4h3.1c1.8-1.7 2.7-4.1 2.7-7zM12 21c2.4 0 4.5-.8 6-2.2l-3.1-2.4c-.8.6-1.8.9-2.9.9-2.3 0-4.2-1.5-4.9-3.6H4v2.5A9 9 0 0 0 12 21zM7.1 13.7a5.4 5.4 0 0 1 0-3.4V7.8H4a9 9 0 0 0 0 8.4zM12 6.6c1.3 0 2.5.5 3.4 1.3l2.6-2.6A9 9 0 0 0 4 7.8l3.1 2.5c.7-2.1 2.6-3.7 4.9-3.7z',
apple:
'M16.4 12.6c0-2.3 1.9-3.4 2-3.5a4.3 4.3 0 0 0-3.4-1.8c-1.4-.1-2.8.9-3.5.9s-1.9-.8-3.1-.8A4.6 4.6 0 0 0 4.5 9.8c-1.7 2.9-.4 7.2 1.2 9.5.8 1.1 1.7 2.4 3 2.4s1.7-.8 3.2-.8 1.9.8 3.2.8 2.2-1.2 3-2.3a10 10 0 0 0 1.3-2.8 4.1 4.1 0 0 1-3-4zM13.8 5.6A4 4 0 0 0 14.7 2.7a4.1 4.1 0 0 0-2.7 1.4 3.8 3.8 0 0 0-1 2.8 3.4 3.4 0 0 0 2.8-1.3z',
}
const FILLED: ReadonlySet<IconName> = new Set(['google', 'apple'])
export interface IconProps extends SVGProps<SVGSVGElement> {
name: IconName
size?: number
}
export default function Icon({ name, size = 20, className, ...rest }: IconProps) {
const filled = FILLED.has(name)
return (
<svg
width={size}
height={size}
viewBox="0 0 24 24"
fill={filled ? 'currentColor' : 'none'}
stroke={filled ? 'none' : 'currentColor'}
strokeWidth={1.8}
strokeLinecap="round"
strokeLinejoin="round"
aria-hidden="true"
focusable="false"
className={className}
{...rest}
>
<path d={PATHS[name]} />
</svg>
)
}
+31
View File
@@ -0,0 +1,31 @@
import type { ReactNode } from 'react'
import Icon from './Icon'
export interface NoticeProps {
tone: 'success' | 'error' | 'info'
children: ReactNode
className?: string
}
const TONE: Record<NoticeProps['tone'], string> = {
success: 'border-[var(--severity-mild)]/40 bg-[color-mix(in_srgb,var(--severity-mild)_10%,white)] text-[var(--color-ink)]',
error: 'border-[var(--color-danger)]/40 bg-[color-mix(in_srgb,var(--color-danger)_8%,white)] text-[var(--color-danger-strong)]',
info: 'border-[var(--color-border)] bg-[var(--color-surface-strong)] text-[var(--color-ink)]',
}
/** Inline status line: icon + text, never colour alone. */
export default function Notice({ tone, children, className = '' }: NoticeProps) {
return (
<div
role={tone === 'error' ? 'alert' : 'status'}
className={`flex items-start gap-2 rounded-lg border px-3 py-2 text-sm ${TONE[tone]} ${className}`}
>
<Icon
name={tone === 'success' ? 'check' : 'alert'}
size={18}
className="mt-0.5 shrink-0"
/>
<div className="min-w-0">{children}</div>
</div>
)
}
+28 -2
View File
@@ -1,5 +1,5 @@
/// <reference types="vite/client" />
import type { SupabaseConnection } from '@faunosteo/supabase'
import type { OAuthProvider, SupabaseConnection } from '@faunosteo/supabase'
/**
* Runtime application config.
@@ -15,6 +15,8 @@ export interface AppConfig {
tagline: string
/** null = no backend configured; the app keeps its local-only behaviour. */
supabase: SupabaseConnection | null
/** OAuth buttons to show on the auth screens; the server must enable the same providers. */
authProviders: OAuthProvider[]
}
/** Shape written by docker/entrypoint.sh (flat strings, empty = unset). */
@@ -25,6 +27,8 @@ export interface RuntimeConfig {
tagline?: string
supabaseUrl?: string
supabaseAnonKey?: string
/** Comma-separated: "google,apple". */
authProviders?: string
}
declare global {
@@ -33,7 +37,7 @@ declare global {
}
}
const DEFAULTS: Omit<AppConfig, 'supabase'> = {
const DEFAULTS: Omit<AppConfig, 'supabase' | 'authProviders'> = {
siteName: 'Faunosteo',
brandName: 'Faunosteo',
footerName: 'Faunosteo',
@@ -61,6 +65,25 @@ export function resolveSupabaseConnection(
return null
}
const KNOWN_PROVIDERS: readonly string[] = ['google', 'apple']
/** "google, apple" → ['google', 'apple']; unknown names are dropped (warned in DEV). */
export function resolveAuthProviders(
raw: string | undefined,
): OAuthProvider[] {
const names = (nonEmpty(raw) ?? '')
.split(',')
.map((name) => name.trim().toLowerCase())
.filter((name) => name !== '')
const known = names.filter((name): name is OAuthProvider =>
KNOWN_PROVIDERS.includes(name),
)
if (known.length !== names.length && import.meta.env.DEV) {
console.warn(`[config] unknown auth provider in "${raw}"; ignored`)
}
return [...new Set(known)]
}
export function resolveConfig(runtime: RuntimeConfig = {}): AppConfig {
return {
siteName:
@@ -81,6 +104,9 @@ export function resolveConfig(runtime: RuntimeConfig = {}): AppConfig {
runtime.supabaseUrl ?? import.meta.env.VITE_SUPABASE_URL,
runtime.supabaseAnonKey ?? import.meta.env.VITE_SUPABASE_ANON_KEY,
),
authProviders: resolveAuthProviders(
runtime.authProviders ?? import.meta.env.VITE_AUTH_PROVIDERS,
),
}
}
+195
View File
@@ -54,6 +54,9 @@ export const en: Dict = {
'home.no_sheet.description':
'This build of the application carries no anatomical sheet: no report can be created or imported.',
'home.space.signin': 'Sign in',
'home.space.open': 'My space',
// footer
'footer.all_rights_reserved': 'All rights reserved.',
'footer.powered_by': 'Powered by',
@@ -177,4 +180,196 @@ export const en: Dict = {
'lang.switch_to_en': 'Switch to English',
'lang.fr': 'FR',
'lang.en': 'EN',
// auth — shared
'auth.brand_claim': 'Your Faunosteo professional space.',
'auth.brand_note':
'The report tool stays available without an account. An account prepares what comes next: saved reports, animal follow-up, sharing with owners.',
'auth.unavailable_title': 'Signed-in space not available',
'auth.unavailable_description':
'This installation has no authentication server. The local report tool remains usable.',
'auth.back_to_tool': 'Back to the report tool',
'auth.email': 'Email address',
'auth.password': 'Password',
'auth.password_confirm': 'Confirm password',
'auth.password_hint':
'At least {min} characters, with a lowercase letter, an uppercase letter and a digit.',
'auth.show_password': 'Show password',
'auth.hide_password': 'Hide password',
'auth.or': 'or',
'auth.continue_with_google': 'Continue with Google',
'auth.continue_with_apple': 'Continue with Apple',
'auth.loading': 'Loading…',
// auth — login
'auth.login.title': 'Welcome back',
'auth.login.subtitle': 'Sign in to your space.',
'auth.login.submit': 'Sign in',
'auth.login.submitting': 'Signing in…',
'auth.login.forgot': 'Forgot your password?',
'auth.login.no_account': 'No account yet?',
'auth.login.signup_link': 'Create an account',
// auth — signup
'auth.signup.title': 'Create your account',
'auth.signup.subtitle': 'A few details, then a confirmation by email.',
'auth.signup.display_name': 'Display name',
'auth.signup.display_name_hint':
'How others will see you. You can change it later.',
'auth.signup.submit': 'Create my account',
'auth.signup.submitting': 'Creating…',
'auth.signup.have_account': 'Already have an account?',
'auth.signup.login_link': 'Sign in',
'auth.signup.check_inbox_title': 'Check your inbox',
'auth.signup.check_inbox_description':
'A confirmation link was sent to {email}. Open it to activate your account, then sign in.',
'auth.signup.check_inbox_spam':
'Nothing after a few minutes? Check your spam folder.',
// auth — forgot / reset
'auth.forgot.title': 'Forgot password',
'auth.forgot.subtitle':
'Enter your email address: we will send you a link to choose a new password.',
'auth.forgot.submit': 'Send the link',
'auth.forgot.submitting': 'Sending…',
'auth.forgot.sent_title': 'Link sent',
'auth.forgot.sent_description':
'If an account exists for {email}, an email is on its way. The link stays valid for one hour.',
'auth.forgot.back_to_login': 'Back to sign in',
'auth.reset.title': 'New password',
'auth.reset.subtitle': 'Choose a new password for your account.',
'auth.reset.submit': 'Save the password',
'auth.reset.submitting': 'Saving…',
'auth.reset.no_session_title': 'Invalid or expired link',
'auth.reset.no_session_description':
'This reset link can no longer be used. Request a new one.',
'auth.reset.request_again': 'Request a new link',
// auth — callback
'auth.callback.working': 'Signing you in…',
'auth.callback.failed_title': 'Sign-in failed',
'auth.callback.failed_description':
'No session could be opened: the link expired, was already used, or was opened in a different browser than the one that requested it. If you just confirmed your address, simply sign in.',
'auth.callback.retry': 'Try signing in again',
// auth — field errors (validation)
'auth.error.email_required': 'The email address is required.',
'auth.error.email_invalid': 'This email address is not valid.',
'auth.error.password_required': 'The password is required.',
'auth.error.password_rules':
'At least 12 characters, with a lowercase letter, an uppercase letter and a digit.',
'auth.error.password_mismatch': 'The two passwords do not match.',
'auth.error.display_name_required': 'The display name is required.',
'auth.error.display_name_too_long': 'The display name exceeds 80 characters.',
// auth — server failures
'auth.failure.invalid_credentials': 'Incorrect email or password.',
'auth.failure.email_not_confirmed':
'Your email address is not confirmed yet. Open the link you received by email.',
'auth.failure.user_exists': 'An account already exists with this email address.',
'auth.failure.weak_password':
'Password too weak: at least 12 characters, with a lowercase letter, an uppercase letter and a digit.',
'auth.failure.same_password': 'The new password must differ from the old one.',
'auth.failure.invalid_email': 'This email address is not accepted.',
'auth.failure.rate_limited':
'Too many attempts. Wait a few minutes before trying again.',
'auth.failure.link_expired': 'This link has expired or was already used.',
'auth.failure.session_expired': 'Your session has expired. Sign in again.',
'auth.failure.reauthentication_needed':
'For security, sign out and sign in again before changing the password.',
'auth.failure.provider_disabled': 'This sign-in method is not enabled.',
'auth.failure.network': 'Cannot reach the server. Check your network.',
'auth.failure.unknown': 'An unexpected error occurred. Try again.',
// shell
'shell.nav_label': 'Main navigation',
'shell.open_menu': 'Open menu',
'shell.close_menu': 'Close menu',
'shell.nav.dashboard': 'Dashboard',
'shell.nav.account': 'My account',
'shell.nav.local_tool': 'Report tool',
'shell.nav.local_tool_hint': 'No account, PDF export',
'shell.sign_out': 'Sign out',
'shell.signing_out': 'Signing out…',
'shell.sign_out_failed':
'Signed out on this device, but the server did not confirm: your other sessions may stay open.',
'shell.loading_session': 'Checking your session…',
'shell.role.owner': 'Platform owner',
'shell.role.admin': 'Administrator',
'shell.role.moderator': 'Moderator',
'shell.role.support': 'Support',
// dashboard
'dashboard.title': 'Dashboard',
'dashboard.greeting': 'Hello {name}',
'dashboard.greeting_fallback': 'Hello',
'dashboard.intro':
'Your Faunosteo space is ready. Online reports will come in a later version; until then the report tool remains available.',
'dashboard.profile.title': 'Your profile',
'dashboard.profile.incomplete':
'Fill in your professional details: they will appear on your future reports.',
'dashboard.profile.complete': 'Your details are filled in.',
'dashboard.profile.missing_label': 'To complete:',
'dashboard.profile.cta_complete': 'Complete my profile',
'dashboard.profile.cta_view': 'View my account',
'dashboard.tool.title': 'Report tool',
'dashboard.tool.description':
'Create or resume a report as today: it works without an account and exports a PDF that carries its own data.',
'dashboard.tool.cta_new': 'New report',
'dashboard.tool.cta_import': 'Import a PDF',
'dashboard.account.title': 'Account',
'dashboard.account.email': 'Email',
'dashboard.account.verified': 'Address confirmed',
'dashboard.account.unverified': 'Address not confirmed',
'dashboard.account.language': 'Language',
'dashboard.account.roles': 'Platform roles',
'dashboard.account.no_roles': 'No platform role',
'dashboard.account.member_since': 'Account created on {date}',
// account
'account.title': 'My account',
'account.save': 'Save',
'account.saving': 'Saving…',
'account.saved': 'Changes saved.',
'account.optional': 'optional',
'account.error.save_failed': 'Saving failed. Check the fields and try again.',
'account.error.required': 'This field is required.',
'account.error.too_long': 'Text too long ({max} characters maximum).',
'account.error.phone_format':
'International format, for example +33612345678.',
'account.error.siret_format': 'A SIRET has exactly 14 digits.',
'account.personal.title': 'Personal information',
'account.personal.description': 'How you appear in Faunosteo.',
'account.personal.display_name': 'Display name',
'account.personal.first_name': 'First name',
'account.personal.last_name': 'Last name',
'account.personal.phone': 'Phone',
'account.personal.phone_hint':
'International format. SMS verification comes later.',
'account.professional.title': 'Professional information',
'account.professional.description':
'Declarative for now: professional verification comes in a later step.',
'account.professional.professional_title': 'Professional title',
'account.professional.professional_title_placeholder': 'Animal osteopath',
'account.professional.practice_name': 'Practice or organisation',
'account.professional.siret': 'SIRET',
'account.professional.siret_hint': '14 digits, no spaces.',
'account.preferences.title': 'Preferences',
'account.preferences.description':
'The language is saved on your account and applies on every device.',
'account.preferences.language': 'Language',
'account.preferences.timezone': 'Time zone',
'account.preferences.timezone_hint': 'Used for dates and future appointments.',
'account.security.title': 'Security',
'account.security.description': 'Password and sessions.',
'account.security.email_label': 'Sign-in address',
'account.security.new_password': 'New password',
'account.security.change_password': 'Change password',
'account.security.changing_password': 'Updating…',
'account.security.password_changed': 'Password updated.',
'account.security.mfa_title': 'Two-factor authentication',
'account.security.mfa_note':
'Not available in this version yet. It will be offered, then required for platform roles.',
'account.security.sign_out_everywhere_note':
'Signing out closes the session on this device.',
}
+197
View File
@@ -56,6 +56,9 @@ export const fr: Dict = {
'home.no_sheet.description':
"Cette version de l'application n'embarque aucune fiche anatomique : aucun bilan ne peut être créé ni importé.",
'home.space.signin': 'Se connecter',
'home.space.open': 'Mon espace',
// footer
'footer.all_rights_reserved': 'Tous droits réservés.',
'footer.powered_by': 'Propulsé par',
@@ -193,4 +196,198 @@ export const fr: Dict = {
'lang.switch_to_en': 'Switch to English',
'lang.fr': 'FR',
'lang.en': 'EN',
// auth — shared
'auth.brand_claim': 'Votre espace professionnel Faunosteo.',
'auth.brand_note':
"L'outil de bilan reste accessible sans compte. Un compte prépare la suite : bilans enregistrés, suivi des animaux, partage avec les propriétaires.",
'auth.unavailable_title': 'Espace connecté non disponible',
'auth.unavailable_description':
"Cette installation ne dispose pas de serveur d'authentification. L'outil de bilan local reste utilisable.",
'auth.back_to_tool': "Retour à l'outil de bilan",
'auth.email': 'Adresse e-mail',
'auth.password': 'Mot de passe',
'auth.password_confirm': 'Confirmer le mot de passe',
'auth.password_hint':
'Au moins {min} caractères, avec une minuscule, une majuscule et un chiffre.',
'auth.show_password': 'Afficher le mot de passe',
'auth.hide_password': 'Masquer le mot de passe',
'auth.or': 'ou',
'auth.continue_with_google': 'Continuer avec Google',
'auth.continue_with_apple': 'Continuer avec Apple',
'auth.loading': 'Chargement…',
// auth — login
'auth.login.title': 'Bon retour',
'auth.login.subtitle': 'Connectez-vous à votre espace.',
'auth.login.submit': 'Se connecter',
'auth.login.submitting': 'Connexion…',
'auth.login.forgot': 'Mot de passe oublié ?',
'auth.login.no_account': 'Pas encore de compte ?',
'auth.login.signup_link': 'Créer un compte',
// auth — signup
'auth.signup.title': 'Créer votre compte',
'auth.signup.subtitle': "Quelques informations, puis une confirmation par e-mail.",
'auth.signup.display_name': 'Nom affiché',
'auth.signup.display_name_hint':
'Tel que vos interlocuteurs le verront. Modifiable ensuite.',
'auth.signup.submit': 'Créer mon compte',
'auth.signup.submitting': 'Création…',
'auth.signup.have_account': 'Déjà un compte ?',
'auth.signup.login_link': 'Se connecter',
'auth.signup.check_inbox_title': 'Vérifiez votre boîte mail',
'auth.signup.check_inbox_description':
'Un lien de confirmation a été envoyé à {email}. Ouvrez-le pour activer votre compte, puis connectez-vous.',
'auth.signup.check_inbox_spam':
"Rien reçu après quelques minutes ? Vérifiez vos courriers indésirables.",
// auth — forgot / reset
'auth.forgot.title': 'Mot de passe oublié',
'auth.forgot.subtitle':
'Indiquez votre adresse e-mail : nous vous envoyons un lien pour choisir un nouveau mot de passe.',
'auth.forgot.submit': 'Envoyer le lien',
'auth.forgot.submitting': 'Envoi…',
'auth.forgot.sent_title': 'Lien envoyé',
'auth.forgot.sent_description':
'Si un compte existe pour {email}, un e-mail vient de partir. Le lien reste valable une heure.',
'auth.forgot.back_to_login': 'Retour à la connexion',
'auth.reset.title': 'Nouveau mot de passe',
'auth.reset.subtitle': 'Choisissez un nouveau mot de passe pour votre compte.',
'auth.reset.submit': 'Enregistrer le mot de passe',
'auth.reset.submitting': 'Enregistrement…',
'auth.reset.no_session_title': 'Lien invalide ou expiré',
'auth.reset.no_session_description':
'Ce lien de réinitialisation ne peut plus être utilisé. Demandez-en un nouveau.',
'auth.reset.request_again': 'Demander un nouveau lien',
// auth — callback
'auth.callback.working': 'Connexion en cours…',
'auth.callback.failed_title': 'Connexion impossible',
'auth.callback.failed_description':
"Aucune session n'a pu être ouverte : lien expiré, déjà utilisé, ou ouvert dans un autre navigateur que celui de la demande. Si vous venez de confirmer votre adresse, connectez-vous simplement.",
'auth.callback.retry': 'Réessayer de se connecter',
// auth — field errors (validation)
'auth.error.email_required': "L'adresse e-mail est requise.",
'auth.error.email_invalid': "Cette adresse e-mail n'est pas valide.",
'auth.error.password_required': 'Le mot de passe est requis.',
'auth.error.password_rules':
'Au moins 12 caractères, avec une minuscule, une majuscule et un chiffre.',
'auth.error.password_mismatch': 'Les deux mots de passe ne correspondent pas.',
'auth.error.display_name_required': 'Le nom affiché est requis.',
'auth.error.display_name_too_long': 'Le nom affiché dépasse 80 caractères.',
// auth — server failures
'auth.failure.invalid_credentials': 'E-mail ou mot de passe incorrect.',
'auth.failure.email_not_confirmed':
"Votre adresse e-mail n'est pas encore confirmée. Ouvrez le lien reçu par e-mail.",
'auth.failure.user_exists': 'Un compte existe déjà avec cette adresse e-mail.',
'auth.failure.weak_password':
'Mot de passe trop faible : au moins 12 caractères, avec une minuscule, une majuscule et un chiffre.',
'auth.failure.same_password': "Le nouveau mot de passe doit être différent de l'ancien.",
'auth.failure.invalid_email': "Cette adresse e-mail n'est pas acceptée.",
'auth.failure.rate_limited':
'Trop de tentatives. Patientez quelques minutes avant de réessayer.',
'auth.failure.link_expired': 'Ce lien a expiré ou a déjà été utilisé.',
'auth.failure.session_expired': 'Votre session a expiré. Reconnectez-vous.',
'auth.failure.reauthentication_needed':
'Par sécurité, déconnectez-vous puis reconnectez-vous avant de changer le mot de passe.',
'auth.failure.provider_disabled': "Ce mode de connexion n'est pas activé.",
'auth.failure.network': 'Connexion au serveur impossible. Vérifiez votre réseau.',
'auth.failure.unknown': "Une erreur inattendue s'est produite. Réessayez.",
// shell
'shell.nav_label': 'Navigation principale',
'shell.open_menu': 'Ouvrir le menu',
'shell.close_menu': 'Fermer le menu',
'shell.nav.dashboard': 'Tableau de bord',
'shell.nav.account': 'Mon compte',
'shell.nav.local_tool': 'Outil de bilan',
'shell.nav.local_tool_hint': 'Sans compte, export PDF',
'shell.sign_out': 'Se déconnecter',
'shell.signing_out': 'Déconnexion…',
'shell.sign_out_failed':
"Déconnecté sur cet appareil, mais le serveur n'a pas confirmé : vos autres sessions peuvent rester ouvertes.",
'shell.loading_session': 'Vérification de la session…',
'shell.role.owner': 'Propriétaire plateforme',
'shell.role.admin': 'Administrateur',
'shell.role.moderator': 'Modérateur',
'shell.role.support': 'Support',
// dashboard
'dashboard.title': 'Tableau de bord',
'dashboard.greeting': 'Bonjour {name}',
'dashboard.greeting_fallback': 'Bonjour',
'dashboard.intro':
"Votre espace Faunosteo est prêt. Les bilans en ligne arriveront dans une prochaine version ; d'ici là, l'outil de bilan reste disponible.",
'dashboard.profile.title': 'Votre profil',
'dashboard.profile.incomplete':
'Renseignez vos informations professionnelles : elles figureront sur vos futurs bilans.',
'dashboard.profile.complete': 'Vos informations sont renseignées.',
'dashboard.profile.missing_label': 'À compléter :',
'dashboard.profile.cta_complete': 'Compléter mon profil',
'dashboard.profile.cta_view': 'Voir mon compte',
'dashboard.tool.title': 'Outil de bilan',
'dashboard.tool.description':
"Créez ou reprenez un bilan comme aujourd'hui : il fonctionne sans compte et exporte un PDF qui contient ses propres données.",
'dashboard.tool.cta_new': 'Nouveau bilan',
'dashboard.tool.cta_import': 'Importer un PDF',
'dashboard.account.title': 'Compte',
'dashboard.account.email': 'E-mail',
'dashboard.account.verified': 'Adresse confirmée',
'dashboard.account.unverified': 'Adresse non confirmée',
'dashboard.account.language': 'Langue',
'dashboard.account.roles': 'Rôles plateforme',
'dashboard.account.no_roles': 'Aucun rôle plateforme',
'dashboard.account.member_since': 'Compte créé le {date}',
// account
'account.title': 'Mon compte',
'account.save': 'Enregistrer',
'account.saving': 'Enregistrement…',
'account.saved': 'Modifications enregistrées.',
'account.optional': 'facultatif',
'account.error.save_failed':
"L'enregistrement a échoué. Vérifiez les champs et réessayez.",
'account.error.required': 'Ce champ est requis.',
'account.error.too_long': 'Texte trop long ({max} caractères maximum).',
'account.error.phone_format':
'Numéro au format international, par exemple +33612345678.',
'account.error.siret_format': 'Le SIRET comporte exactement 14 chiffres.',
'account.personal.title': 'Informations personnelles',
'account.personal.description': 'Comment vous apparaissez dans Faunosteo.',
'account.personal.display_name': 'Nom affiché',
'account.personal.first_name': 'Prénom',
'account.personal.last_name': 'Nom',
'account.personal.phone': 'Téléphone',
'account.personal.phone_hint':
'Format international. La vérification par SMS viendra plus tard.',
'account.professional.title': 'Informations professionnelles',
'account.professional.description':
'Déclaratives pour le moment : la vérification professionnelle arrivera dans une prochaine étape.',
'account.professional.professional_title': 'Titre professionnel',
'account.professional.professional_title_placeholder': 'Ostéopathe animalier',
'account.professional.practice_name': 'Cabinet ou structure',
'account.professional.siret': 'SIRET',
'account.professional.siret_hint': '14 chiffres, sans espaces.',
'account.preferences.title': 'Préférences',
'account.preferences.description':
"La langue est enregistrée sur votre compte et s'applique sur tous vos appareils.",
'account.preferences.language': 'Langue',
'account.preferences.timezone': 'Fuseau horaire',
'account.preferences.timezone_hint':
'Utilisé pour les dates et les futurs rendez-vous.',
'account.security.title': 'Sécurité',
'account.security.description': 'Mot de passe et sessions.',
'account.security.email_label': 'Adresse de connexion',
'account.security.new_password': 'Nouveau mot de passe',
'account.security.change_password': 'Changer le mot de passe',
'account.security.changing_password': 'Mise à jour…',
'account.security.password_changed': 'Mot de passe mis à jour.',
'account.security.mfa_title': 'Double authentification',
'account.security.mfa_note':
'Pas encore disponible dans cette version. Elle sera proposée, puis exigée pour les rôles plateforme.',
'account.security.sign_out_everywhere_note':
'Se déconnecter ferme la session sur cet appareil.',
}
+43
View File
@@ -0,0 +1,43 @@
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import type { Locale } from '@/i18n/types'
function isLocale(value: string): value is Locale {
return value === 'fr' || value === 'en'
}
/**
* Keeps the UI language and profiles.locale together:
* - when an account loads, its locale wins over the device choice (once per sign-in);
* - while signed in, switching the language is saved to the profile.
* Returns the stop function.
*/
export function startLocaleSync(): () => void {
let appliedForUser: string | null = null
const stopAuth = useAuthStore.subscribe((state, previous) => {
if (!state.user) {
appliedForUser = null
return
}
const profile = state.profile
if (!profile || profile === previous.profile) return
if (appliedForUser === state.user.id) return
appliedForUser = state.user.id
if (isLocale(profile.locale)) {
useLocaleStore.getState().setLocale(profile.locale)
}
})
const stopLocale = useLocaleStore.subscribe((state) => {
const auth = useAuthStore.getState()
if (auth.status !== 'signed_in' || !auth.profile) return
if (auth.profile.locale === state.locale) return
void auth.updateProfile({ locale: state.locale }).catch(() => undefined)
})
return () => {
stopAuth()
stopLocale()
}
}
+158
View File
@@ -0,0 +1,158 @@
import { create } from 'zustand'
import {
AuthFailure,
type AuthChangeEvent,
type Session,
type User,
classifyAuthError,
fetchOwnPlatformRoles,
fetchOwnProfile,
signOut as signOutRequest,
updateOwnProfile,
type AuthFailureKind,
type FaunosteoClient,
type OwnProfilePatch,
type PlatformRole,
type Profile,
} from '@faunosteo/supabase'
import { getSupabaseClient } from '@/lib/supabase'
/**
* unavailable = no Supabase configured (local-only deployment); loading until
* the client has read the persisted session and the URL (OAuth / email links).
*/
export type AuthStatus = 'loading' | 'unavailable' | 'signed_out' | 'signed_in'
export interface AuthState {
status: AuthStatus
session: Session | null
user: User | null
/** Null until loaded, or when the profile row is missing. */
profile: Profile | null
roles: PlatformRole[]
/** Set by a password-recovery link until the new password is saved. */
recovery: boolean
/** Failure while reading the URL (expired link, bad code): shown by the landing routes. */
urlFailure: AuthFailureKind | null
/** Subscribes to the client; returns the unsubscribe. Safe to call twice. */
start: () => () => void
refreshAccount: () => Promise<void>
updateProfile: (patch: OwnProfilePatch) => Promise<Profile>
signOut: () => Promise<void>
clearRecovery: () => void
}
type Set = (patch: Partial<AuthState>) => void
async function loadAccount(client: FaunosteoClient, user: User, set: Set) {
const [profile, roles] = await Promise.all([
fetchOwnProfile(client, user.id),
fetchOwnPlatformRoles(client, user.id),
])
set({ profile, roles })
}
/**
* Applies one GoTrue event. The account load runs outside the callback: the
* client serialises its callbacks, awaiting a request inside one deadlocks.
*/
function applyAuthEvent(
client: FaunosteoClient,
event: AuthChangeEvent,
session: Session | null,
set: Set,
previousUserId: string | undefined,
) {
if (event === 'SIGNED_OUT' || session === null) {
set({
status: 'signed_out',
session: null,
user: null,
profile: null,
roles: [],
recovery: false,
})
return
}
const patch: Partial<AuthState> = {
status: 'signed_in',
session,
user: session.user,
}
if (event === 'PASSWORD_RECOVERY') patch.recovery = true
set(patch)
if (session.user.id !== previousUserId || event === 'USER_UPDATED') {
setTimeout(() => {
void loadAccount(client, session.user, set).catch(() => {
set({ profile: null, roles: [] })
})
}, 0)
}
}
function requireClient(): FaunosteoClient {
const client = getSupabaseClient()
if (!client) throw new AuthFailure('unknown')
return client
}
function requireUser(user: User | null): User {
if (!user) throw new AuthFailure('session_expired')
return user
}
export const useAuthStore = create<AuthState>((set, get) => ({
status: 'loading',
session: null,
user: null,
profile: null,
roles: [],
recovery: false,
urlFailure: null,
start: () => {
const client = getSupabaseClient()
if (!client) {
set({ status: 'unavailable' })
return () => undefined
}
void client.auth.initialize().then(({ error }) => {
if (error) set({ urlFailure: classifyAuthError(error) })
})
const { data } = client.auth.onAuthStateChange((event, session) => {
applyAuthEvent(client, event, session, set, get().user?.id)
})
return () => data.subscription.unsubscribe()
},
refreshAccount: async () => {
await loadAccount(requireClient(), requireUser(get().user), set)
},
updateProfile: async (patch) => {
const user = requireUser(get().user)
const profile = await updateOwnProfile(requireClient(), user.id, patch)
set({ profile })
return profile
},
signOut: async () => {
const clear = () => set({
status: 'signed_out',
session: null,
user: null,
profile: null,
roles: [],
recovery: false,
})
try {
// auth-js clears the local session even when the server call fails.
await signOutRequest(requireClient())
} finally {
// SIGNED_OUT also arrives through the subscription; this keeps the UI honest if it does not.
clear()
}
},
clearRecovery: () => set({ recovery: false }),
}))
+144
View File
@@ -0,0 +1,144 @@
/**
* In-memory stand-in for the parts of the Supabase client the identity step
* uses: auth events, profile select/update, profile_roles select. Tests mock
* `@/lib/supabase` to hand this object out.
*/
import { vi } from 'vitest'
import type {
AuthChangeEvent,
FaunosteoClient,
Profile,
Session,
User,
} from '@faunosteo/supabase'
type Listener = (event: AuthChangeEvent, session: Session | null) => void
type Row = Record<string, unknown>
export function fakeUser(patch: Partial<User> = {}): User {
return {
id: 'user-1',
aud: 'authenticated',
email: 'alice@example.test',
email_confirmed_at: '2026-10-11T10:00:00Z',
created_at: '2026-10-01T10:00:00Z',
app_metadata: {},
user_metadata: {},
...patch,
} as User
}
export function fakeSession(user: User = fakeUser()): Session {
return {
access_token: 'at',
refresh_token: 'rt',
token_type: 'bearer',
expires_in: 3600,
user,
} as Session
}
export function fakeProfile(patch: Partial<Profile> = {}): Profile {
return {
id: 'user-1',
display_name: 'Alice Local',
first_name: null,
last_name: null,
phone: null,
phone_verified_at: null,
locale: 'fr',
timezone: 'Europe/Paris',
active: true,
practice_name: null,
professional_title: null,
siret: null,
created_at: '2026-10-01T10:00:00Z',
updated_at: '2026-10-01T10:00:00Z',
...patch,
}
}
/** Minimal PostgREST builder: filters, then select / update, awaitable. */
function builder(tables: Record<string, Row[]>, table: string) {
const filters: Array<(row: Row) => boolean> = []
let patch: Row | null = null
const rows = () => (tables[table] ?? []).filter((r) => filters.every((f) => f(r)))
const apply = () => {
if (!patch) return rows()
const hit = rows()
hit.forEach((r) => Object.assign(r, patch))
return hit
}
const api = {
select: () => api,
update: (values: Row) => {
patch = values
return api
},
eq: (col: string, value: unknown) => {
filters.push((r) => r[col] === value)
return api
},
is: (col: string, value: unknown) => {
filters.push((r) => r[col] === value)
return api
},
maybeSingle: async () => ({ data: apply()[0] ?? null, error: null }),
single: async () => {
const [first] = apply()
return first
? { data: first, error: null }
: { data: null, error: { message: 'no row', code: 'PGRST116' } }
},
then: (resolve: (v: { data: Row[]; error: null }) => void) =>
resolve({ data: apply(), error: null }),
}
return api
}
export interface FakeSupabase {
client: FaunosteoClient
tables: Record<string, Row[]>
emit: (event: AuthChangeEvent, session: Session | null) => void
auth: {
initialize: ReturnType<typeof vi.fn>
signInWithPassword: ReturnType<typeof vi.fn>
signUp: ReturnType<typeof vi.fn>
signOut: ReturnType<typeof vi.fn>
updateUser: ReturnType<typeof vi.fn>
resetPasswordForEmail: ReturnType<typeof vi.fn>
signInWithOAuth: ReturnType<typeof vi.fn>
}
}
export function createFakeSupabase(
tables: Record<string, Row[]> = { profiles: [fakeProfile()], profile_roles: [] },
): FakeSupabase {
const listeners: Listener[] = []
const auth = {
initialize: vi.fn(async () => ({ error: null })),
onAuthStateChange: vi.fn((cb: Listener) => {
listeners.push(cb)
return { data: { subscription: { unsubscribe: vi.fn() } } }
}),
signInWithPassword: vi.fn(),
signUp: vi.fn(),
signOut: vi.fn(async () => ({ error: null })),
updateUser: vi.fn(),
resetPasswordForEmail: vi.fn(),
signInWithOAuth: vi.fn(),
}
const client = {
auth,
from: (table: string) => builder(tables, table),
} as unknown as FaunosteoClient
return {
client,
tables,
auth,
emit: (event, session) => listeners.forEach((cb) => cb(event, session)),
}
}
/** Resolves once the store has run its deferred account load. */
export const flush = () => new Promise((r) => setTimeout(r, 0))
+123
View File
@@ -0,0 +1,123 @@
import { describe, expect, it } from 'vitest'
import {
fieldErrors,
loginSchema,
newPasswordSchema,
passwordSchema,
signupSchema,
} from '@/auth/validation'
import { safeNextPath } from '@/auth/redirects'
import {
personalPatch,
personalSchema,
professionalSchema,
translateFieldError,
} from '@/account/validation'
describe('auth validation', () => {
it('password mirrors the server policy: 12 chars, lower, upper, digit', () => {
expect(passwordSchema.safeParse('Short1aA').success).toBe(false)
expect(passwordSchema.safeParse('alllowercase123').success).toBe(false)
expect(passwordSchema.safeParse('NoDigitsHereAtAll').success).toBe(false)
expect(passwordSchema.safeParse('CorrectHorse12').success).toBe(true)
})
it('reports one i18n key per field, first issue wins', () => {
const r = loginSchema.safeParse({ email: 'nope', password: '' })
expect(r.success).toBe(false)
if (!r.success) {
expect(fieldErrors(r.error)).toEqual({
email: 'auth.error.email_invalid',
password: 'auth.error.password_required',
})
}
})
it('signup flags a confirmation mismatch on the confirm field', () => {
const r = signupSchema.safeParse({
displayName: 'A',
email: 'a@b.co',
password: 'CorrectHorse12',
passwordConfirm: 'CorrectHorse13',
})
expect(r.success).toBe(false)
if (!r.success) {
expect(fieldErrors(r.error).passwordConfirm).toBe('auth.error.password_mismatch')
}
expect(
newPasswordSchema.safeParse({ password: 'CorrectHorse12', passwordConfirm: 'x' })
.success,
).toBe(false)
})
})
describe('safeNextPath', () => {
it('keeps same-origin paths and refuses anything else', () => {
expect(safeNextPath('/app/account')).toBe('/app/account')
expect(safeNextPath(null)).toBe('/app')
expect(safeNextPath('https://evil.test/')).toBe('/app')
expect(safeNextPath('//evil.test')).toBe('/app')
expect(safeNextPath('app')).toBe('/app')
})
it('refuses the backslash and control-character escapes the URL parser accepts', () => {
expect(safeNextPath('/\\evil.test')).toBe('/app')
expect(safeNextPath('/\t/evil.test')).toBe('/app')
expect(safeNextPath('/\n/evil.test/x')).toBe('/app')
expect(safeNextPath('/ /evil.test')).toBe('/%20/evil.test')
expect(safeNextPath('/app/account?tab=x#s')).toBe('/app/account?tab=x#s')
})
})
describe('account validation', () => {
it('turns empty optional fields into null and keeps display_name', () => {
const r = personalSchema.safeParse({
display_name: ' Alice ',
first_name: '',
last_name: 'Local',
phone: '',
})
expect(r.success).toBe(true)
if (r.success) {
expect(personalPatch(r.data)).toEqual({
display_name: 'Alice',
first_name: null,
last_name: 'Local',
phone: null,
})
}
})
it('checks phone E.164 and SIRET 14 digits (spaces tolerated)', () => {
const bad = personalSchema.safeParse({
display_name: 'A',
first_name: '',
last_name: '',
phone: '06 12',
})
expect(bad.success).toBe(false)
const siretOk = professionalSchema.safeParse({
professional_title: '',
practice_name: '',
siret: '123 456 789 01234',
})
expect(siretOk.success).toBe(true)
if (siretOk.success) expect(siretOk.data.siret).toBe('12345678901234')
const siretBad = professionalSchema.safeParse({
professional_title: '',
practice_name: '',
siret: '1234',
})
expect(siretBad.success).toBe(false)
if (!siretBad.success) {
expect(fieldErrors(siretBad.error).siret).toBe('account.error.siret_format')
}
})
it('translates a key|value message with its placeholder', () => {
const t = (k: string) => (k === 'account.error.too_long' ? 'Max {max}' : k)
expect(translateFieldError(t, 'account.error.too_long|80')).toBe('Max 80')
expect(translateFieldError(t, 'account.error.required')).toBe('account.error.required')
expect(translateFieldError(t, undefined)).toBeUndefined()
})
})
+19 -1
View File
@@ -1,5 +1,9 @@
import { describe, it, expect } from 'vitest'
import { resolveConfig, resolveSupabaseConnection } from '@/config/env'
import {
resolveAuthProviders,
resolveConfig,
resolveSupabaseConnection,
} from '@/config/env'
describe('resolveConfig', () => {
it('keeps the identity defaults and no Supabase when nothing is injected', () => {
@@ -35,3 +39,17 @@ describe('resolveSupabaseConnection', () => {
expect(resolveSupabaseConnection(undefined, 'key')).toBeNull()
})
})
describe('resolveAuthProviders', () => {
it('is empty by default', () => {
expect(resolveConfig({}).authProviders).toEqual([])
expect(resolveAuthProviders('')).toEqual([])
})
it('parses a comma list, trims, lowercases, dedupes and drops unknown names', () => {
expect(resolveAuthProviders(' Google, apple ,google,facebook')).toEqual([
'google',
'apple',
])
})
})
@@ -0,0 +1,75 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
import RequireAuth from '@/app/guards/RequireAuth'
import RedirectIfSignedIn from '@/app/guards/RedirectIfSignedIn'
import { useAuthStore, type AuthStatus } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
function ShowLocation() {
const loc = useLocation()
return <p>{loc.pathname + loc.search}</p>
}
function mount(path: string) {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/login" element={<ShowLocation />} />
<Route element={<RedirectIfSignedIn />}>
<Route path="/signup" element={<p>signup form</p>} />
</Route>
<Route path="/app" element={<RequireAuth />}>
<Route index element={<p>dashboard</p>} />
<Route path="account" element={<p>account</p>} />
</Route>
</Routes>
</MemoryRouter>,
)
}
function setStatus(status: AuthStatus) {
useAuthStore.setState({ status, recovery: false })
}
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(cleanup)
describe('RequireAuth', () => {
it('waits while the session loads', () => {
setStatus('loading')
mount('/app')
expect(screen.getByText(fr['shell.loading_session'])).toBeInTheDocument()
})
it('sends a visitor to /login with the return path', () => {
setStatus('signed_out')
mount('/app/account?tab=x')
expect(screen.getByText('/login?next=%2Fapp%2Faccount%3Ftab%3Dx')).toBeInTheDocument()
})
it('also redirects when no backend exists', () => {
setStatus('unavailable')
mount('/app')
expect(screen.getByText(/^\/login/)).toBeInTheDocument()
})
it('renders the page once signed in', () => {
setStatus('signed_in')
mount('/app/account')
expect(screen.getByText('account')).toBeInTheDocument()
})
})
describe('RedirectIfSignedIn', () => {
it('shows the form to a visitor and skips it for a signed-in user', () => {
setStatus('signed_out')
mount('/signup')
expect(screen.getByText('signup form')).toBeInTheDocument()
cleanup()
setStatus('signed_in')
mount('/signup')
expect(screen.queryByText('signup form')).not.toBeInTheDocument()
})
})
+1
View File
@@ -8,6 +8,7 @@ const base: AppConfig = {
footerName: 'F',
tagline: 'T',
supabase: null,
authProviders: [],
}
describe('getSupabaseClient', () => {
@@ -0,0 +1,101 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
import AccountRoute from '@/app/routes/app/AccountRoute'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
let fake: FakeSupabase
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
fake = createFakeSupabase()
mocks.fake = fake
useAuthStore.setState({
status: 'signed_in',
user: fakeUser(),
profile: fakeProfile(),
roles: ['owner'],
})
})
afterEach(cleanup)
function mount() {
return render(
<MemoryRouter>
<AccountRoute />
</MemoryRouter>,
)
}
describe('AccountRoute', () => {
it('shows the four sections, the roles and the sign-in address', () => {
mount()
for (const key of [
'account.personal.title',
'account.professional.title',
'account.preferences.title',
'account.security.title',
]) {
expect(screen.getByRole('heading', { name: fr[key] })).toBeInTheDocument()
}
expect(screen.getByText(fr['shell.role.owner'])).toBeInTheDocument()
expect(screen.getByText('alice@example.test')).toBeInTheDocument()
expect(screen.getByText(fr['account.security.mfa_note'])).toBeInTheDocument()
})
it('saves personal information, empty optionals as null', async () => {
const user = userEvent.setup()
mount()
await user.type(screen.getByLabelText(new RegExp(`^${fr['account.personal.first_name']}`)), 'Alice')
const [save] = screen.getAllByRole('button', { name: fr['account.save'] })
await user.click(save)
expect(await screen.findByText(fr['account.saved'])).toBeInTheDocument()
expect(fake.tables.profiles[0]).toMatchObject({
display_name: 'Alice Local',
first_name: 'Alice',
last_name: null,
phone: null,
})
})
it('refuses a malformed SIRET next to the field, without calling the server', async () => {
const user = userEvent.setup()
mount()
await user.type(screen.getByLabelText(new RegExp(`^${fr['account.professional.siret']}`)), '1234')
const saves = screen.getAllByRole('button', { name: fr['account.save'] })
await user.click(saves[1])
expect(await screen.findByText(fr['account.error.siret_format'])).toBeInTheDocument()
expect(fake.tables.profiles[0].siret).toBeNull()
})
it('changes the password through the client', async () => {
fake.auth.updateUser.mockResolvedValue({ data: {}, error: null })
const user = userEvent.setup()
mount()
await user.type(screen.getByLabelText(fr['account.security.new_password']), 'CorrectHorse12')
await user.type(screen.getByLabelText(fr['auth.password_confirm']), 'CorrectHorse12')
await user.click(screen.getByRole('button', { name: fr['account.security.change_password'] }))
await waitFor(() =>
expect(fake.auth.updateUser).toHaveBeenCalledWith({ password: 'CorrectHorse12' }),
)
expect(await screen.findByText(fr['account.security.password_changed'])).toBeInTheDocument()
})
it('switching the language select updates the locale store', async () => {
const user = userEvent.setup()
mount()
await user.selectOptions(screen.getByLabelText(fr['account.preferences.language']), 'en')
expect(useLocaleStore.getState().locale).toBe('en')
})
})
@@ -0,0 +1,58 @@
import { afterEach, beforeEach, describe, expect, it } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import { MemoryRouter } from 'react-router-dom'
import DashboardRoute from '@/app/routes/app/DashboardRoute'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
import { fakeProfile, fakeUser } from '../helpers/fakeSupabase'
beforeEach(() => useLocaleStore.setState({ locale: 'fr' }))
afterEach(cleanup)
function mount() {
return render(
<MemoryRouter>
<DashboardRoute />
</MemoryRouter>,
)
}
describe('DashboardRoute', () => {
it('greets by first name and lists what the profile lacks', () => {
useAuthStore.setState({
status: 'signed_in',
user: fakeUser(),
profile: fakeProfile({ first_name: 'Alice' }),
roles: [],
})
mount()
expect(screen.getByRole('heading', { level: 1 })).toHaveTextContent('Bonjour Alice')
expect(screen.getByText(fr['dashboard.profile.incomplete'])).toBeInTheDocument()
expect(screen.getByText(fr['account.personal.last_name'], { exact: false })).toBeInTheDocument()
expect(
screen.getByRole('link', { name: fr['dashboard.profile.cta_complete'] }),
).toHaveAttribute('href', '/app/account')
expect(screen.getByText(fr['dashboard.account.verified'])).toBeInTheDocument()
expect(screen.getByText(fr['dashboard.account.no_roles'])).toBeInTheDocument()
})
it('switches to the complete state and shows roles', () => {
useAuthStore.setState({
status: 'signed_in',
user: fakeUser({ email_confirmed_at: undefined }),
profile: fakeProfile({
first_name: 'Alice',
last_name: 'Local',
professional_title: 'Ostéopathe',
practice_name: 'Cabinet',
}),
roles: ['admin'],
})
mount()
expect(screen.getByText(fr['dashboard.profile.complete'])).toBeInTheDocument()
expect(screen.getByRole('link', { name: fr['dashboard.profile.cta_view'] })).toBeInTheDocument()
expect(screen.getByText(fr['shell.role.admin'])).toBeInTheDocument()
expect(screen.getByText(fr['dashboard.account.unverified'])).toBeInTheDocument()
})
})
@@ -0,0 +1,124 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen, waitFor } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { createFakeSupabase, fakeSession, type FakeSupabase } from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({ fake: null as unknown, providers: [] as string[] }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
vi.mock('@/app/providers/ConfigProvider', async (importOriginal) => {
const mod = await importOriginal<typeof import('@/app/providers/ConfigProvider')>()
return {
...mod,
useConfig: () => ({
siteName: 'Faunosteo',
brandName: 'Faunosteo',
footerName: 'Faunosteo',
tagline: 'T',
supabase: mocks.fake ? { url: 'http://x', anonKey: 'k' } : null,
authProviders: mocks.providers,
}),
}
})
import LoginRoute from '@/app/routes/auth/LoginRoute'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
let fake: FakeSupabase
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
useAuthStore.setState({ status: 'signed_out', recovery: false })
fake = createFakeSupabase()
mocks.fake = fake
mocks.providers = []
})
afterEach(cleanup)
function mount(path = '/login') {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/login" element={<LoginRoute />} />
<Route path="/app" element={<p>dashboard</p>} />
<Route path="/app/account" element={<p>account</p>} />
</Routes>
</MemoryRouter>,
)
}
describe('LoginRoute', () => {
it('explains when no backend is configured', () => {
mocks.fake = null
mount()
expect(screen.getByText(fr['auth.unavailable_title'])).toBeInTheDocument()
expect(screen.queryByLabelText(fr['auth.email'])).not.toBeInTheDocument()
})
it('validates before calling the server', async () => {
const user = userEvent.setup()
mount()
await user.click(screen.getByRole('button', { name: fr['auth.login.submit'] }))
expect(screen.getByText(fr['auth.error.email_required'])).toBeInTheDocument()
expect(screen.getByText(fr['auth.error.password_required'])).toBeInTheDocument()
expect(fake.auth.signInWithPassword).not.toHaveBeenCalled()
})
it('signs in and follows the next path', async () => {
fake.auth.signInWithPassword.mockResolvedValue({
data: { session: fakeSession(), user: fakeSession().user },
error: null,
})
const user = userEvent.setup()
mount('/login?next=%2Fapp%2Faccount')
await user.type(screen.getByLabelText(fr['auth.email']), 'alice@example.test')
await user.type(screen.getByLabelText(fr['auth.password']), 'CorrectHorse12')
await user.click(screen.getByRole('button', { name: fr['auth.login.submit'] }))
await waitFor(() => expect(screen.getByText('account')).toBeInTheDocument())
expect(fake.auth.signInWithPassword).toHaveBeenCalledWith({
email: 'alice@example.test',
password: 'CorrectHorse12',
})
})
it('phrases a wrong password without leaking the server message', async () => {
fake.auth.signInWithPassword.mockResolvedValue({
data: { session: null, user: null },
error: { code: 'invalid_credentials', message: 'Invalid login credentials', status: 400 },
})
const user = userEvent.setup()
mount()
await user.type(screen.getByLabelText(fr['auth.email']), 'alice@example.test')
await user.type(screen.getByLabelText(fr['auth.password']), 'wrong')
await user.click(screen.getByRole('button', { name: fr['auth.login.submit'] }))
expect(
await screen.findByText(fr['auth.failure.invalid_credentials']),
).toBeInTheDocument()
expect(screen.queryByText(/Invalid login/)).not.toBeInTheDocument()
})
it('shows one OAuth button per configured provider', () => {
mocks.providers = ['google']
mount()
expect(
screen.getByRole('button', { name: fr['auth.continue_with_google'] }),
).toBeInTheDocument()
expect(
screen.queryByRole('button', { name: fr['auth.continue_with_apple'] }),
).not.toBeInTheDocument()
})
it('toggles password visibility', async () => {
const user = userEvent.setup()
mount()
const input = screen.getByLabelText(fr['auth.password'])
expect(input).toHaveAttribute('type', 'password')
await user.click(screen.getByRole('button', { name: fr['auth.show_password'] }))
expect(input).toHaveAttribute('type', 'text')
})
})
@@ -0,0 +1,84 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter } from 'react-router-dom'
import { createFakeSupabase, type FakeSupabase } from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
import SignupRoute from '@/app/routes/auth/SignupRoute'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
let fake: FakeSupabase
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
fake = createFakeSupabase()
mocks.fake = fake
})
afterEach(cleanup)
function mount() {
return render(
<MemoryRouter initialEntries={['/signup']}>
<SignupRoute />
</MemoryRouter>,
)
}
async function fill(user: ReturnType<typeof userEvent.setup>, password: string, confirm = password) {
await user.type(screen.getByLabelText(fr['auth.signup.display_name']), 'Alice')
await user.type(screen.getByLabelText(fr['auth.email']), 'alice@example.test')
await user.type(screen.getByLabelText(fr['auth.password']), password)
await user.type(screen.getByLabelText(fr['auth.password_confirm']), confirm)
await user.click(screen.getByRole('button', { name: fr['auth.signup.submit'] }))
}
describe('SignupRoute', () => {
it('enforces the password policy and the confirmation client-side', async () => {
const user = userEvent.setup()
mount()
await fill(user, 'weak', 'weak')
expect(screen.getByText(fr['auth.error.password_rules'])).toBeInTheDocument()
expect(fake.auth.signUp).not.toHaveBeenCalled()
cleanup()
mount()
await fill(user, 'CorrectHorse12', 'CorrectHorse13')
expect(screen.getByText(fr['auth.error.password_mismatch'])).toBeInTheDocument()
})
it('sends display name + locale as metadata and shows the inbox step', async () => {
fake.auth.signUp.mockResolvedValue({ data: { session: null, user: null }, error: null })
const user = userEvent.setup()
mount()
await fill(user, 'CorrectHorse12')
expect(await screen.findByText(fr['auth.signup.check_inbox_title'])).toBeInTheDocument()
expect(screen.getByText(/alice@example\.test/)).toBeInTheDocument()
const [call] = fake.auth.signUp.mock.calls[0] as [Record<string, unknown>]
expect(call).toMatchObject({
email: 'alice@example.test',
password: 'CorrectHorse12',
options: {
data: { display_name: 'Alice', locale: 'fr' },
},
})
const options = call.options as { emailRedirectTo: string }
expect(options.emailRedirectTo).toMatch(/\/auth\/callback$/)
})
it('tells when the address is already taken', async () => {
fake.auth.signUp.mockResolvedValue({
data: { session: null, user: null },
error: { code: 'user_already_exists', message: 'User already registered', status: 422 },
})
const user = userEvent.setup()
mount()
await fill(user, 'CorrectHorse12')
expect(await screen.findByText(fr['auth.failure.user_exists'])).toBeInTheDocument()
})
})
@@ -0,0 +1,67 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
createFakeSupabase,
fakeProfile,
fakeSession,
flush,
type FakeSupabase,
} from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { startLocaleSync } from '@/services/localeSync'
let fake: FakeSupabase
let stops: Array<() => void> = []
beforeEach(() => {
localStorage.clear()
useLocaleStore.setState({ locale: 'fr' })
useAuthStore.setState({
status: 'loading',
session: null,
user: null,
profile: null,
roles: [],
recovery: false,
urlFailure: null,
})
fake = createFakeSupabase({
profiles: [fakeProfile({ locale: 'en' })],
profile_roles: [],
})
mocks.fake = fake
stops = [useAuthStore.getState().start(), startLocaleSync()]
})
afterEach(() => stops.forEach((s) => s()))
describe('locale sync', () => {
it('applies the account locale once when the profile loads', async () => {
fake.emit('SIGNED_IN', fakeSession())
await flush()
expect(useLocaleStore.getState().locale).toBe('en')
expect(localStorage.getItem('osteo:locale')).toBe('en')
})
it('saves a language switch to profiles.locale while signed in', async () => {
fake.emit('SIGNED_IN', fakeSession())
await flush()
useLocaleStore.getState().setLocale('fr')
await flush()
expect(fake.tables.profiles[0].locale).toBe('fr')
expect(useAuthStore.getState().profile?.locale).toBe('fr')
})
it('leaves the profile alone when signed out', async () => {
fake.emit('INITIAL_SESSION', null)
useLocaleStore.getState().setLocale('fr')
await flush()
expect(fake.tables.profiles[0].locale).toBe('en')
})
})
@@ -0,0 +1,93 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import { cleanup, render, screen } from '@testing-library/react'
import userEvent from '@testing-library/user-event'
import { MemoryRouter, Route, Routes } from 'react-router-dom'
import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
import AppLayout from '@/components/shell/AppLayout'
import { monogram } from '@/components/shell/UserBadge'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { fr } from '@/i18n/fr'
let fake: FakeSupabase
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
fake = createFakeSupabase()
mocks.fake = fake
useAuthStore.setState({
status: 'signed_in',
user: fakeUser(),
profile: fakeProfile({ display_name: 'Alice Local' }),
roles: [],
})
})
afterEach(cleanup)
function mount(path = '/app') {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/" element={<p>local tool</p>} />
<Route path="/app" element={<AppLayout />}>
<Route index element={<p>dashboard page</p>} />
<Route path="account" element={<p>account page</p>} />
</Route>
</Routes>
</MemoryRouter>,
)
}
describe('AppLayout', () => {
it('renders the sidebar navigation, the user and the page', () => {
mount()
const nav = screen.getByRole('navigation', { name: fr['shell.nav_label'] })
expect(nav).toHaveTextContent(fr['shell.nav.dashboard'])
expect(nav).toHaveTextContent(fr['shell.nav.account'])
expect(nav).toHaveTextContent(fr['shell.nav.local_tool'])
expect(screen.getAllByText('Alice Local').length).toBeGreaterThan(0)
expect(screen.getByText('dashboard page')).toBeInTheDocument()
})
it('marks the active destination', () => {
mount('/app/account')
const link = screen.getByRole('link', { name: new RegExp(fr['shell.nav.account']) })
expect(link).toHaveAttribute('aria-current', 'page')
})
it('opens the mobile drawer from the menu button and closes it on navigation', async () => {
const user = userEvent.setup()
mount()
await user.click(screen.getByRole('button', { name: fr['shell.open_menu'] }))
const drawer = await screen.findByRole('dialog', { name: fr['shell.nav_label'] })
expect(drawer).toBeInTheDocument()
const links = screen.getAllByRole('link', { name: new RegExp(fr['shell.nav.account']) })
await user.click(links[links.length - 1])
expect(await screen.findByText('account page')).toBeInTheDocument()
})
it('signs out and returns to the local tool', async () => {
const user = userEvent.setup()
mount()
const [button] = screen.getAllByRole('button', { name: fr['shell.sign_out'] })
await user.click(button)
expect(fake.auth.signOut).toHaveBeenCalled()
expect(await screen.findByText('local tool')).toBeInTheDocument()
})
})
describe('monogram', () => {
it('takes initials, else two letters, else ?', () => {
expect(monogram('Alice Local', undefined)).toBe('AL')
expect(monogram('Alice', undefined)).toBe('AL')
expect(monogram(undefined, 'bob@x.test')).toBe('BO')
expect(monogram('', '')).toBe('?')
})
})
+107
View File
@@ -0,0 +1,107 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
import {
createFakeSupabase,
fakeSession,
flush,
type FakeSupabase,
} from '../helpers/fakeSupabase'
const mocks = vi.hoisted(() => ({ fake: null as unknown }))
vi.mock('@/lib/supabase', () => ({
getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null,
isSupabaseConfigured: () => mocks.fake !== null,
}))
import { useAuthStore } from '@/state/authStore'
const INITIAL = {
status: 'loading' as const,
session: null,
user: null,
profile: null,
roles: [],
recovery: false,
urlFailure: null,
}
let fake: FakeSupabase
let stop: () => void = () => undefined
beforeEach(() => {
useAuthStore.setState(INITIAL)
fake = createFakeSupabase()
fake.tables.profile_roles = [
{ user_id: 'user-1', role: 'admin', revoked_at: null },
{ user_id: 'user-1', role: 'support', revoked_at: '2026-01-01' },
]
mocks.fake = fake
})
afterEach(() => stop())
describe('authStore', () => {
it('is unavailable when no backend is configured', () => {
mocks.fake = null
stop = useAuthStore.getState().start()
expect(useAuthStore.getState().status).toBe('unavailable')
})
it('loads the profile and active roles after SIGNED_IN', async () => {
stop = useAuthStore.getState().start()
expect(fake.auth.initialize).toHaveBeenCalled()
fake.emit('SIGNED_IN', fakeSession())
expect(useAuthStore.getState().status).toBe('signed_in')
await flush()
const s = useAuthStore.getState()
expect(s.profile?.display_name).toBe('Alice Local')
expect(s.roles).toEqual(['admin'])
})
it('clears everything on SIGNED_OUT and on an INITIAL_SESSION without session', async () => {
stop = useAuthStore.getState().start()
fake.emit('INITIAL_SESSION', null)
expect(useAuthStore.getState().status).toBe('signed_out')
fake.emit('SIGNED_IN', fakeSession())
await flush()
fake.emit('SIGNED_OUT', null)
expect(useAuthStore.getState()).toMatchObject({
status: 'signed_out',
user: null,
profile: null,
roles: [],
})
})
it('flags a recovery link until the password is saved', () => {
stop = useAuthStore.getState().start()
fake.emit('PASSWORD_RECOVERY', fakeSession())
expect(useAuthStore.getState().recovery).toBe(true)
useAuthStore.getState().clearRecovery()
expect(useAuthStore.getState().recovery).toBe(false)
})
it('records a URL exchange failure for the landing routes', async () => {
fake.auth.initialize.mockResolvedValueOnce({
error: { code: 'flow_state_expired', message: 'x', status: 400 },
})
stop = useAuthStore.getState().start()
await flush()
expect(useAuthStore.getState().urlFailure).toBe('link_expired')
})
it('updateProfile writes the row and keeps the store in sync', async () => {
stop = useAuthStore.getState().start()
fake.emit('SIGNED_IN', fakeSession())
await flush()
await useAuthStore.getState().updateProfile({ first_name: 'Alice' })
expect(useAuthStore.getState().profile?.first_name).toBe('Alice')
expect(fake.tables.profiles[0].first_name).toBe('Alice')
})
it('signOut calls the client and resets the state', async () => {
stop = useAuthStore.getState().start()
fake.emit('SIGNED_IN', fakeSession())
await useAuthStore.getState().signOut()
expect(fake.auth.signOut).toHaveBeenCalled()
expect(useAuthStore.getState().status).toBe('signed_out')
})
})
+5 -1
View File
@@ -21,6 +21,9 @@ TAGLINE=$(js_escape "${APP_TAGLINE:-Outils pour ostéopathes animaliers}")
# 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:-}")
# OAuth buttons offered by the auth screens ("google,apple"); the Supabase
# project must enable the same providers.
AUTH_PROVIDERS=$(js_escape "${APP_AUTH_PROVIDERS:-}")
cat > "$ENV_JS" <<EOF
window.__APP_CONFIG__ = {
@@ -29,7 +32,8 @@ window.__APP_CONFIG__ = {
footerName: "${FOOTER_NAME}",
tagline: "${TAGLINE}",
supabaseUrl: "${SUPABASE_URL}",
supabaseAnonKey: "${SUPABASE_ANON_KEY}"
supabaseAnonKey: "${SUPABASE_ANON_KEY}",
authProviders: "${AUTH_PROVIDERS}"
};
EOF
+45
View File
@@ -0,0 +1,45 @@
# Design references
Permanent graphic references for the application, validated by the owner.
A screen built later follows these before any new proposal; a change of
direction needs a new validated file here, never a silent drift.
## faunosteo-etape7-maquettes-validees.png
Validated 2026-10-12 with Step 7 (identity). One image, seven views:
1. Connexion (desktop): split layout, brand panel left with a photo and the
tagline, white card right, Google + Apple under the form.
2. Inscription (desktop): centred card, password rules shown as a checklist.
3. Tableau de bord (desktop): sidebar (Tableau de bord, Bilans, Clients,
Animaux, Agenda, Fiches anatomiques, Mon compte, Paramètres, Réduire),
top bar with a bell and the user menu, four stat tiles, "Accès rapides"
and "Derniers bilans".
4. Profil et paramètres (desktop): "Mon compte" with tabs (Profil, Cabinet et
activité, Sécurité, Préférences), avatar with "Modifier la photo",
professional block with activity name, SIRET, activity type, website.
5. Menu mobile: drawer with the same navigation and "Se déconnecter".
6. Tableau de bord (mobile): hamburger, bell, avatar, stat tiles, quick
actions, bottom tab bar (Accueil, Bilans, Agenda, Profil).
7. Profil (mobile): tabs Profil / Sécurité, bottom tab bar.
### What the mockup shows beyond Step 7
The mockup is the target for the whole SaaS shell. Items it shows that no
step has built yet, with the step that owns them:
| Element | Owner |
|---|---|
| Bilans, Clients, Animaux, Agenda, Fiches anatomiques entries and screens | Steps 9 to 16 (clients/animals, cloud reports, agenda) |
| Stat tiles (bilans créés, clients, animaux, rendez-vous) and "Derniers bilans" | once the reports and agenda tables exist; never invented numbers |
| Notification bell | notifications step |
| Avatar photo and "Modifier la photo" | Step 8 (files foundation, avatar bucket) |
| Bottom tab bar on mobile | with the first list screens (today only two destinations) |
| Tabs in Mon compte | optional restructuring when "Cabinet et activité" gains fields (activity type, website) |
| Password rule checklist | the mockup says 8 characters; the server policy is 12 with lower, upper and digit (config.toml); the hint text follows the server |
Step 7 as shipped (2026-10-11, validated 2026-10-12): login, signup,
password recovery, dashboard (profile completeness, local tool, account
facts), Mon compte as stacked sections, sidebar + drawer, FR/EN. The owner
accepted that the Home of the local tool (`/`) shows no sidebar while signed
in, only the "Mon espace" button, until the tool is integrated into `/app`.
Binary file not shown.

After

Width:  |  Height:  |  Size: 1.5 MiB

+132
View File
@@ -0,0 +1,132 @@
# Identity: auth, profile, /app shell (Step 7)
Validated by the owner on 2026-10-12. Graphic reference:
`docs/design/faunosteo-etape7-maquettes-validees.png` (see `docs/design/README.md`
for what the mockup shows beyond this step).
Source of truth for the signed-in space added in Step 7. The local tool
(`/`, `/new`, `/editor`) is untouched and needs no account; the two live side
by side until the plan's Step 14 decides what goes behind authentication.
## 1. Routes
| Route | Guard | Screen |
|---|---|---|
| `/login` | visitor only (`RedirectIfSignedIn`) | email + password, OAuth buttons per `authProviders`, link to signup / forgot |
| `/signup` | visitor only | display name, email, password ×2 → "check your inbox" step |
| `/forgot-password` | visitor only | email → "link sent" step |
| `/reset-password` | none; needs the recovery session | new password ×2; "invalid or expired link" otherwise |
| `/auth/callback` | none | landing of OAuth redirects and confirmation links; waits for the session then goes to `/app` (or `?next=`) |
| `/app` | `RequireAuth` | dashboard: greeting, profile completeness card, local tool card, account card |
| `/app/account` | `RequireAuth` | Mon compte: personal, professional, preferences (language, timezone), security (password, MFA note, sign out) |
`RequireAuth` waits for the client to read the persisted session, then sends
a visitor to `/login?next=<path>`; `next` is honoured only when it is a
same-origin path (`safeNextPath`). `/app/*` under the guard renders inside
`AppLayout` (desktop sidebar, light top bar, mobile drawer).
A deployment without Supabase (`APP_SUPABASE_URL` empty) shows an
"unavailable" notice on the auth screens; `/app` redirects to `/login`; the
Home header shows no entry to the space. With Supabase configured, the Home
header shows "Se connecter" or "Mon espace".
## 2. Session and profile in the app
- `state/authStore.ts` subscribes to `client.auth.onAuthStateChange` after
`client.auth.initialize()` (which also exchanges the PKCE code found in the
URL). Status: `loading | unavailable | signed_out | signed_in`. On sign-in it
loads `profiles` (own row) and the active `profile_roles`.
- `services/localeSync.ts`: when a profile loads, its `locale` wins over the
device choice (once per sign-in); while signed in, switching the language
(header toggle or the Preferences select) writes `profiles.locale`.
- Profile writes go through `updateOwnProfile` (`packages/supabase`), one
PATCH per account section; the columns are the ones the migrations grant
(`display_name, first_name, last_name, phone, locale, timezone,
practice_name, professional_title, siret`). `active`,
`phone_verified_at` and roles are server-only.
- Platform roles are read-only badges (`shell.role.*`); no admin screen yet.
- GoTrue errors never reach the screen: `classifyAuthError` folds codes into a
closed `AuthFailureKind`, phrased by `auth.failure.*`.
## 3. Server configuration
`supabase/config.toml`:
- email/password with confirmation mandatory, password policy 12 chars +
lower/upper/digit (mirrored client-side in `src/auth/validation.ts`);
- `[auth.external.google]` / `[auth.external.apple]` read their ids from
`env(SUPABASE_AUTH_EXTERNAL_<PROVIDER>_CLIENT_ID|SECRET)`; both are
`enabled = false` until the ids exist (put them in `supabase/.env`, gitignored,
then flip `enabled`). Google needs an OAuth client with the redirect
`http://127.0.0.1:54321/auth/v1/callback` (local) or
`https://<project>.supabase.co/auth/v1/callback`; Apple needs a paid developer
account and a Services ID (BACKEND_ARCHITECTURE §2);
- `[auth.mfa.totp]` enrolment and verification are on server-side;
- redirect URLs allow `http://127.0.0.1:5173/**` and `http://localhost:5173/**`
(local only). On the hosted project the allowlist is exact, never a host
wildcard: Site URL `https://<prod-origin>`, Redirect URLs
`https://<prod-origin>/auth/callback` and `https://<prod-origin>/reset-password`.
A broad pattern there turns `emailRedirectTo` / `redirectTo` into a
server-side open redirect.
The app side: `APP_AUTH_PROVIDERS=google,apple` (Docker) or
`VITE_AUTH_PROVIDERS` (dev) lists the buttons to show. Showing a button for a
provider the server has not enabled yields the phrased error
"this sign-in method is not enabled".
PKCE pitfall: a confirmation or recovery link must be opened in the browser
that made the request (the code verifier lives in its localStorage). Opened
elsewhere, the email is still confirmed server-side but no session opens; the
callback page says so and the user signs in normally.
## 4. MFA: what the foundations have, what is missing
Architecture §2 wants TOTP mandatory for `owner/admin/moderator/support`,
enforced by an RLS helper `has_mfa()` on admin tables. Today:
- server: TOTP enrolment/verification enabled (this step); nothing enforces it;
- SQL: no `private.has_mfa()` helper (would read `auth.jwt() ->> 'aal' = 'aal2'`);
the role helpers `private.is_platform_*` ignore the assurance level;
- app: no enrolment UI (QR + code), no `aal2` step-up on sign-in;
- there is no admin table or screen yet to protect.
The Security section shows a note instead. To close the gap (a later step):
migration adding `private.has_mfa()` and folding it into `is_platform_*` (or
into the policies of the first admin table) with pgTAP allowed/denied cases;
enrolment + challenge screens in Mon compte; step-up at sign-in for accounts
holding a platform role.
## 5. Manual validation (local stack)
```bash
pnpm db:start # prints API URL + anon key; Mailpit at http://127.0.0.1:54324
VITE_SUPABASE_URL=http://127.0.0.1:54321 VITE_SUPABASE_ANON_KEY=<anon key> \
VITE_AUTH_PROVIDERS=google pnpm dev
```
1. `/app` while signed out → `/login?next=%2Fapp`. The login card shows a
Google button (not functional until the provider is enabled: expect the
"not enabled" message).
2. Wrong password → "E-mail ou mot de passe incorrect". Seeded account
`alice@faunosteo.local` / `LocalDev-only-password-1` → lands on `/app`.
3. Dashboard: greeting, "À compléter : Prénom, Nom", "Adresse confirmée",
no platform role (owner@ shows "Propriétaire plateforme").
4. Mon compte: fill professional title / practice / SIRET → "Modifications
enregistrées"; SIRET `1234` → inline error, nothing saved. Language select
or the FR/EN toggle → the UI switches; reload → the account language is
applied (profiles.locale in Studio).
5. Mobile (375 px): hamburger opens the drawer; navigation closes it; no
horizontal scroll on login, dashboard, account.
6. Home shows "Mon espace" while signed in; sidebar "Se déconnecter" → Home with
"Se connecter"; `/app` guarded again.
7. `/signup` with a new address → "Vérifiez votre boîte mail"; open Mailpit,
click the confirmation link in the same browser → `/app` signed in,
"Adresse confirmée".
8. `/forgot-password` → Mailpit recovery link → `/reset-password` → new
password → `/app`; sign out and sign in with the new password.
9. REST: anon cannot read profiles (`42501`), alice reads one row only
(SUPABASE.md §8).
Automated: `pnpm test:run` (auth store, locale sync, forms, guards, shell,
dashboard, account, pgTAP 009), plus the headless end-to-end run described in
the Step 7 report (not part of CI).
+7
View File
@@ -216,6 +216,13 @@ Definition of Done: architecture Sprint 1 identity part; audit_logs receives rol
Risks: Apple sign-in setup cost; phone provider pending (Q7).
```
Step 7 implementation note (2026-10-11): shipped as `docs/development/IDENTITY.md`.
Deviations: no TanStack Query (a zustand store covers the profile read/update of this
step; the query layer comes with the first list screens); `platform_invitations` and the
MFA helper not written (no admin screen to protect yet, gap documented in IDENTITY.md §4);
professional fields added to `profiles` as declared free text (verification = Step 11);
Google/Apple wired in config.toml behind env ids, buttons behind `APP_AUTH_PROVIDERS`.
```text
Step 8
Name: Files foundation (Storage)
+7 -2
View File
@@ -233,8 +233,13 @@ 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.
Both empty (the default) keeps the app in its local-only mode:
`getSupabaseClient()` returns null, the auth screens show an "unavailable"
notice and `/app` redirects to `/login`. `APP_AUTH_PROVIDERS` /
`VITE_AUTH_PROVIDERS` (`google,apple`) lists the OAuth buttons to show.
Sign-in, sign-up, email confirmation, password recovery, the `/app` shell
and Mon compte are documented in `IDENTITY.md` (routes, session handling,
provider setup, MFA gap, manual validation).
## 10. Self-hosted parity
+157
View File
@@ -0,0 +1,157 @@
import type { AuthError, Provider, Session, User } from '@supabase/supabase-js'
import type { FaunosteoClient } from './client'
/** OAuth providers the app may offer. Phone and others wait for later steps. */
export type OAuthProvider = Extract<Provider, 'google' | 'apple'>
/**
* Closed set of reasons the UI knows how to phrase. Everything GoTrue reports
* is folded into one of these; the raw message never reaches the screen.
*/
export type AuthFailureKind =
| 'invalid_credentials'
| 'email_not_confirmed'
| 'user_exists'
| 'weak_password'
| 'same_password'
| 'invalid_email'
| 'rate_limited'
| 'link_expired'
| 'session_expired'
| 'reauthentication_needed'
| 'provider_disabled'
| 'network'
| 'unknown'
export class AuthFailure extends Error {
readonly kind: AuthFailureKind
constructor(kind: AuthFailureKind, cause?: unknown) {
super(`auth: ${kind}`, { cause })
this.name = 'AuthFailure'
this.kind = kind
}
}
const CODE_TO_KIND: Record<string, AuthFailureKind> = {
invalid_credentials: 'invalid_credentials',
email_not_confirmed: 'email_not_confirmed',
user_already_exists: 'user_exists',
email_exists: 'user_exists',
weak_password: 'weak_password',
same_password: 'same_password',
email_address_invalid: 'invalid_email',
validation_failed: 'invalid_email',
over_request_rate_limit: 'rate_limited',
over_email_send_rate_limit: 'rate_limited',
otp_expired: 'link_expired',
flow_state_not_found: 'link_expired',
flow_state_expired: 'link_expired',
bad_code_verifier: 'link_expired',
session_expired: 'session_expired',
session_not_found: 'session_expired',
refresh_token_not_found: 'session_expired',
reauthentication_needed: 'reauthentication_needed',
reauthentication_not_valid: 'reauthentication_needed',
provider_disabled: 'provider_disabled',
oauth_provider_not_supported: 'provider_disabled',
email_provider_disabled: 'provider_disabled',
signup_disabled: 'provider_disabled',
}
/** Maps a GoTrue error to a closed kind; code first, HTTP status as fallback. */
export function classifyAuthError(error: AuthError): AuthFailureKind {
const code = (error as { code?: string }).code
if (code && CODE_TO_KIND[code]) return CODE_TO_KIND[code]
if (error.status === 429) return 'rate_limited'
if (error.status === 400 && /invalid login/i.test(error.message)) {
return 'invalid_credentials'
}
if (error.status === undefined || error.status === 0) return 'network'
return 'unknown'
}
function fail(error: AuthError): never {
throw new AuthFailure(classifyAuthError(error), error)
}
export interface EmailPasswordCredentials {
email: string
password: string
}
export interface SignUpInput extends EmailPasswordCredentials {
displayName: string
/** Stored in user metadata; the profile trigger reads it. */
locale: 'fr' | 'en'
/** Absolute URL the confirmation link lands on. */
emailRedirectTo: string
}
export interface SignUpResult {
/** Null while the email is not confirmed (confirmations enabled). */
session: Session | null
user: User | null
}
export async function signInWithPassword(
client: FaunosteoClient,
credentials: EmailPasswordCredentials,
): Promise<Session> {
const { data, error } = await client.auth.signInWithPassword(credentials)
if (error) fail(error)
return data.session
}
export async function signUpWithPassword(
client: FaunosteoClient,
input: SignUpInput,
): Promise<SignUpResult> {
const { data, error } = await client.auth.signUp({
email: input.email,
password: input.password,
options: {
emailRedirectTo: input.emailRedirectTo,
data: { display_name: input.displayName, locale: input.locale },
},
})
if (error) fail(error)
return { session: data.session, user: data.user }
}
/** Starts the redirect flow; the browser leaves the page on success. */
export async function signInWithOAuth(
client: FaunosteoClient,
provider: OAuthProvider,
redirectTo: string,
): Promise<void> {
const { error } = await client.auth.signInWithOAuth({
provider,
options: { redirectTo },
})
if (error) fail(error)
}
export async function sendPasswordReset(
client: FaunosteoClient,
email: string,
redirectTo: string,
): Promise<void> {
const { error } = await client.auth.resetPasswordForEmail(email, {
redirectTo,
})
if (error) fail(error)
}
/** Needs a live session (recovery link or signed-in user). */
export async function updatePassword(
client: FaunosteoClient,
password: string,
): Promise<void> {
const { error } = await client.auth.updateUser({ password })
if (error) fail(error)
}
export async function signOut(client: FaunosteoClient): Promise<void> {
const { error } = await client.auth.signOut()
if (error) fail(error)
}
+9
View File
@@ -306,6 +306,9 @@ export type Database = {
locale: string
phone: string | null
phone_verified_at: string | null
practice_name: string | null
professional_title: string | null
siret: string | null
timezone: string
updated_at: string
}
@@ -320,6 +323,9 @@ export type Database = {
locale?: string
phone?: string | null
phone_verified_at?: string | null
practice_name?: string | null
professional_title?: string | null
siret?: string | null
timezone?: string
updated_at?: string
}
@@ -333,6 +339,9 @@ export type Database = {
locale?: string
phone?: string | null
phone_verified_at?: string | null
practice_name?: string | null
professional_title?: string | null
siret?: string | null
timezone?: string
updated_at?: string
}
+25 -3
View File
@@ -3,6 +3,8 @@ export {
type FaunosteoClient,
type SupabaseConnection,
} from './client'
/** Auth types the app needs without depending on supabase-js directly. */
export type { AuthChangeEvent, Session, User } from '@supabase/supabase-js'
export type {
Database,
Enums,
@@ -15,12 +17,32 @@ 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'>
export {
AuthFailure,
classifyAuthError,
sendPasswordReset,
signInWithOAuth,
signInWithPassword,
signOut,
signUpWithPassword,
updatePassword,
type AuthFailureKind,
type EmailPasswordCredentials,
type OAuthProvider,
type SignUpInput,
type SignUpResult,
} from './auth'
export {
fetchOwnProfile,
ProfileError,
updateOwnProfile,
type OwnProfilePatch,
type Profile,
} from './profiles'
/** owner | admin | moderator | support. Not a professional status. */
export type PlatformRole = Enums<'platform_role'>
export { fetchOwnPlatformRoles, type PlatformRole } from './platform-roles'
export { publishSheetVersion } from './anatomical-sheets'
/** Row of public.species. */
+18
View File
@@ -0,0 +1,18 @@
import type { FaunosteoClient } from './client'
import type { Enums } from './database.types'
export type PlatformRole = Enums<'platform_role'>
/** Active platform roles of the signed-in user (RLS: own rows, or any as admin). */
export async function fetchOwnPlatformRoles(
client: FaunosteoClient,
userId: string,
): Promise<PlatformRole[]> {
const { data, error } = await client
.from('profile_roles')
.select('role')
.eq('user_id', userId)
.is('revoked_at', null)
if (error) throw new Error(error.message, { cause: error })
return data.map((row) => row.role)
}
+55
View File
@@ -0,0 +1,55 @@
import type { FaunosteoClient } from './client'
import type { Tables, TablesUpdate } from './database.types'
export type Profile = Tables<'profiles'>
/** Columns the signed-in user may change (column grant in the profiles migrations). */
export type OwnProfilePatch = Pick<
TablesUpdate<'profiles'>,
| 'display_name'
| 'first_name'
| 'last_name'
| 'phone'
| 'locale'
| 'timezone'
| 'practice_name'
| 'professional_title'
| 'siret'
>
export class ProfileError extends Error {
readonly code: string | null
constructor(message: string, code: string | null, cause?: unknown) {
super(message, { cause })
this.name = 'ProfileError'
this.code = code
}
}
/** The row RLS lets the user see: their own. Null when the trigger has not run yet. */
export async function fetchOwnProfile(
client: FaunosteoClient,
userId: string,
): Promise<Profile | null> {
const { data, error } = await client
.from('profiles')
.select('*')
.eq('id', userId)
.maybeSingle()
if (error) throw new ProfileError(error.message, error.code, error)
return data
}
export async function updateOwnProfile(
client: FaunosteoClient,
userId: string,
patch: OwnProfilePatch,
): Promise<Profile> {
const { data, error } = await client
.from('profiles')
.update(patch)
.eq('id', userId)
.select('*')
.single()
if (error) throw new ProfileError(error.message, error.code, error)
return data
}
+25
View File
@@ -0,0 +1,25 @@
import { describe, expect, it } from 'vitest'
import type { AuthError } from '@supabase/supabase-js'
import { classifyAuthError } from '../src/auth'
function err(patch: Partial<AuthError> & { code?: string }): AuthError {
return { name: 'AuthApiError', message: 'm', ...patch } as AuthError
}
describe('classifyAuthError', () => {
it('maps GoTrue codes to the closed kinds the UI phrases', () => {
expect(classifyAuthError(err({ code: 'invalid_credentials', status: 400 }))).toBe('invalid_credentials')
expect(classifyAuthError(err({ code: 'email_not_confirmed', status: 400 }))).toBe('email_not_confirmed')
expect(classifyAuthError(err({ code: 'user_already_exists', status: 422 }))).toBe('user_exists')
expect(classifyAuthError(err({ code: 'weak_password', status: 422 }))).toBe('weak_password')
expect(classifyAuthError(err({ code: 'otp_expired', status: 403 }))).toBe('link_expired')
expect(classifyAuthError(err({ code: 'bad_code_verifier', status: 400 }))).toBe('link_expired')
})
it('falls back on the HTTP status, then network, then unknown', () => {
expect(classifyAuthError(err({ status: 429 }))).toBe('rate_limited')
expect(classifyAuthError(err({ status: 400, message: 'Invalid login credentials' }))).toBe('invalid_credentials')
expect(classifyAuthError(err({ status: 0 }))).toBe('network')
expect(classifyAuthError(err({ status: 500, code: 'unexpected_failure' }))).toBe('unknown')
})
})
@@ -86,6 +86,9 @@ const expectedColumns = {
'locale',
'phone',
'phone_verified_at',
'practice_name',
'professional_title',
'siret',
'timezone',
'updated_at',
],
+25 -4
View File
@@ -69,7 +69,12 @@ enabled = false
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"]
additional_redirect_urls = [
"http://127.0.0.1:5173",
"http://localhost:5173",
"http://127.0.0.1:5173/**",
"http://localhost:5173/**",
]
jwt_expiry = 3600
enable_refresh_token_rotation = true
refresh_token_reuse_interval = 10
@@ -107,9 +112,25 @@ enable_confirmations = false
max_enrolled_factors = 10
[auth.mfa.totp]
# Enrolment opens with the identity step (mandatory for platform staff).
enroll_enabled = false
verify_enabled = false
# Server side ready since Step 7; the enrolment UI and the has_mfa() helper
# enforcing it for platform staff are still to come (SUPABASE.md §11).
enroll_enabled = true
verify_enabled = true
# OAuth providers (Step 7). Values come from the environment: the CLI reads
# supabase/.env (gitignored) or the shell. Disabled until the ids exist.
# Google: https://supabase.com/docs/guides/auth/social-login/auth-google
[auth.external.google]
enabled = false
client_id = "env(SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID)"
secret = "env(SUPABASE_AUTH_EXTERNAL_GOOGLE_SECRET)"
skip_nonce_check = false
# Apple needs a paid developer account + a Services ID (BACKEND_ARCHITECTURE §2).
[auth.external.apple]
enabled = false
client_id = "env(SUPABASE_AUTH_EXTERNAL_APPLE_CLIENT_ID)"
secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)"
[edge_runtime]
# No Edge Function before the files/webhooks steps; keeps the local stack light.
@@ -0,0 +1,23 @@
-- Step 7 identity: professional information on the account profile.
-- Free text declared by the practitioner, shown in "Mon compte". Verification
-- (SIRET check, documents, badge) belongs to the Professional Verification
-- domain (DOMAIN_MAP §2) and lands with its own tables; nothing here is trusted.
alter table public.profiles
add column practice_name text
constraint profiles_practice_name_length check (char_length(practice_name) between 1 and 120),
add column professional_title text
constraint profiles_professional_title_length check (char_length(professional_title) between 1 and 80),
-- French SIRET: 14 digits, format only (no Luhn, no registry lookup).
add column siret text
constraint profiles_siret_format check (siret ~ '^[0-9]{14}$');
comment on column public.profiles.practice_name is
'Cabinet / practice name declared by the user. Unverified.';
comment on column public.profiles.professional_title is
'Professional title declared by the user (e.g. ostéopathe animalier). Unverified.';
comment on column public.profiles.siret is
'SIRET declared by the user, 14 digits, format-checked only. Verification = later domain.';
-- Same rule as the other user-editable columns: column-level UPDATE, own row through RLS.
grant update (practice_name, professional_title, siret) on public.profiles to authenticated;
@@ -0,0 +1,72 @@
-- Professional columns on profiles: own-row update, format checks, denied paths.
begin;
select plan(13);
insert into auth.users (id, email) values
('00000000-0000-0000-0000-00000000000a', 'alice@test.local'),
('00000000-0000-0000-0000-00000000000b', 'bob@test.local');
select has_column('public', 'profiles', 'practice_name', 'practice_name exists');
select has_column('public', 'profiles', 'professional_title', 'professional_title exists');
select has_column('public', 'profiles', 'siret', 'siret exists');
select is(
(select count(*)::int from information_schema.column_privileges
where table_schema = 'public' and table_name = 'profiles' and grantee = 'authenticated'
and privilege_type = 'UPDATE'
and column_name in ('practice_name', 'professional_title', 'siret')),
3,
'authenticated may update the three professional columns'
);
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
select lives_ok(
$$ update public.profiles
set practice_name = 'Cabinet Équilibre', professional_title = 'Ostéopathe animalier', siret = '12345678901234'
where id = '00000000-0000-0000-0000-00000000000a' $$,
'alice fills her professional information'
);
select is(
(select siret from public.profiles where id = '00000000-0000-0000-0000-00000000000a'),
'12345678901234',
'siret stored as declared'
);
select throws_ok(
$$ update public.profiles set siret = '1234' where id = '00000000-0000-0000-0000-00000000000a' $$,
'23514', null, 'siret must be 14 digits'
);
select throws_ok(
$$ update public.profiles set siret = '1234567890123a' where id = '00000000-0000-0000-0000-00000000000a' $$,
'23514', null, 'siret refuses letters'
);
select throws_ok(
$$ update public.profiles set practice_name = '' where id = '00000000-0000-0000-0000-00000000000a' $$,
'23514', null, 'empty practice_name refused (null clears it)'
);
select lives_ok(
$$ update public.profiles set siret = null, practice_name = null where id = '00000000-0000-0000-0000-00000000000a' $$,
'alice clears her professional information'
);
-- Bob's row is invisible to alice: the update touches zero rows.
select is(
(select count(*)::int from public.profiles where id = '00000000-0000-0000-0000-00000000000b'),
0,
'alice does not see bob'
);
select lives_ok(
$$ update public.profiles set practice_name = 'Hijack'
where id = '00000000-0000-0000-0000-00000000000b' $$,
'writing an invisible row raises nothing'
);
reset role;
select is(
(select practice_name from public.profiles where id = '00000000-0000-0000-0000-00000000000b'),
null,
'bob untouched'
);
select * from finish();
rollback;