diff --git a/.claude/memory/decisions.md b/.claude/memory/decisions.md index ed1f200d..da5969c1 100644 --- a/.claude/memory/decisions.md +++ b/.claude/memory/decisions.md @@ -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 ` + + )} + + ) +} 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..a2e8d586 --- /dev/null +++ b/apps/app/src/auth/redirects.ts @@ -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 +} 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..648598cf --- /dev/null +++ b/apps/app/src/components/shell/MobileDrawer.tsx @@ -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 ( + + {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..a33c6860 --- /dev/null +++ b/apps/app/src/components/shell/SignOutButton.tsx @@ -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 ( + + ) +} 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 (