From b10b227ee9ac05eab015a326eb9ddf8a28d453a8 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 11 Oct 2026 23:16:13 +0200 Subject: [PATCH 01/10] feat(supabase): auth, profile and roles services; professional columns on profiles; OAuth + TOTP config - packages/supabase: signIn/signUp/OAuth/reset/updatePassword/signOut wrappers with a closed AuthFailure kind, fetch/update own profile, own platform roles - migration 20261011100000: practice_name, professional_title, siret (format-checked, column grants); pgTAP 009; database.types regenerated - config.toml: TOTP enroll/verify on, [auth.external.google|apple] via env(), wildcard redirect URLs - app config: authProviders (APP_AUTH_PROVIDERS / VITE_AUTH_PROVIDERS), entrypoint env.js, DEPLOY table - TODO: Step 7 plan --- .claude/tasks/TODO.md | 11 ++ DEPLOY.md | 1 + apps/app/src/config/env.ts | 30 +++- docker/entrypoint.sh | 6 +- packages/supabase/src/auth.ts | 154 ++++++++++++++++++ packages/supabase/src/database.types.ts | 9 + packages/supabase/src/index.ts | 26 ++- packages/supabase/src/platform-roles.ts | 18 ++ packages/supabase/src/profiles.ts | 55 +++++++ .../supabase/tests/db/schema-types.test.ts | 3 + supabase/config.toml | 29 +++- .../20261011100000_profiles_professional.sql | 23 +++ supabase/tests/009_profiles_professional.sql | 72 ++++++++ 13 files changed, 427 insertions(+), 10 deletions(-) create mode 100644 packages/supabase/src/auth.ts create mode 100644 packages/supabase/src/platform-roles.ts create mode 100644 packages/supabase/src/profiles.ts create mode 100644 supabase/migrations/20261011100000_profiles_professional.sql create mode 100644 supabase/tests/009_profiles_professional.sql diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index e14a877f..bb29638a 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -114,6 +114,17 @@ 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 +- [ ] Step 7 — identity: auth, profile, roles, /app shell (started 2026-10-11, branch feature/step-07-identity-app-shell; direction graphique validée par l'utilisateur: identité actuelle conservée, maquettes = référence externe non versionnée). 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 + - [ ] 7.0 plan + branch + ctx7 cache (supabase-js auth, config.toml providers) + - [ ] 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 + - [ ] 7.2 migration 20261011100000_profiles_professional: practice_name, professional_title, siret (+ CHECKs, column grants); pgTAP 009; database.types regenerated (real stack) + schema-types map + - [ ] 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 + - [ ] 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 + - [ ] 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) + - [ ] 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 + - [ ] 7.7 Home coexistence: "Mon espace / Se connecter" entry on the header when configured; characterisation tests T12 unchanged with default config + - [ ] 7.8 tests: config, authStore (fake client), locale sync, forms (validation, errors, submit), guard redirect, layout nav, account save; i18n parity; pgTAP; root check + docker build + - [ ] 7.9 docs: SUPABASE.md auth section (providers env, Mailpit, MFA gap), CLAUDE.md map/architecture, CHANGELOG, plan note; memory (BDR, LRN, EVAL, journal); verifier + security gates; stop for user validation --- ## Phase A — DONE (kept for reference) diff --git a/DEPLOY.md b/DEPLOY.md index d4016952..ba9928ed 100644 --- a/DEPLOY.md +++ b/DEPLOY.md @@ -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 diff --git a/apps/app/src/config/env.ts b/apps/app/src/config/env.ts index 05cfa2ad..93d105ea 100644 --- a/apps/app/src/config/env.ts +++ b/apps/app/src/config/env.ts @@ -1,5 +1,5 @@ /// -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 = { +const DEFAULTS: Omit = { 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, + ), } } diff --git a/docker/entrypoint.sh b/docker/entrypoint.sh index 55231199..484a5e8e 100644 --- a/docker/entrypoint.sh +++ b/docker/entrypoint.sh @@ -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" < + +/** + * 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' + | '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 = { + 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', + 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 { + const { data, error } = await client.auth.signInWithPassword(credentials) + if (error) fail(error) + return data.session +} + +export async function signUpWithPassword( + client: FaunosteoClient, + input: SignUpInput, +): Promise { + 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 { + const { error } = await client.auth.signInWithOAuth({ + provider, + options: { redirectTo }, + }) + if (error) fail(error) +} + +export async function sendPasswordReset( + client: FaunosteoClient, + email: string, + redirectTo: string, +): Promise { + 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 { + const { error } = await client.auth.updateUser({ password }) + if (error) fail(error) +} + +export async function signOut(client: FaunosteoClient): Promise { + const { error } = await client.auth.signOut() + if (error) fail(error) +} diff --git a/packages/supabase/src/database.types.ts b/packages/supabase/src/database.types.ts index 1290eb9b..7e38c423 100644 --- a/packages/supabase/src/database.types.ts +++ b/packages/supabase/src/database.types.ts @@ -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 } diff --git a/packages/supabase/src/index.ts b/packages/supabase/src/index.ts index 7738d67e..484fb76e 100644 --- a/packages/supabase/src/index.ts +++ b/packages/supabase/src/index.ts @@ -15,12 +15,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. */ diff --git a/packages/supabase/src/platform-roles.ts b/packages/supabase/src/platform-roles.ts new file mode 100644 index 00000000..09ab8a08 --- /dev/null +++ b/packages/supabase/src/platform-roles.ts @@ -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 { + 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) +} diff --git a/packages/supabase/src/profiles.ts b/packages/supabase/src/profiles.ts new file mode 100644 index 00000000..98db9ec7 --- /dev/null +++ b/packages/supabase/src/profiles.ts @@ -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 { + 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 { + 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 +} diff --git a/packages/supabase/tests/db/schema-types.test.ts b/packages/supabase/tests/db/schema-types.test.ts index 584b3a4c..df272c5b 100644 --- a/packages/supabase/tests/db/schema-types.test.ts +++ b/packages/supabase/tests/db/schema-types.test.ts @@ -86,6 +86,9 @@ const expectedColumns = { 'locale', 'phone', 'phone_verified_at', + 'practice_name', + 'professional_title', + 'siret', 'timezone', 'updated_at', ], diff --git a/supabase/config.toml b/supabase/config.toml index a0120a9b..cc16863e 100644 --- a/supabase/config.toml +++ b/supabase/config.toml @@ -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. diff --git a/supabase/migrations/20261011100000_profiles_professional.sql b/supabase/migrations/20261011100000_profiles_professional.sql new file mode 100644 index 00000000..f2f5b019 --- /dev/null +++ b/supabase/migrations/20261011100000_profiles_professional.sql @@ -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; diff --git a/supabase/tests/009_profiles_professional.sql b/supabase/tests/009_profiles_professional.sql new file mode 100644 index 00000000..2b4fef06 --- /dev/null +++ b/supabase/tests/009_profiles_professional.sql @@ -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; From 0f7292f9b304395912fd85d7dd69d6c5d5accec1 Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 11 Oct 2026 23:16:57 +0200 Subject: [PATCH 02/10] test(config): authProviders parsing; fixture carries the new field --- apps/app/tests/unit/config.env.test.ts | 20 +++++++++++++++++++- apps/app/tests/unit/lib.supabase.test.ts | 1 + 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/apps/app/tests/unit/config.env.test.ts b/apps/app/tests/unit/config.env.test.ts index 5f57a985..51674ad7 100644 --- a/apps/app/tests/unit/config.env.test.ts +++ b/apps/app/tests/unit/config.env.test.ts @@ -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', + ]) + }) +}) diff --git a/apps/app/tests/unit/lib.supabase.test.ts b/apps/app/tests/unit/lib.supabase.test.ts index 9d471ec1..493c71e7 100644 --- a/apps/app/tests/unit/lib.supabase.test.ts +++ b/apps/app/tests/unit/lib.supabase.test.ts @@ -8,6 +8,7 @@ const base: AppConfig = { footerName: 'F', tagline: 'T', supabase: null, + authProviders: [], } describe('getSupabaseClient', () => { From c517ea267bc67a11abba5924e8744f83028279ec Mon Sep 17 00:00:00 2001 From: bchanot Date: Sun, 11 Oct 2026 23:29:13 +0200 Subject: [PATCH 03/10] =?UTF-8?q?feat(app):=20identity=20screens=20and=20/?= =?UTF-8?q?app=20shell=20=E2=80=94=20auth=20store,=20login/signup/reset=20?= =?UTF-8?q?flows,=20dashboard,=20account?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - state/authStore: session subscription (initialize + onAuthStateChange), profile + roles load, recovery flag, URL failure; services/localeSync: profiles.locale <-> localeStore - routes: /login, /signup, /forgot-password, /reset-password, /auth/callback; guards RequireAuth (next=) and RedirectIfSignedIn; /app (dashboard), /app/account behind the guard - shell: AppLayout (desktop sidebar, light top bar, mobile drawer), SidebarNav, UserBadge, SignOutButton - account: personal / professional / preferences / security sections, one save each, Zod validation with i18n keys - ui: Icon, FormField, Notice, ButtonLink (buttonClassName shared), PasswordField, OAuthButtons (config-driven) - Home header: Mon espace / Se connecter when Supabase is configured; local tool routes untouched - i18n: auth.*, shell.*, dashboard.*, account.*, home.space.* in fr + en --- apps/app/src/account/useProfileForm.ts | 55 +++++ apps/app/src/account/validation.ts | 80 +++++++ apps/app/src/app/App.tsx | 45 +++- .../app/src/app/guards/RedirectIfSignedIn.tsx | 14 ++ apps/app/src/app/guards/RequireAuth.tsx | 13 ++ apps/app/src/app/guards/SessionLoading.tsx | 19 ++ apps/app/src/app/providers/AuthProvider.tsx | 16 ++ apps/app/src/app/routes/HomeRoute.tsx | 5 +- apps/app/src/app/routes/app/AccountRoute.tsx | 35 +++ .../app/src/app/routes/app/DashboardRoute.tsx | 136 ++++++++++++ .../src/app/routes/auth/AuthCallbackRoute.tsx | 34 +++ .../app/routes/auth/ForgotPasswordRoute.tsx | 97 +++++++++ apps/app/src/app/routes/auth/LoginRoute.tsx | 115 ++++++++++ .../app/routes/auth/ResetPasswordRoute.tsx | 131 ++++++++++++ apps/app/src/app/routes/auth/SignupRoute.tsx | 200 ++++++++++++++++++ apps/app/src/auth/redirects.ts | 17 ++ apps/app/src/auth/useAuthFailureMessage.ts | 12 ++ apps/app/src/auth/validation.ts | 63 ++++++ .../components/account/PersonalInfoForm.tsx | 74 +++++++ .../components/account/PreferencesForm.tsx | 80 +++++++ .../account/ProfessionalInfoForm.tsx | 85 ++++++++ .../app/src/components/account/RoleBadges.tsx | 19 ++ apps/app/src/components/account/SaveRow.tsx | 20 ++ .../src/components/account/SectionCard.tsx | 28 +++ .../src/components/account/SecurityPanel.tsx | 133 ++++++++++++ apps/app/src/components/auth/AuthLayout.tsx | 78 +++++++ apps/app/src/components/auth/AuthLink.tsx | 11 + apps/app/src/components/auth/OAuthButtons.tsx | 65 ++++++ .../app/src/components/auth/PasswordField.tsx | 30 +++ .../src/components/auth/UnavailableNotice.tsx | 21 ++ .../src/components/brand/HomeSpaceLink.tsx | 25 +++ apps/app/src/components/shell/AppLayout.tsx | 77 +++++++ .../app/src/components/shell/MobileDrawer.tsx | 74 +++++++ apps/app/src/components/shell/SidebarNav.tsx | 60 ++++++ .../src/components/shell/SignOutButton.tsx | 36 ++++ apps/app/src/components/shell/UserBadge.tsx | 38 ++++ apps/app/src/components/ui/Button.tsx | 21 +- apps/app/src/components/ui/ButtonLink.tsx | 17 ++ apps/app/src/components/ui/FormField.tsx | 54 +++++ apps/app/src/components/ui/Icon.tsx | 63 ++++++ apps/app/src/components/ui/Notice.tsx | 31 +++ apps/app/src/i18n/en.ts | 191 +++++++++++++++++ apps/app/src/i18n/fr.ts | 193 +++++++++++++++++ apps/app/src/services/localeSync.ts | 43 ++++ apps/app/src/state/authStore.ts | 153 ++++++++++++++ packages/supabase/src/index.ts | 2 + 46 files changed, 2798 insertions(+), 11 deletions(-) create mode 100644 apps/app/src/account/useProfileForm.ts create mode 100644 apps/app/src/account/validation.ts create mode 100644 apps/app/src/app/guards/RedirectIfSignedIn.tsx create mode 100644 apps/app/src/app/guards/RequireAuth.tsx create mode 100644 apps/app/src/app/guards/SessionLoading.tsx create mode 100644 apps/app/src/app/providers/AuthProvider.tsx create mode 100644 apps/app/src/app/routes/app/AccountRoute.tsx create mode 100644 apps/app/src/app/routes/app/DashboardRoute.tsx create mode 100644 apps/app/src/app/routes/auth/AuthCallbackRoute.tsx create mode 100644 apps/app/src/app/routes/auth/ForgotPasswordRoute.tsx create mode 100644 apps/app/src/app/routes/auth/LoginRoute.tsx create mode 100644 apps/app/src/app/routes/auth/ResetPasswordRoute.tsx create mode 100644 apps/app/src/app/routes/auth/SignupRoute.tsx create mode 100644 apps/app/src/auth/redirects.ts create mode 100644 apps/app/src/auth/useAuthFailureMessage.ts create mode 100644 apps/app/src/auth/validation.ts create mode 100644 apps/app/src/components/account/PersonalInfoForm.tsx create mode 100644 apps/app/src/components/account/PreferencesForm.tsx create mode 100644 apps/app/src/components/account/ProfessionalInfoForm.tsx create mode 100644 apps/app/src/components/account/RoleBadges.tsx create mode 100644 apps/app/src/components/account/SaveRow.tsx create mode 100644 apps/app/src/components/account/SectionCard.tsx create mode 100644 apps/app/src/components/account/SecurityPanel.tsx create mode 100644 apps/app/src/components/auth/AuthLayout.tsx create mode 100644 apps/app/src/components/auth/AuthLink.tsx create mode 100644 apps/app/src/components/auth/OAuthButtons.tsx create mode 100644 apps/app/src/components/auth/PasswordField.tsx create mode 100644 apps/app/src/components/auth/UnavailableNotice.tsx create mode 100644 apps/app/src/components/brand/HomeSpaceLink.tsx create mode 100644 apps/app/src/components/shell/AppLayout.tsx create mode 100644 apps/app/src/components/shell/MobileDrawer.tsx create mode 100644 apps/app/src/components/shell/SidebarNav.tsx create mode 100644 apps/app/src/components/shell/SignOutButton.tsx create mode 100644 apps/app/src/components/shell/UserBadge.tsx create mode 100644 apps/app/src/components/ui/ButtonLink.tsx create mode 100644 apps/app/src/components/ui/FormField.tsx create mode 100644 apps/app/src/components/ui/Icon.tsx create mode 100644 apps/app/src/components/ui/Notice.tsx create mode 100644 apps/app/src/services/localeSync.ts create mode 100644 apps/app/src/state/authStore.ts diff --git a/apps/app/src/account/useProfileForm.ts b/apps/app/src/account/useProfileForm.ts new file mode 100644 index 00000000..6b31d03d --- /dev/null +++ b/apps/app/src/account/useProfileForm.ts @@ -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> { + values: T + errors: FieldErrors + state: SaveState + field: (key: keyof T) => (e: ChangeEvent) => void + submit: (e: FormEvent) => Promise +} + +/** + * 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>( + initial: T, + schema: ZodType, + toPatch: (values: T) => OwnProfilePatch, +): ProfileForm { + const updateProfile = useAuthStore((s) => s.updateProfile) + const [values, setValues] = useState(initial) + const [errors, setErrors] = useState>({}) + const [state, setState] = useState('idle') + + const field = (key: keyof T) => (e: ChangeEvent) => { + 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 } +} diff --git a/apps/app/src/account/validation.ts b/apps/app/src/account/validation.ts new file mode 100644 index 00000000..4a06b0d7 --- /dev/null +++ b/apps/app/src/account/validation.ts @@ -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 + +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 + +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 + +/** '' → 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) +} diff --git a/apps/app/src/app/App.tsx b/apps/app/src/app/App.tsx index 349d4e24..ca232e07 100644 --- a/apps/app/src/app/App.tsx +++ b/apps/app/src/app/App.tsx @@ -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 (
@@ -22,12 +34,37 @@ function AppShell() { ) } +/** Auth screens and the signed-in /app shell sit beside the local tool. */ +export function AppRoutes() { + return ( + + }> + } /> + } /> + } /> + + } /> + } /> + }> + }> + } /> + } /> + } /> + + + } /> + + ) +} + export default function App() { return ( - - - + + + + + ) } diff --git a/apps/app/src/app/guards/RedirectIfSignedIn.tsx b/apps/app/src/app/guards/RedirectIfSignedIn.tsx new file mode 100644 index 00000000..5aad80c2 --- /dev/null +++ b/apps/app/src/app/guards/RedirectIfSignedIn.tsx @@ -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 + } + return +} diff --git a/apps/app/src/app/guards/RequireAuth.tsx b/apps/app/src/app/guards/RequireAuth.tsx new file mode 100644 index 00000000..d75130b9 --- /dev/null +++ b/apps/app/src/app/guards/RequireAuth.tsx @@ -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 + if (status === 'signed_in') return + const next = encodeURIComponent(location.pathname + location.search) + return +} diff --git a/apps/app/src/app/guards/SessionLoading.tsx b/apps/app/src/app/guards/SessionLoading.tsx new file mode 100644 index 00000000..b4f4609d --- /dev/null +++ b/apps/app/src/app/guards/SessionLoading.tsx @@ -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 ( +
+ +

+ {t('shell.loading_session')} +

+
+ ) +} diff --git a/apps/app/src/app/providers/AuthProvider.tsx b/apps/app/src/app/providers/AuthProvider.tsx new file mode 100644 index 00000000..fba0a32c --- /dev/null +++ b/apps/app/src/app/providers/AuthProvider.tsx @@ -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} +} diff --git a/apps/app/src/app/routes/HomeRoute.tsx b/apps/app/src/app/routes/HomeRoute.tsx index 044e4698..2a1665c2 100644 --- a/apps/app/src/app/routes/HomeRoute.tsx +++ b/apps/app/src/app/routes/HomeRoute.tsx @@ -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 (
- + + +
{noSheet && ( diff --git a/apps/app/src/app/routes/app/AccountRoute.tsx b/apps/app/src/app/routes/app/AccountRoute.tsx new file mode 100644 index 00000000..b3c2c4d3 --- /dev/null +++ b/apps/app/src/app/routes/app/AccountRoute.tsx @@ -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 ( +
+
+

+ {t('account.title')} +

+ +
+ {profile ? ( + <> + + + + + ) : ( + {t('auth.loading')} + )} + +
+ ) +} diff --git a/apps/app/src/app/routes/app/DashboardRoute.tsx b/apps/app/src/app/routes/app/DashboardRoute.tsx new file mode 100644 index 00000000..45e3ca63 --- /dev/null +++ b/apps/app/src/app/routes/app/DashboardRoute.tsx @@ -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 + +/** 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 ( + +

{t('dashboard.profile.title')}

+

+ {complete ? t('dashboard.profile.complete') : t('dashboard.profile.incomplete')} +

+ {!complete && ( +

+ + {t('dashboard.profile.missing_label')} + {' '} + {missing.join(', ')} +

+ )} + + {complete ? t('dashboard.profile.cta_view') : t('dashboard.profile.cta_complete')} + +
+ ) +} + +function ToolCard() { + const t = useT() + return ( + +

{t('dashboard.tool.title')}

+

+ {t('dashboard.tool.description')} +

+
+ + {t('dashboard.tool.cta_new')} + + + {t('dashboard.tool.cta_import')} + +
+
+ ) +} + +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 ( + +

{t('dashboard.account.title')}

+
+
+
{t('dashboard.account.email')}
+
{user?.email}
+
+
+ + {verified ? t('dashboard.account.verified') : t('dashboard.account.unverified')} +
+
+
{t('dashboard.account.language')}
+
{t(`lang.${locale}`)}
+
+
+
{t('dashboard.account.roles')}
+
{roles.length ? : t('dashboard.account.no_roles')}
+
+
+ {created && ( +

+ {t('dashboard.account.member_since').replace('{date}', created)} +

+ )} +
+ ) +} + +export default function DashboardRoute() { + const t = useT() + const profile = useAuthStore((s) => s.profile) + const missing = missingFields(profile, t) + return ( +
+
+

+ {greeting(profile, t)} +

+

+ {t('dashboard.intro')} +

+
+
+ + + +
+
+ ) +} diff --git a/apps/app/src/app/routes/auth/AuthCallbackRoute.tsx b/apps/app/src/app/routes/auth/AuthCallbackRoute.tsx new file mode 100644 index 00000000..733b34b4 --- /dev/null +++ b/apps/app/src/app/routes/auth/AuthCallbackRoute.tsx @@ -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 + } + const providerError = params.get('error_description') ?? params.get('error') + if (status === 'loading' && !urlFailure && !providerError) { + return + } + // Landing here without a session means the exchange failed, whatever the client reported. + return ( + + {t('auth.callback.failed_description')} + {t('auth.callback.retry')} + + ) +} diff --git a/apps/app/src/app/routes/auth/ForgotPasswordRoute.tsx b/apps/app/src/app/routes/auth/ForgotPasswordRoute.tsx new file mode 100644 index 00000000..2467f980 --- /dev/null +++ b/apps/app/src/app/routes/auth/ForgotPasswordRoute.tsx @@ -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(null) + const [failure, setFailure] = useState(null) + const [busy, setBusy] = useState(false) + const [sentTo, setSentTo] = useState(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 = ( +

+ {t('auth.forgot.back_to_login')} +

+ ) + + if (sentTo) { + return ( + + + {t('auth.forgot.sent_description').replace('{email}', sentTo)} + + + ) + } + + return ( + + {!client ? ( + + ) : ( +
+ + setEmail(e.target.value)} + aria-invalid={Boolean(error)} + aria-describedby={fieldDescribedBy('forgot-email', undefined, error ?? undefined)} + required + /> + + {failure && {failure}} + +
+ )} +
+ ) +} diff --git a/apps/app/src/app/routes/auth/LoginRoute.tsx b/apps/app/src/app/routes/auth/LoginRoute.tsx new file mode 100644 index 00000000..bbc0728f --- /dev/null +++ b/apps/app/src/app/routes/auth/LoginRoute.tsx @@ -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({ email: '', password: '' }) + const [errors, setErrors] = useState>({}) + const [failure, setFailure] = useState(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 = ( +

+ {t('auth.login.no_account')}{' '} + {t('auth.login.signup_link')} +

+ ) + + return ( + + {!client ? ( + + ) : ( + <> + +
+ + setValues({ ...values, email: e.target.value })} + aria-invalid={Boolean(errors.email)} + aria-describedby={fieldDescribedBy('login-email', undefined, errors.email)} + required + /> + + + setValues({ ...values, password: e.target.value })} + aria-invalid={Boolean(errors.password)} + aria-describedby={fieldDescribedBy('login-password', undefined, errors.password)} + required + /> + + {failure && {failure}} + +

+ {t('auth.login.forgot')} +

+
+ + )} +
+ ) +} diff --git a/apps/app/src/app/routes/auth/ResetPasswordRoute.tsx b/apps/app/src/app/routes/auth/ResetPasswordRoute.tsx new file mode 100644 index 00000000..ef65bd9d --- /dev/null +++ b/apps/app/src/app/routes/auth/ResetPasswordRoute.tsx @@ -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 ( + + {t('auth.forgot.back_to_login')} +

+ } + > + {t('auth.reset.no_session_description')} + {t('auth.reset.request_again')} +
+ ) +} + +/** + * 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({ password: '', passwordConfirm: '' }) + const [errors, setErrors] = useState>({}) + const [failure, setFailure] = useState(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 ( + + + + ) + } + if (status === 'loading') return + if (status !== 'signed_in') return + + return ( + +
+ + setValues({ ...values, password: e.target.value })} + aria-invalid={Boolean(errors.password)} + aria-describedby={fieldDescribedBy('reset-password', 'hint', errors.password)} + required + /> + + + setValues({ ...values, passwordConfirm: e.target.value })} + aria-invalid={Boolean(errors.passwordConfirm)} + aria-describedby={fieldDescribedBy('reset-password-confirm', undefined, errors.passwordConfirm)} + required + /> + + {failure && {failure}} + +
+
+ ) +} diff --git a/apps/app/src/app/routes/auth/SignupRoute.tsx b/apps/app/src/app/routes/auth/SignupRoute.tsx new file mode 100644 index 00000000..22e726e4 --- /dev/null +++ b/apps/app/src/app/routes/auth/SignupRoute.tsx @@ -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 ( + + {t('auth.signup.login_link')} +

+ } + > + + {t('auth.signup.check_inbox_description').replace('{email}', email)} + +

+ {t('auth.signup.check_inbox_spam')} +

+
+ ) +} + +export default function SignupRoute() { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const describe = useAuthFailureMessage() + const client = getSupabaseClient() + const [values, setValues] = useState(EMPTY) + const [errors, setErrors] = useState>({}) + const [failure, setFailure] = useState(null) + const [busy, setBusy] = useState(false) + const [sentTo, setSentTo] = useState(null) + + function field(key: K) { + return (e: React.ChangeEvent) => + 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 + + const footer = ( +

+ {t('auth.signup.have_account')}{' '} + {t('auth.signup.login_link')} +

+ ) + const passwordHint = t('auth.password_hint').replace( + '{min}', + String(PASSWORD_MIN_LENGTH), + ) + + return ( + + {!client ? ( + + ) : ( + <> + +
+ + + + + + + + + + + + + {failure && {failure}} + +
+ + )} +
+ ) +} diff --git a/apps/app/src/auth/redirects.ts b/apps/app/src/auth/redirects.ts new file mode 100644 index 00000000..f8a2dfae --- /dev/null +++ b/apps/app/src/auth/redirects.ts @@ -0,0 +1,17 @@ +/** 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() +} + +/** + * The `next` query value is only honoured when it is a same-origin path: + * never a scheme, never a protocol-relative URL. + */ +export function safeNextPath(raw: string | null, fallback = APP_HOME_PATH) { + if (!raw || !raw.startsWith('/') || raw.startsWith('//')) return fallback + return raw +} diff --git a/apps/app/src/auth/useAuthFailureMessage.ts b/apps/app/src/auth/useAuthFailureMessage.ts new file mode 100644 index 00000000..c9efc84b --- /dev/null +++ b/apps/app/src/auth/useAuthFailureMessage.ts @@ -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') + } +} diff --git a/apps/app/src/auth/validation.ts b/apps/app/src/auth/validation.ts new file mode 100644 index 00000000..c4f2a433 --- /dev/null +++ b/apps/app/src/auth/validation.ts @@ -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 = Partial> + +/** First issue per field, as an i18n key. */ +export function fieldErrors(error: z.ZodError): FieldErrors { + const out: Record = {} + for (const issue of error.issues) { + const field = String(issue.path[0] ?? '') + if (field && !out[field]) out[field] = issue.message + } + return out as FieldErrors +} diff --git a/apps/app/src/components/account/PersonalInfoForm.tsx b/apps/app/src/components/account/PersonalInfoForm.tsx new file mode 100644 index 00000000..209bbe63 --- /dev/null +++ b/apps/app/src/components/account/PersonalInfoForm.tsx @@ -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 ( + +
+ + + +
+ + + + + + +
+ + + + + +
+ ) +} diff --git a/apps/app/src/components/account/PreferencesForm.tsx b/apps/app/src/components/account/PreferencesForm.tsx new file mode 100644 index 00000000..748501db --- /dev/null +++ b/apps/app/src/components/account/PreferencesForm.tsx @@ -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 ( + +
+ + + + + + + + +
+ ) +} diff --git a/apps/app/src/components/account/ProfessionalInfoForm.tsx b/apps/app/src/components/account/ProfessionalInfoForm.tsx new file mode 100644 index 00000000..adf20d12 --- /dev/null +++ b/apps/app/src/components/account/ProfessionalInfoForm.tsx @@ -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 ( + +
+ + + + + + + + + + + +
+ ) +} diff --git a/apps/app/src/components/account/RoleBadges.tsx b/apps/app/src/components/account/RoleBadges.tsx new file mode 100644 index 00000000..21fc00ee --- /dev/null +++ b/apps/app/src/components/account/RoleBadges.tsx @@ -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 ( +
    + {roles.map((role) => ( +
  • + {t(`shell.role.${role}`)} +
  • + ))} +
+ ) +} diff --git a/apps/app/src/components/account/SaveRow.tsx b/apps/app/src/components/account/SaveRow.tsx new file mode 100644 index 00000000..fc1ef709 --- /dev/null +++ b/apps/app/src/components/account/SaveRow.tsx @@ -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 ( +
+ + {state === 'saved' && {t('account.saved')}} + {state === 'failed' && ( + {t('account.error.save_failed')} + )} +
+ ) +} diff --git a/apps/app/src/components/account/SectionCard.tsx b/apps/app/src/components/account/SectionCard.tsx new file mode 100644 index 00000000..501afd5c --- /dev/null +++ b/apps/app/src/components/account/SectionCard.tsx @@ -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 ( + +
+
+

+ {title} +

+ {description && ( +

{description}

+ )} +
+
{children}
+
+
+ ) +} diff --git a/apps/app/src/components/account/SecurityPanel.tsx b/apps/app/src/components/account/SecurityPanel.tsx new file mode 100644 index 00000000..7d9244bb --- /dev/null +++ b/apps/app/src/components/account/SecurityPanel.tsx @@ -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({ password: '', passwordConfirm: '' }) + const [errors, setErrors] = useState>({}) + const [failure, setFailure] = useState(null) + const [state, setState] = useState('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 ( +
+ + setValues({ ...values, password: e.target.value })} + aria-invalid={Boolean(errors.password)} + aria-describedby={fieldDescribedBy('new-password', 'hint', errors.password)} + /> + + + setValues({ ...values, passwordConfirm: e.target.value })} + aria-invalid={Boolean(errors.passwordConfirm)} + aria-describedby={fieldDescribedBy('new-password-confirm', undefined, errors.passwordConfirm)} + /> + +
+ + {state === 'saved' && ( + {t('account.security.password_changed')} + )} + {failure && {failure}} +
+
+ ) +} + +export default function SecurityPanel() { + const t = useT() + const email = useAuthStore((s) => s.user?.email) + return ( + +
+
+

+ {t('account.security.email_label')} +

+

{email}

+
+ +
+

+ {t('account.security.mfa_title')} +

+

+ {t('account.security.mfa_note')} +

+
+
+

+ {t('account.security.sign_out_everywhere_note')} +

+ +
+
+
+ ) +} diff --git a/apps/app/src/components/auth/AuthLayout.tsx b/apps/app/src/components/auth/AuthLayout.tsx new file mode 100644 index 00000000..2d7342c0 --- /dev/null +++ b/apps/app/src/components/auth/AuthLayout.tsx @@ -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 ( +
+ + +
+
+ + + + +
+
+
+ +
+

+ {title} +

+ {subtitle && ( +

+ {subtitle} +

+ )} +
+ {children} +
+ {footer && ( +
+ {footer} +
+ )} +
+
+
+
+ ) +} diff --git a/apps/app/src/components/auth/AuthLink.tsx b/apps/app/src/components/auth/AuthLink.tsx new file mode 100644 index 00000000..86a39467 --- /dev/null +++ b/apps/app/src/components/auth/AuthLink.tsx @@ -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 ( + + ) +} diff --git a/apps/app/src/components/auth/OAuthButtons.tsx b/apps/app/src/components/auth/OAuthButtons.tsx new file mode 100644 index 00000000..573b3022 --- /dev/null +++ b/apps/app/src/components/auth/OAuthButtons.tsx @@ -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 = { + 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(null) + const [pending, setPending] = useState(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 ( +
+
+ {authProviders.map((provider) => ( + + ))} +
+ {error && {error}} +
+ + {t('auth.or')} + +
+
+ ) +} diff --git a/apps/app/src/components/auth/PasswordField.tsx b/apps/app/src/components/auth/PasswordField.tsx new file mode 100644 index 00000000..fb8ab2c0 --- /dev/null +++ b/apps/app/src/components/auth/PasswordField.tsx @@ -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, '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 ( +
+ + +
+ ) +} diff --git a/apps/app/src/components/auth/UnavailableNotice.tsx b/apps/app/src/components/auth/UnavailableNotice.tsx new file mode 100644 index 00000000..a2161715 --- /dev/null +++ b/apps/app/src/components/auth/UnavailableNotice.tsx @@ -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 ( +
+ +

{t('auth.unavailable_title')}

+

{t('auth.unavailable_description')}

+
+ +
+ ) +} diff --git a/apps/app/src/components/brand/HomeSpaceLink.tsx b/apps/app/src/components/brand/HomeSpaceLink.tsx new file mode 100644 index 00000000..c61c3a2f --- /dev/null +++ b/apps/app/src/components/brand/HomeSpaceLink.tsx @@ -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 ( + + {signedIn ? t('home.space.open') : t('home.space.signin')} + + ) +} diff --git a/apps/app/src/components/shell/AppLayout.tsx b/apps/app/src/components/shell/AppLayout.tsx new file mode 100644 index 00000000..521b624e --- /dev/null +++ b/apps/app/src/components/shell/AppLayout.tsx @@ -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 ( +
+ + +
+
+ + + + +

+ {t(pageTitleKey(location.pathname))} +

+
+ +
+
+
+
+ +
+
+
+ + setDrawerOpen(false)} /> +
+ ) +} diff --git a/apps/app/src/components/shell/MobileDrawer.tsx b/apps/app/src/components/shell/MobileDrawer.tsx new file mode 100644 index 00000000..d9ef839a --- /dev/null +++ b/apps/app/src/components/shell/MobileDrawer.tsx @@ -0,0 +1,74 @@ +import { useEffect } from 'react' +import { Link } from 'react-router-dom' +import { AnimatePresence, motion } 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() + useEffect(() => { + if (!open) return + const onKey = (e: KeyboardEvent) => e.key === 'Escape' && onClose() + window.addEventListener('keydown', onKey) + return () => window.removeEventListener('keydown', onKey) + }, [open, onClose]) + + return ( + + {open && ( +
+ + +
+ + + + +
+
+ +
+
+ + +
+
+
+ )} +
+ ) +} diff --git a/apps/app/src/components/shell/SidebarNav.tsx b/apps/app/src/components/shell/SidebarNav.tsx new file mode 100644 index 00000000..98f9830e --- /dev/null +++ b/apps/app/src/components/shell/SidebarNav.tsx @@ -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 ( + + ) +} diff --git a/apps/app/src/components/shell/SignOutButton.tsx b/apps/app/src/components/shell/SignOutButton.tsx new file mode 100644 index 00000000..d302cab2 --- /dev/null +++ b/apps/app/src/components/shell/SignOutButton.tsx @@ -0,0 +1,36 @@ +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() + } finally { + // The guard would redirect anyway; going home keeps the local tool one step away. + navigate('/', { replace: true }) + } + } + + return ( + + ) +} diff --git a/apps/app/src/components/shell/UserBadge.tsx b/apps/app/src/components/shell/UserBadge.tsx new file mode 100644 index 00000000..f4ebba77 --- /dev/null +++ b/apps/app/src/components/shell/UserBadge.tsx @@ -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 ( +
+ + + + {name} + + {user?.email && profile?.display_name && ( + + {user.email} + + )} + +
+ ) +} diff --git a/apps/app/src/components/ui/Button.tsx b/apps/app/src/components/ui/Button.tsx index 50d310e3..a5c1a3da 100644 --- a/apps/app/src/components/ui/Button.tsx +++ b/apps/app/src/components/ui/Button.tsx @@ -23,6 +23,20 @@ const SIZES: Record, 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 = 'primary', + size: NonNullable = '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 (