From 4744e289862656c9f9b9813c1c8447b970895a4a Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 2 Nov 2026 16:49:37 +0100 Subject: [PATCH] feat(app): admin and catalogue entries, step-up guard, MFA in Mon compte (V1-2.5 E, F) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Nav hint from own grants and roles (never a control); RequireCatalog, RequireAdmin (no admin read before aal2), Accès non autorisé page, placeholder routes; TOTP factor list, enrolment with QR and one-time secret, removal, inline step-up for aal2 actions, step-up in password reset; auth kind aal2_required. App 601, e2e:ui 227. --- .../2026-11-02-v1-2-5-label-proposals.md | 27 +++ apps/app/src/app/App.tsx | 23 ++ apps/app/src/app/guards/RequireAdmin.tsx | 108 ++++++++++ apps/app/src/app/guards/RequireCatalog.tsx | 12 ++ .../app/routes/app/admin/AdminAccessRoute.tsx | 6 + .../app/routes/app/admin/AdminHomeRoute.tsx | 6 + .../app/admin/AdminSheetCreateRoute.tsx | 6 + .../app/routes/app/admin/AdminSheetRoute.tsx | 6 + .../app/routes/app/admin/AdminSheetsRoute.tsx | 6 + .../routes/app/admin/AdminSpeciesRoute.tsx | 6 + .../app/routes/app/anatomy/CatalogRoute.tsx | 6 + .../app/routes/auth/ResetPasswordRoute.tsx | 50 ++++- apps/app/src/auth/navigationHint.ts | 39 ++++ apps/app/src/auth/stepUp.ts | 24 +++ apps/app/src/auth/useMfaFailureMessage.ts | 8 + apps/app/src/auth/useStepUp.ts | 59 ++++++ apps/app/src/auth/validation.ts | 19 ++ apps/app/src/components/account/EnrolTotp.tsx | 159 ++++++++++++++ .../app/src/components/account/MfaFactors.tsx | 197 ++++++++++++++++++ .../src/components/account/SecurityPanel.tsx | 47 +++-- apps/app/src/components/auth/InlineStepUp.tsx | 15 ++ apps/app/src/components/auth/TotpCodeForm.tsx | 117 +++++++++++ .../app/src/components/shell/AccessDenied.tsx | 26 +++ .../src/components/shell/PlaceholderPage.tsx | 16 ++ apps/app/src/components/shell/SidebarNav.tsx | 65 ++++-- apps/app/src/components/ui/Icon.tsx | 4 + apps/app/src/i18n/en.ts | 60 +++++- apps/app/src/i18n/fr.ts | 60 +++++- apps/app/src/state/authStore.ts | 13 ++ apps/app/tests/helpers/fakeSupabase.ts | 44 ++++ .../unit/components.SecurityPanel.test.tsx | 191 +++++++++++++++++ .../tests/unit/guards.RequireAdmin.test.tsx | 178 ++++++++++++++++ .../tests/unit/routes.AccountRoute.test.tsx | 4 +- .../unit/routes.ResetPasswordRoute.test.tsx | 108 ++++++++++ apps/app/tests/unit/shell.navigation.test.tsx | 135 ++++++++++++ apps/app/tests/unit/state.authStore.test.ts | 19 ++ packages/supabase/src/auth.ts | 3 + packages/supabase/tests/auth.test.ts | 1 + 38 files changed, 1818 insertions(+), 55 deletions(-) create mode 100644 .claude/audits/2026-11-02-v1-2-5-label-proposals.md create mode 100644 apps/app/src/app/guards/RequireAdmin.tsx create mode 100644 apps/app/src/app/guards/RequireCatalog.tsx create mode 100644 apps/app/src/app/routes/app/admin/AdminAccessRoute.tsx create mode 100644 apps/app/src/app/routes/app/admin/AdminHomeRoute.tsx create mode 100644 apps/app/src/app/routes/app/admin/AdminSheetCreateRoute.tsx create mode 100644 apps/app/src/app/routes/app/admin/AdminSheetRoute.tsx create mode 100644 apps/app/src/app/routes/app/admin/AdminSheetsRoute.tsx create mode 100644 apps/app/src/app/routes/app/admin/AdminSpeciesRoute.tsx create mode 100644 apps/app/src/app/routes/app/anatomy/CatalogRoute.tsx create mode 100644 apps/app/src/auth/navigationHint.ts create mode 100644 apps/app/src/auth/stepUp.ts create mode 100644 apps/app/src/auth/useMfaFailureMessage.ts create mode 100644 apps/app/src/auth/useStepUp.ts create mode 100644 apps/app/src/components/account/EnrolTotp.tsx create mode 100644 apps/app/src/components/account/MfaFactors.tsx create mode 100644 apps/app/src/components/auth/InlineStepUp.tsx create mode 100644 apps/app/src/components/auth/TotpCodeForm.tsx create mode 100644 apps/app/src/components/shell/AccessDenied.tsx create mode 100644 apps/app/src/components/shell/PlaceholderPage.tsx create mode 100644 apps/app/tests/unit/components.SecurityPanel.test.tsx create mode 100644 apps/app/tests/unit/guards.RequireAdmin.test.tsx create mode 100644 apps/app/tests/unit/routes.ResetPasswordRoute.test.tsx create mode 100644 apps/app/tests/unit/shell.navigation.test.tsx diff --git a/.claude/audits/2026-11-02-v1-2-5-label-proposals.md b/.claude/audits/2026-11-02-v1-2-5-label-proposals.md new file mode 100644 index 00000000..08f58c98 --- /dev/null +++ b/.claude/audits/2026-11-02-v1-2-5-label-proposals.md @@ -0,0 +1,27 @@ +# V1-2.5 new FR/EN labels: proposals for the checkpoint + +Ratified wordings used verbatim (V1-2 contract §3, §17.9, REVUE.md): Fiches anatomiques / Anatomical sheets; +Administration; Accès non autorisé / Access denied, its explanation and « Retour au tableau de bord » / « Back to +dashboard » (L32); Fiches officielles / Official sheets; Espèces / Species; Accès et habilitations / Access and +permissions (L14). Everything below is a proposal, not ratified. + +## Slices E and F (shell, step-up, MFA) + +| Key | FR | EN | +|---|---|---| +| admin.sheets.new | Nouvelle fiche (§11.1) | New sheet | +| admin.step_up.title | Double authentification requise | Two-factor authentication required | +| admin.step_up.body | L'administration demande une session renforcée : saisissez le code à 6 chiffres de votre application d'authentification. | Administration needs a strengthened session: enter the 6-digit code from your authenticator app. | +| admin.step_up.no_factor | L'administration demande la double authentification. Ajoutez d'abord un facteur dans Mon compte, Sécurité. | Administration requires two-factor authentication. First add a factor in My account, Security. | +| admin.step_up.to_security | Ouvrir Mon compte, Sécurité | Open My account, Security | +| auth.failure.aal2_required | Votre compte est protégé par la double authentification : saisissez d'abord un code de votre application d'authentification. | Your account is protected by two-factor authentication: enter a code from your authenticator app first. | +| mfa.description | Un code à 6 chiffres d'une application d'authentification, en plus du mot de passe. Exigée pour l'administration. | A 6-digit code from an authenticator app, on top of your password. Required for administration. | +| mfa.factor.* | Chargement des facteurs… · Aucun facteur pour le moment. · Facteurs d'authentification · Facteur sans nom · Vérifié · Non vérifié · Ajouté le {date} · Supprimer · Facteur supprimé. | Loading factors… · No factor yet. · Authentication factors · Unnamed factor · Verified · Not verified · Added on {date} · Remove · Factor removed. | +| mfa.remove.* | Supprimer ce facteur ? · « {name} » ne servira plus à renforcer votre session. Supprimer un facteur vérifié demande une session renforcée. · Supprimer | Remove this factor? · “{name}” will no longer strengthen your session. Removing a verified factor needs a strengthened session. · Remove | +| mfa.enrol.* | Ajouter un facteur · Nom du facteur · Pour le reconnaître dans la liste, par exemple « Téléphone personnel ». · Continuer · Création… · Scannez ce QR code avec votre application d'authentification, puis saisissez le code qu'elle affiche. · QR code à scanner avec votre application d'authentification · Clé de configuration manuelle · Si vous ne pouvez pas scanner le QR code. Elle n'est affichée qu'une fois : ne la conservez pas ailleurs. · Facteur ajouté et vérifié. | Add a factor · Factor name · To recognise it in the list, for example “Personal phone”. · Continue · Creating… · Scan this QR code with your authenticator app, then enter the code it shows. · QR code to scan with your authenticator app · Setup key for manual entry · If you cannot scan the QR code. It is shown only once: do not keep it anywhere else. · Factor added and verified. | +| mfa.code.* | Code de vérification · Les 6 chiffres affichés par votre application d'authentification. · Vérifier · Vérification… | Verification code · The 6 digits shown by your authenticator app. · Verify · Verifying… | +| mfa.step_up.* | Facteur · Cette action demande une session renforcée : saisissez un code de votre application d'authentification. | Factor · This action needs a strengthened session: enter a code from your authenticator app. | +| mfa.error.* | Le code comporte 6 chiffres. · Donnez un nom au facteur. · Nom trop long ({max} caractères maximum). | The code has 6 digits. · Give the factor a name. · Name too long ({max} characters maximum). | +| mfa.failure.* | aal2_required: Cette action demande une session renforcée par la double authentification. · invalid_code: Code incorrect ou expiré. Saisissez le code affiché maintenant. · factor_not_found: Ce facteur n'existe plus. Rechargez la page. · challenge_expired: La vérification a expiré. Saisissez un nouveau code. · too_many_factors: Nombre maximal de facteurs atteint. Supprimez-en un avant d'en ajouter un autre. · name_taken: Un facteur porte déjà ce nom. Choisissez-en un autre. · unavailable: La double authentification est momentanément indisponible. Réessayez plus tard. · rate_limited, session_expired, network: as auth.failure.* | same keys, EN as in en.ts | + +Choices to confirm: factor name limit 64 characters (no GoTrue limit documented); no copy button for the setup key. diff --git a/apps/app/src/app/App.tsx b/apps/app/src/app/App.tsx index b952bc8d..8a6df79a 100644 --- a/apps/app/src/app/App.tsx +++ b/apps/app/src/app/App.tsx @@ -25,6 +25,15 @@ import AnimalsListRoute from './routes/app/animals/AnimalsListRoute' import AnimalCreateRoute from './routes/app/animals/AnimalCreateRoute' import AnimalDetailRoute from './routes/app/animals/AnimalDetailRoute' import AnimalEditRoute from './routes/app/animals/AnimalEditRoute' +import RequireCatalog from './guards/RequireCatalog' +import RequireAdmin from './guards/RequireAdmin' +import CatalogRoute from './routes/app/anatomy/CatalogRoute' +import AdminHomeRoute from './routes/app/admin/AdminHomeRoute' +import AdminSheetsRoute from './routes/app/admin/AdminSheetsRoute' +import AdminSheetCreateRoute from './routes/app/admin/AdminSheetCreateRoute' +import AdminSheetRoute from './routes/app/admin/AdminSheetRoute' +import AdminSpeciesRoute from './routes/app/admin/AdminSpeciesRoute' +import AdminAccessRoute from './routes/app/admin/AdminAccessRoute' import { useUnsavedGuard } from './useUnsavedGuard' /** The local tool: unchanged routes, no account needed, shared footer. */ @@ -74,6 +83,20 @@ export function AppRoutes() { } /> + {/* V1-2 (§11.1): the server decides every read; these gates never use the nav hint. */} + }> + } /> + + }> + } /> + + } /> + } /> + } /> + + } /> + } /> + } /> diff --git a/apps/app/src/app/guards/RequireAdmin.tsx b/apps/app/src/app/guards/RequireAdmin.tsx new file mode 100644 index 00000000..59fad57b --- /dev/null +++ b/apps/app/src/app/guards/RequireAdmin.tsx @@ -0,0 +1,108 @@ +import { useEffect, useState, type ReactNode } from 'react' +import { Link, Outlet } from 'react-router-dom' +import type { TotpFactor } from '@faunosteo/supabase' +import TotpCodeForm from '@/components/auth/TotpCodeForm' +import Button from '@/components/ui/Button' +import Card from '@/components/ui/Card' +import Notice from '@/components/ui/Notice' +import { stepUpFactors } from '@/auth/stepUp' +import { useMfaFailureMessage } from '@/auth/useMfaFailureMessage' +import { usePageHeading } from '@/app/usePageHeading' +import { getSupabaseClient } from '@/lib/supabase' +import { useAuthStore } from '@/state/authStore' +import { useT } from '@/i18n/useT' + +type Gate = + | { status: 'checking' } + | { status: 'open' } + | { status: 'challenge'; factors: TotpFactor[] } + | { status: 'no_factor' } + | { status: 'failed'; error: unknown } + +function StepUpCard({ children }: { children: ReactNode }) { + const t = useT() + const heading = usePageHeading() + return ( + +

+ {t('admin.step_up.title')} +

+ {children} +
+ ) +} + +/** + * Wraps /app/admin/* (contract §5.6): the pages render only on an `aal2` + * session, so no admin data is requested before. At `aal1` the account + * steps up with one of its verified factors; without one, it is sent to + * Mon compte, Sécurité to add one. The gate is for the screens: every admin + * RPC checks `aal2` and the capability on the server. + */ +export default function RequireAdmin() { + const t = useT() + const describe = useMfaFailureMessage() + const userId = useAuthStore((s) => s.user?.id) + const [gate, setGate] = useState({ status: 'checking' }) + // Bumped after a step-up and on retry: the level is read again from the new session. + const [attempt, setAttempt] = useState(0) + const check = () => setAttempt((n) => n + 1) + + useEffect(() => { + let live = true + const client = getSupabaseClient() + setGate({ status: 'checking' }) + if (!client) return + stepUpFactors(client) + .then((factors) => { + if (!live) return + if (factors === null) setGate({ status: 'open' }) + else if (factors.length === 0) setGate({ status: 'no_factor' }) + else setGate({ status: 'challenge', factors }) + }) + .catch((error: unknown) => { + if (live) setGate({ status: 'failed', error }) + }) + return () => { + live = false + } + }, [userId, attempt]) + + if (gate.status === 'open') return + if (gate.status === 'checking') { + return ( +

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

+ ) + } + if (gate.status === 'challenge') { + return ( + +

{t('admin.step_up.body')}

+ +
+ ) + } + if (gate.status === 'no_factor') { + return ( + + {t('admin.step_up.no_factor')} + + {t('admin.step_up.to_security')} + + + ) + } + return ( +
+ {describe(gate.error)} + +
+ ) +} diff --git a/apps/app/src/app/guards/RequireCatalog.tsx b/apps/app/src/app/guards/RequireCatalog.tsx new file mode 100644 index 00000000..63f0e317 --- /dev/null +++ b/apps/app/src/app/guards/RequireCatalog.tsx @@ -0,0 +1,12 @@ +import { Outlet } from 'react-router-dom' + +/** + * Wraps /app/anatomy/*. It decides nothing: the navigation hint (own grant + * rows) never gates a page. The pages request the catalogue and show + * « Accès non autorisé » (AccessDenied) when the server refuses + * (`rights.catalog`, `not_found`), the same whether the sheet exists or not + * (contract §5.3). Signed-out visitors never reach it (RequireAuth). + */ +export default function RequireCatalog() { + return +} diff --git a/apps/app/src/app/routes/app/admin/AdminAccessRoute.tsx b/apps/app/src/app/routes/app/admin/AdminAccessRoute.tsx new file mode 100644 index 00000000..e9dd96fd --- /dev/null +++ b/apps/app/src/app/routes/app/admin/AdminAccessRoute.tsx @@ -0,0 +1,6 @@ +import PlaceholderPage from '@/components/shell/PlaceholderPage' + +/** V1-2.5 placeholder (slice E): the rights screen (owner), built by slice G. */ +export default function AdminAccessRoute() { + return +} diff --git a/apps/app/src/app/routes/app/admin/AdminHomeRoute.tsx b/apps/app/src/app/routes/app/admin/AdminHomeRoute.tsx new file mode 100644 index 00000000..7f2c4c63 --- /dev/null +++ b/apps/app/src/app/routes/app/admin/AdminHomeRoute.tsx @@ -0,0 +1,6 @@ +import PlaceholderPage from '@/components/shell/PlaceholderPage' + +/** V1-2.5 placeholder (slice E): the administration page (board 10), built by slice G. */ +export default function AdminHomeRoute() { + return +} diff --git a/apps/app/src/app/routes/app/admin/AdminSheetCreateRoute.tsx b/apps/app/src/app/routes/app/admin/AdminSheetCreateRoute.tsx new file mode 100644 index 00000000..8786c688 --- /dev/null +++ b/apps/app/src/app/routes/app/admin/AdminSheetCreateRoute.tsx @@ -0,0 +1,6 @@ +import PlaceholderPage from '@/components/shell/PlaceholderPage' + +/** V1-2.5 placeholder (slice E): the sheet creation form, built by slice H. */ +export default function AdminSheetCreateRoute() { + return +} diff --git a/apps/app/src/app/routes/app/admin/AdminSheetRoute.tsx b/apps/app/src/app/routes/app/admin/AdminSheetRoute.tsx new file mode 100644 index 00000000..2c3673ed --- /dev/null +++ b/apps/app/src/app/routes/app/admin/AdminSheetRoute.tsx @@ -0,0 +1,6 @@ +import PlaceholderPage from '@/components/shell/PlaceholderPage' + +/** V1-2.5 placeholder (slice E): the sheet overview (versions, rounds, working copy), built by slice H. */ +export default function AdminSheetRoute() { + return +} diff --git a/apps/app/src/app/routes/app/admin/AdminSheetsRoute.tsx b/apps/app/src/app/routes/app/admin/AdminSheetsRoute.tsx new file mode 100644 index 00000000..b0cb6ff8 --- /dev/null +++ b/apps/app/src/app/routes/app/admin/AdminSheetsRoute.tsx @@ -0,0 +1,6 @@ +import PlaceholderPage from '@/components/shell/PlaceholderPage' + +/** V1-2.5 placeholder (slice E): the official sheets list with its filters, built by slice H. */ +export default function AdminSheetsRoute() { + return +} diff --git a/apps/app/src/app/routes/app/admin/AdminSpeciesRoute.tsx b/apps/app/src/app/routes/app/admin/AdminSpeciesRoute.tsx new file mode 100644 index 00000000..a00b6763 --- /dev/null +++ b/apps/app/src/app/routes/app/admin/AdminSpeciesRoute.tsx @@ -0,0 +1,6 @@ +import PlaceholderPage from '@/components/shell/PlaceholderPage' + +/** V1-2.5 placeholder (slice E): the species screen, built by slice G. */ +export default function AdminSpeciesRoute() { + return +} diff --git a/apps/app/src/app/routes/app/anatomy/CatalogRoute.tsx b/apps/app/src/app/routes/app/anatomy/CatalogRoute.tsx new file mode 100644 index 00000000..f4374890 --- /dev/null +++ b/apps/app/src/app/routes/app/anatomy/CatalogRoute.tsx @@ -0,0 +1,6 @@ +import PlaceholderPage from '@/components/shell/PlaceholderPage' + +/** V1-2.5 placeholder (slice E): the catalogue list (board 01), built by slice I. */ +export default function CatalogRoute() { + return +} diff --git a/apps/app/src/app/routes/auth/ResetPasswordRoute.tsx b/apps/app/src/app/routes/auth/ResetPasswordRoute.tsx index ef65bd9d..fef1e480 100644 --- a/apps/app/src/app/routes/auth/ResetPasswordRoute.tsx +++ b/apps/app/src/app/routes/auth/ResetPasswordRoute.tsx @@ -1,8 +1,9 @@ import { useState, type FormEvent } from 'react' import { useNavigate } from 'react-router-dom' -import { updatePassword } from '@faunosteo/supabase' +import { assuranceLevel, updatePassword } from '@faunosteo/supabase' import AuthLayout from '@/components/auth/AuthLayout' import AuthLink from '@/components/auth/AuthLink' +import InlineStepUp from '@/components/auth/InlineStepUp' import PasswordField from '@/components/auth/PasswordField' import UnavailableNotice from '@/components/auth/UnavailableNotice' import Button from '@/components/ui/Button' @@ -17,6 +18,7 @@ import { type FieldErrors, } from '@/auth/validation' import { useAuthFailureMessage } from '@/auth/useAuthFailureMessage' +import { isAal2Required, useStepUp } from '@/auth/useStepUp' import { getSupabaseClient } from '@/lib/supabase' import { useAuthStore } from '@/state/authStore' import { useT } from '@/i18n/useT' @@ -43,6 +45,9 @@ function NoSession() { /** * 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. + * An account with a verified factor needs an `aal2` session for it, the + * recovery session included (IDENTITY.md §4.1): the step-up comes before the + * new password is sent, and again if GoTrue still refuses. */ export default function ResetPasswordRoute() { const t = useT() @@ -55,26 +60,45 @@ export default function ResetPasswordRoute() { const [errors, setErrors] = useState>({}) const [failure, setFailure] = useState(null) const [busy, setBusy] = useState(false) + const stepUp = useStepUp() + + async function save(password: string) { + if (!client) return + setFailure(null) + setBusy(true) + try { + await updatePassword(client, password) + clearRecovery() + navigate(APP_HOME_PATH, { replace: true }) + } catch (err) { + const opened = isAal2Required(err) && (await stepUp.open(() => void save(password))) + if (!opened) setFailure(describe(err)) + setBusy(false) + } + } + + /** The account holds a verified factor and this session is below aal2. */ + async function needsStepUp(): Promise { + if (!client) return false + const level = await assuranceLevel(client).catch(() => null) + return level?.current === 'aal1' && level.next === 'aal2' + } 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) + const password = parsed.data.password setBusy(true) - try { - await updatePassword(client, parsed.data.password) - clearRecovery() - navigate(APP_HOME_PATH, { replace: true }) - } catch (err) { - setFailure(describe(err)) + if ((await needsStepUp()) && (await stepUp.open(() => void save(password)))) { setBusy(false) + return } + await save(password) } if (!client) { @@ -87,6 +111,14 @@ export default function ResetPasswordRoute() { if (status === 'loading') return if (status !== 'signed_in') return + if (stepUp.challenge) { + return ( + + + + ) + } + return (
diff --git a/apps/app/src/auth/navigationHint.ts b/apps/app/src/auth/navigationHint.ts new file mode 100644 index 00000000..43f91854 --- /dev/null +++ b/apps/app/src/auth/navigationHint.ts @@ -0,0 +1,39 @@ +import type { OwnCatalogGrant, PlatformRole } from '@faunosteo/supabase' + +export interface NavigationHint { + /** « Fiches anatomiques »: an active `catalog_reader` grant or any active capability (§5.3). */ + catalog: boolean + /** « Administration »: an active capability or the owner role (§11.1, BDR-094). */ + admin: boolean +} + +const CAPABILITIES: ReadonlySet = new Set([ + 'sheet_editor', + 'sheet_reviewer', + 'sheet_publisher', +]) + +/** Not revoked and not past its expiry, on the device clock. */ +function isActive(grant: OwnCatalogGrant, now: number): boolean { + if (grant.revoked_at) return false + return grant.expires_at === null || Date.parse(grant.expires_at) > now +} + +/** + * Which navigation entries to show, from the caller's own grant rows and + * platform roles. A display hint only: a hidden entry protects nothing, and + * a shown one grants nothing. Every page acts on the server's answer (RLS, + * the capability and `aal2` checks), never on this. + */ +export function navigationHint( + grants: readonly OwnCatalogGrant[], + roles: readonly PlatformRole[], + now: number = Date.now(), +): NavigationHint { + const active = grants.filter((grant) => isActive(grant, now)) + const capability = active.some((grant) => CAPABILITIES.has(grant.kind)) + return { + catalog: capability || active.some((grant) => grant.kind === 'catalog_reader'), + admin: capability || roles.includes('owner'), + } +} diff --git a/apps/app/src/auth/stepUp.ts b/apps/app/src/auth/stepUp.ts new file mode 100644 index 00000000..f62614ea --- /dev/null +++ b/apps/app/src/auth/stepUp.ts @@ -0,0 +1,24 @@ +import { + assuranceLevel, + listTotpFactors, + type FaunosteoClient, + type TotpFactor, +} from '@faunosteo/supabase' + +/** The account's verified TOTP factors: the ones a step-up can use. */ +export async function verifiedFactors(client: FaunosteoClient): Promise { + const factors = await listTotpFactors(client) + return factors.filter((factor) => factor.status === 'verified') +} + +/** + * What raising the session to `aal2` needs (contract §5.6): null when the + * session is `aal2` already, else the account's verified factors, empty when + * it has none (a factor must be added first). The level read is a hint for + * the screens; GoTrue and the RPCs check the token themselves. + */ +export async function stepUpFactors(client: FaunosteoClient): Promise { + const level = await assuranceLevel(client) + if (level.current === 'aal2') return null + return verifiedFactors(client) +} diff --git a/apps/app/src/auth/useMfaFailureMessage.ts b/apps/app/src/auth/useMfaFailureMessage.ts new file mode 100644 index 00000000..3997a20e --- /dev/null +++ b/apps/app/src/auth/useMfaFailureMessage.ts @@ -0,0 +1,8 @@ +import { classifyMfaError } from '@faunosteo/supabase' +import { useT } from '@/i18n/useT' + +/** One sentence per MFA failure kind (`mfa.failure.`); GoTrue's own message never shows. */ +export function useMfaFailureMessage(): (error: unknown) => string { + const t = useT() + return (error) => t(`mfa.failure.${classifyMfaError(error)}`) +} diff --git a/apps/app/src/auth/useStepUp.ts b/apps/app/src/auth/useStepUp.ts new file mode 100644 index 00000000..8e96ff52 --- /dev/null +++ b/apps/app/src/auth/useStepUp.ts @@ -0,0 +1,59 @@ +import { useState } from 'react' +import { AuthFailure, MfaFailure, type TotpFactor } from '@faunosteo/supabase' +import { getSupabaseClient } from '@/lib/supabase' +import { verifiedFactors } from './stepUp' + +interface PendingStepUp { + factors: TotpFactor[] + resume: () => void +} + +/** The open challenge: its factors, and what verifying or cancelling it does. */ +export interface StepUpChallenge { + factors: TotpFactor[] + onVerified: () => void + onCancel: () => void +} + +/** GoTrue refused because the session is below `aal2` (IDENTITY.md §4.1). */ +export function isAal2Required(error: unknown): boolean { + return ( + (error instanceof MfaFailure || error instanceof AuthFailure) && + error.kind === 'aal2_required' + ) +} + +/** + * An action GoTrue may refuse below `aal2` (a password change, a second + * factor, the removal of a verified one): `open` shows the challenge for one + * of the account's verified factors and keeps the action to resume once the + * session is `aal2`; it answers false when the account has no verified factor + * (nothing to step up with) or the factors cannot be read. Never a bypass: + * the retried action goes to GoTrue again. + */ +export function useStepUp() { + const [pending, setPending] = useState(null) + + async function open(resume: () => void): Promise { + const client = getSupabaseClient() + if (!client) return false + try { + const factors = await verifiedFactors(client) + if (factors.length === 0) return false + setPending({ factors, resume }) + return true + } catch { + return false + } + } + + const challenge: StepUpChallenge | null = pending && { + factors: pending.factors, + onVerified: () => { + setPending(null) + pending.resume() + }, + onCancel: () => setPending(null), + } + return { open, challenge } +} diff --git a/apps/app/src/auth/validation.ts b/apps/app/src/auth/validation.ts index c4f2a433..a9556393 100644 --- a/apps/app/src/auth/validation.ts +++ b/apps/app/src/auth/validation.ts @@ -50,6 +50,25 @@ export const newPasswordSchema = z path: ['passwordConfirm'], }) +/** A TOTP code as authenticator apps show it: six digits, spaces tolerated. */ +export const totpCodeSchema = z.object({ + code: z + .string() + .transform((value) => value.replace(/\s/g, '')) + .pipe(z.string().regex(/^\d{6}$/, 'mfa.error.code_format')), +}) + +/** The name a factor is listed under (GoTrue's friendly_name, unique per account). */ +export const FACTOR_NAME_MAX_LENGTH = 64 + +export const factorNameSchema = z.object({ + name: z + .string() + .trim() + .min(1, 'mfa.error.name_required') + .max(FACTOR_NAME_MAX_LENGTH, 'mfa.error.name_too_long'), +}) + export type FieldErrors = Partial> /** First issue per field, as an i18n key. */ diff --git a/apps/app/src/components/account/EnrolTotp.tsx b/apps/app/src/components/account/EnrolTotp.tsx new file mode 100644 index 00000000..db82e6ac --- /dev/null +++ b/apps/app/src/components/account/EnrolTotp.tsx @@ -0,0 +1,159 @@ +import { useEffect, useRef, useState, type FormEvent } from 'react' +import { enrollTotp, unenrollFactor, type TotpEnrolment } from '@faunosteo/supabase' +import InlineStepUp from '@/components/auth/InlineStepUp' +import TotpCodeForm from '@/components/auth/TotpCodeForm' +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 { + FACTOR_NAME_MAX_LENGTH, + factorNameSchema, + fieldErrors, + type FieldErrors, +} from '@/auth/validation' +import { isAal2Required, useStepUp } from '@/auth/useStepUp' +import { useMfaFailureMessage } from '@/auth/useMfaFailureMessage' +import { getSupabaseClient } from '@/lib/supabase' +import { useT } from '@/i18n/useT' + +export interface EnrolTotpProps { + /** The factor is verified: the list is read again. */ + onDone: () => void + /** Closed without verifying; the unverified factor it created is removed first. */ + onClose: () => void +} + +/** + * Adds a TOTP factor (contract §5.6): name → enrol → QR code and the secret + * for manual entry → a code from the authenticator → verified. The secret + * lives in this component's state only: never in a store, storage or a log, + * gone when it unmounts. An unverified factor it created is removed on + * cancel, and on unmount as a fallback (a dormant factor is a path, §5.7.3). + */ +export default function EnrolTotp({ onDone, onClose }: EnrolTotpProps) { + const t = useT() + const describe = useMfaFailureMessage() + const stepUp = useStepUp() + const [name, setName] = useState('') + const [errors, setErrors] = useState>({}) + const [failure, setFailure] = useState(null) + const [busy, setBusy] = useState(false) + const [enrolment, setEnrolment] = useState(null) + const unverifiedId = useRef(null) + + useEffect( + () => () => { + const client = getSupabaseClient() + const factorId = unverifiedId.current + if (client && factorId) void unenrollFactor(client, factorId).catch(() => undefined) + }, + [], + ) + + async function enrol(friendlyName: string) { + const client = getSupabaseClient() + if (!client) return + setFailure(null) + setBusy(true) + try { + const created = await enrollTotp(client, friendlyName) + unverifiedId.current = created.factorId + setEnrolment(created) + } catch (error) { + // A verified factor exists and the session is aal1: step up, then enrol again. + const opened = isAal2Required(error) && (await stepUp.open(() => void enrol(friendlyName))) + if (!opened) setFailure(describe(error)) + } + setBusy(false) + } + + function submitName(event: FormEvent) { + event.preventDefault() + const parsed = factorNameSchema.safeParse({ name }) + if (!parsed.success) { + setErrors(fieldErrors(parsed.error)) + return + } + setErrors({}) + void enrol(parsed.data.name) + } + + function verified() { + unverifiedId.current = null + setEnrolment(null) + onDone() + } + + async function cancel() { + const client = getSupabaseClient() + const factorId = unverifiedId.current + unverifiedId.current = null + setEnrolment(null) + if (client && factorId) await unenrollFactor(client, factorId).catch(() => undefined) + onClose() + } + + if (enrolment) { + return ( +
+

{t('mfa.enrol.scan')}

+ {/* A data: URI built by supabase-js, shown as an image: no markup enters the page. */} + {t('mfa.enrol.qr_alt')} +
+

{t('mfa.enrol.secret_label')}

+

{t('mfa.enrol.secret_hint')}

+ + {enrolment.secret} + +
+ void cancel()} + /> +
+ ) + } + + return ( +
+ {stepUp.challenge ? ( + + ) : ( + + + setName(e.target.value)} + autoComplete="off" + aria-invalid={Boolean(errors.name)} + aria-describedby={fieldDescribedBy('factor-name', 'hint', errors.name)} + /> + + {failure && {failure}} +
+ + +
+ + )} +
+ ) +} diff --git a/apps/app/src/components/account/MfaFactors.tsx b/apps/app/src/components/account/MfaFactors.tsx new file mode 100644 index 00000000..d8c11a30 --- /dev/null +++ b/apps/app/src/components/account/MfaFactors.tsx @@ -0,0 +1,197 @@ +import { useEffect, useState } from 'react' +import { listTotpFactors, unenrollFactor, type TotpFactor } from '@faunosteo/supabase' +import InlineStepUp from '@/components/auth/InlineStepUp' +import { factorLabel } from '@/components/auth/TotpCodeForm' +import Badge from '@/components/ui/Badge' +import Button from '@/components/ui/Button' +import Dialog from '@/components/ui/Dialog' +import Notice from '@/components/ui/Notice' +import EnrolTotp from './EnrolTotp' +import { isAal2Required, useStepUp } from '@/auth/useStepUp' +import { useMfaFailureMessage } from '@/auth/useMfaFailureMessage' +import { getSupabaseClient } from '@/lib/supabase' +import { useLocaleStore } from '@/state/localeStore' +import { useT } from '@/i18n/useT' + +type ListState = + | { status: 'loading' } + | { status: 'ready'; factors: TotpFactor[] } + | { status: 'error'; error: unknown } + +/** The account's TOTP factors, verified and unverified, read from GoTrue on open and after each change. */ +function useFactorList() { + const [state, setState] = useState({ status: 'loading' }) + const [reload, setReload] = useState(0) + + useEffect(() => { + let live = true + const client = getSupabaseClient() + if (!client) return + listTotpFactors(client) + .then((factors) => { + if (live) setState({ status: 'ready', factors }) + }) + .catch((error: unknown) => { + if (live) setState({ status: 'error', error }) + }) + return () => { + live = false + } + }, [reload]) + + return { state, refresh: () => setReload((n) => n + 1) } +} + +function FactorRow({ factor, onRemove }: { factor: TotpFactor; onRemove: () => void }) { + const t = useT() + const locale = useLocaleStore((s) => s.locale) + const verified = factor.status === 'verified' + return ( +
  • +
    +

    + {factorLabel(factor, t('mfa.factor.unnamed'))} + + {t(verified ? 'mfa.factor.verified' : 'mfa.factor.unverified')} + +

    +

    + {t('mfa.factor.added_on').replace( + '{date}', + new Date(factor.createdAt).toLocaleDateString(locale), + )} +

    +
    + +
  • + ) +} + +/** + * Double authentification in Mon compte, Sécurité (contract §5.6): the + * factor list, adding one, removing one after a confirmation. GoTrue's `aal2` + * requirements (a second factor, removing a verified one) open the step-up + * in place; the action is then sent again, never worked around. + */ +export default function MfaFactors() { + const t = useT() + const describe = useMfaFailureMessage() + const stepUp = useStepUp() + const { state, refresh } = useFactorList() + const [enrolling, setEnrolling] = useState(false) + const [toRemove, setToRemove] = useState(null) + const [removing, setRemoving] = useState(false) + const [failure, setFailure] = useState(null) + const [notice, setNotice] = useState(null) + + async function remove(factor: TotpFactor) { + const client = getSupabaseClient() + if (!client) return + setFailure(null) + setRemoving(true) + try { + await unenrollFactor(client, factor.id) + setNotice(t('mfa.factor.removed')) + refresh() + } catch (error) { + const opened = isAal2Required(error) && (await stepUp.open(() => void remove(factor))) + if (!opened) setFailure(describe(error)) + } + setRemoving(false) + setToRemove(null) + } + + function enrolled() { + setEnrolling(false) + setNotice(t('mfa.enrol.done')) + refresh() + } + + function closeEnrolment() { + setEnrolling(false) + refresh() + } + + const factors = state.status === 'ready' ? state.factors : [] + return ( +
    +
    +

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

    +

    {t('mfa.description')}

    +
    + {state.status === 'loading' && ( +

    + {t('mfa.factor.loading')} +

    + )} + {state.status === 'error' && ( +
    + {describe(state.error)} + +
    + )} + {state.status === 'ready' && factors.length === 0 && ( +

    {t('mfa.factor.none')}

    + )} + {factors.length > 0 && ( +
      + {factors.map((factor) => ( + setToRemove(factor)} /> + ))} +
    + )} + {stepUp.challenge && } + {failure && {failure}} + {notice && {notice}} + {enrolling ? ( + + ) : ( + + )} + setToRemove(null)} + title={t('mfa.remove.title')} + description={ +

    + {t('mfa.remove.body').replace( + '{name}', + toRemove ? factorLabel(toRemove, t('mfa.factor.unnamed')) : '', + )} +

    + } + size="sm" + > +
    + + +
    +
    +
    + ) +} diff --git a/apps/app/src/components/account/SecurityPanel.tsx b/apps/app/src/components/account/SecurityPanel.tsx index 7d9244bb..81d33bf6 100644 --- a/apps/app/src/components/account/SecurityPanel.tsx +++ b/apps/app/src/components/account/SecurityPanel.tsx @@ -1,10 +1,12 @@ import { useState, type FormEvent } from 'react' import { updatePassword } from '@faunosteo/supabase' +import InlineStepUp from '@/components/auth/InlineStepUp' 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 MfaFactors from './MfaFactors' import SectionCard from './SectionCard' import { fieldErrors, @@ -13,6 +15,7 @@ import { type FieldErrors, } from '@/auth/validation' import { useAuthFailureMessage } from '@/auth/useAuthFailureMessage' +import { isAal2Required, useStepUp } from '@/auth/useStepUp' import { getSupabaseClient } from '@/lib/supabase' import { useAuthStore } from '@/state/authStore' import { useT } from '@/i18n/useT' @@ -27,29 +30,38 @@ function ChangePasswordForm() { const [errors, setErrors] = useState>({}) const [failure, setFailure] = useState(null) const [state, setState] = useState('idle') + const stepUp = useStepUp() - async function submit(e: FormEvent) { - e.preventDefault() + async function save(password: string) { const client = getSupabaseClient() - const parsed = newPasswordSchema.safeParse(values) if (!client) return + setFailure(null) + setState('saving') + try { + await updatePassword(client, password) + setValues({ password: '', passwordConfirm: '' }) + setState('saved') + } catch (err) { + // With a verified factor GoTrue wants aal2 (IDENTITY.md §4.1): step up, then send it again. + const opened = isAal2Required(err) && (await stepUp.open(() => void save(password))) + if (!opened) setFailure(describe(err)) + setState('idle') + } + } + + function submit(e: FormEvent) { + e.preventDefault() + const parsed = newPasswordSchema.safeParse(values) 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') - } + void save(parsed.data.password) } + if (stepUp.challenge) return + return (
    {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/InlineStepUp.tsx b/apps/app/src/components/auth/InlineStepUp.tsx new file mode 100644 index 00000000..37bfa2a9 --- /dev/null +++ b/apps/app/src/components/auth/InlineStepUp.tsx @@ -0,0 +1,15 @@ +import Notice from '@/components/ui/Notice' +import TotpCodeForm from './TotpCodeForm' +import type { StepUpChallenge } from '@/auth/useStepUp' +import { useT } from '@/i18n/useT' + +/** GoTrue asked for `aal2`: the reason, then the challenge in place; the action resumes once it succeeds. */ +export default function InlineStepUp({ challenge }: { challenge: StepUpChallenge }) { + const t = useT() + return ( +

    + {t('mfa.step_up.required')} + +
    + ) +} diff --git a/apps/app/src/components/auth/TotpCodeForm.tsx b/apps/app/src/components/auth/TotpCodeForm.tsx new file mode 100644 index 00000000..0d7e1387 --- /dev/null +++ b/apps/app/src/components/auth/TotpCodeForm.tsx @@ -0,0 +1,117 @@ +import { useId, useState, type FormEvent } from 'react' +import { verifyTotp, type TotpFactor } from '@faunosteo/supabase' +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 Select from '@/components/ui/Select' +import { fieldErrors, totpCodeSchema, type FieldErrors } from '@/auth/validation' +import { useMfaFailureMessage } from '@/auth/useMfaFailureMessage' +import { getSupabaseClient } from '@/lib/supabase' +import { useT } from '@/i18n/useT' + +/** A factor the code may come from: the account's verified ones, or the one being enrolled. */ +export type CodeFactor = Pick + +export interface TotpCodeFormProps { + /** At least one; a choice is offered when there are several. */ + factors: CodeFactor[] + /** Called once GoTrue accepted the code: the session is `aal2` from now on. */ + onVerified: () => void + onCancel?: () => void +} + +/** The name a factor is listed under, or the generic one when it has none. */ +export function factorLabel(factor: CodeFactor, fallback: string): string { + return factor.friendlyName ?? fallback +} + +/** + * A 6-digit TOTP code, challenged and verified by GoTrue: the step-up + * challenge (contract §5.6) with a verified factor, or the verification of a + * factor being enrolled. Success upgrades this session to `aal2` + * (supabase-js then emits the new session to the store). The code is never + * kept once sent. + */ +export default function TotpCodeForm({ factors, onVerified, onCancel }: TotpCodeFormProps) { + const t = useT() + const describe = useMfaFailureMessage() + const id = useId() + const [factorId, setFactorId] = useState(factors[0]?.id ?? '') + const [code, setCode] = useState('') + const [errors, setErrors] = useState>({}) + const [failure, setFailure] = useState(null) + const [busy, setBusy] = useState(false) + + async function submit(event: FormEvent) { + event.preventDefault() + const client = getSupabaseClient() + const parsed = totpCodeSchema.safeParse({ code }) + if (!client) return + if (!parsed.success) { + setErrors(fieldErrors(parsed.error)) + return + } + setErrors({}) + setFailure(null) + setBusy(true) + try { + await verifyTotp(client, factorId, parsed.data.code) + setCode('') + onVerified() + } catch (error) { + setCode('') + setFailure(describe(error)) + setBusy(false) + } + } + + const codeId = `${id}-code` + return ( + + {factors.length > 1 && ( + + + + )} + + setCode(e.target.value)} + inputMode="numeric" + autoComplete="one-time-code" + maxLength={7} + aria-invalid={Boolean(errors.code)} + aria-describedby={fieldDescribedBy(codeId, 'hint', errors.code)} + /> + + {failure && {failure}} +
    + + {onCancel && ( + + )} +
    + + ) +} diff --git a/apps/app/src/components/shell/AccessDenied.tsx b/apps/app/src/components/shell/AccessDenied.tsx new file mode 100644 index 00000000..c8f6fd0f --- /dev/null +++ b/apps/app/src/components/shell/AccessDenied.tsx @@ -0,0 +1,26 @@ +import ButtonLink from '@/components/ui/ButtonLink' +import Card from '@/components/ui/Card' +import { usePageHeading } from '@/app/usePageHeading' +import { useT } from '@/i18n/useT' + +/** + * « Accès non autorisé » (contract §5.3, BDR-094): what a catalogue or + * administration page shows when the server refuses (`rights.*`, and + * `not_found` under /app/anatomy), the same whether the sheet exists or not. + * Nothing from the address is echoed. + */ +export default function AccessDenied() { + const t = useT() + const heading = usePageHeading() + return ( + +

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

    +

    {t('access_denied.body')}

    + + {t('access_denied.back')} + +
    + ) +} diff --git a/apps/app/src/components/shell/PlaceholderPage.tsx b/apps/app/src/components/shell/PlaceholderPage.tsx new file mode 100644 index 00000000..05632f76 --- /dev/null +++ b/apps/app/src/components/shell/PlaceholderPage.tsx @@ -0,0 +1,16 @@ +import { usePageHeading } from '@/app/usePageHeading' +import { useT } from '@/i18n/useT' + +/** + * V1-2.5 placeholder: the heading of a catalogue or administration page that + * a later slice of the step builds (G to I). It requests nothing. + */ +export default function PlaceholderPage({ titleKey }: { titleKey: string }) { + const t = useT() + const heading = usePageHeading() + return ( +

    + {t(titleKey)} +

    + ) +} diff --git a/apps/app/src/components/shell/SidebarNav.tsx b/apps/app/src/components/shell/SidebarNav.tsx index ac0eebc2..439eacdf 100644 --- a/apps/app/src/components/shell/SidebarNav.tsx +++ b/apps/app/src/components/shell/SidebarNav.tsx @@ -1,5 +1,8 @@ +import { Fragment } from 'react' import { NavLink } from 'react-router-dom' import Icon, { type IconName } from '@/components/ui/Icon' +import { navigationHint, type NavigationHint } from '@/auth/navigationHint' +import { useAuthStore } from '@/state/authStore' import { useT } from '@/i18n/useT' interface NavItem { @@ -8,12 +11,24 @@ interface NavItem { labelKey: string hintKey?: string end?: boolean + /** Shown only when this part of the navigation hint holds (V1-2, §11.1). */ + shownWhen?: keyof NavigationHint + /** Set apart by a separator above and below, as on the validated board 10. */ + separated?: boolean } export const NAV_ITEMS: readonly NavItem[] = [ { to: '/app', icon: 'dashboard', labelKey: 'shell.nav.dashboard', end: true }, { to: '/app/clients', icon: 'users', labelKey: 'shell.nav.clients' }, { to: '/app/animals', icon: 'paw', labelKey: 'shell.nav.animals' }, + { to: '/app/anatomy', icon: 'book', labelKey: 'shell.nav.anatomy', shownWhen: 'catalog' }, + { + to: '/app/admin', + icon: 'shield', + labelKey: 'shell.nav.admin', + shownWhen: 'admin', + separated: true, + }, { to: '/app/account', icon: 'user', labelKey: 'shell.nav.account' }, { to: '/', @@ -33,29 +48,41 @@ function linkClass(active: boolean): string { ].join(' ') } -/** The destinations of the shell, in the validated mockup's order; `onNavigate` closes the mobile drawer. */ +/** + * The destinations of the shell, in the validated mockup's order; `onNavigate` + * closes the mobile drawer. « Fiches anatomiques » and « Administration » follow + * the account's own grant rows and roles: hiding an entry protects nothing, + * the pages act on the server's refusal. + */ export default function SidebarNav({ onNavigate }: { onNavigate?: () => void }) { const t = useT() + const grants = useAuthStore((s) => s.catalogGrants) + const roles = useAuthStore((s) => s.roles) + const hint = navigationHint(grants, roles) + const items = NAV_ITEMS.filter((item) => !item.shownWhen || hint[item.shownWhen]) return ( ) diff --git a/apps/app/src/components/ui/Icon.tsx b/apps/app/src/components/ui/Icon.tsx index b44da71a..8124fb75 100644 --- a/apps/app/src/components/ui/Icon.tsx +++ b/apps/app/src/components/ui/Icon.tsx @@ -7,6 +7,8 @@ export type IconName = | 'user' | 'users' | 'paw' + | 'book' + | 'shield' | 'tool' | 'logout' | 'eye' @@ -24,6 +26,8 @@ const PATHS: Record = { user: 'M12 12a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM4 21a8 8 0 0 1 16 0', users: 'M9 11a4 4 0 1 0 0-8 4 4 0 0 0 0 8zM2 21a7 7 0 0 1 14 0M16 3.5a4 4 0 0 1 0 7M22 21a7 7 0 0 0-4.5-6.5', paw: 'M3.7 10.5a1.8 1.8 0 1 0 3.6 0 1.8 1.8 0 1 0-3.6 0M7.1 6.5a1.9 1.9 0 1 0 3.8 0 1.9 1.9 0 1 0-3.8 0M13.1 6.5a1.9 1.9 0 1 0 3.8 0 1.9 1.9 0 1 0-3.8 0M16.7 10.5a1.8 1.8 0 1 0 3.6 0 1.8 1.8 0 1 0-3.6 0M12 12.5c-2.5 0-5 3.2-5 5.3 0 1.6 1.3 2.4 2.8 2.4 1 0 1.5-.5 2.2-.5s1.2.5 2.2.5c1.5 0 2.8-.8 2.8-2.4 0-2.1-2.5-5.3-5-5.3z', + book: 'M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2zM4 21V5M8 7h7M8 11h5', + shield: 'M12 3l8 3v6c0 4.5-3.4 8-8 9-4.6-1-8-4.5-8-9V6zM9 12l2 2 4-4', tool: 'M14 3l7 7-4 4-7-7zM10 10l-6 6 4 4 6-6M3 21l3-3', logout: 'M10 4H5v16h5M15 8l5 4-5 4M20 12H9', eye: 'M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12zM12 15a3 3 0 1 0 0-6 3 3 0 0 0 0 6z', diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index e444ef4c..896e93c3 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -444,8 +444,6 @@ export const en: Dict = { 'account.security.changing_password': 'Updating…', 'account.security.password_changed': 'Password updated.', 'account.security.mfa_title': 'Two-factor authentication', - 'account.security.mfa_note': - 'Not available in this version yet. It will be offered, then required for platform roles.', 'account.security.sign_out_everywhere_note': 'Signing out closes the session on this device.', 'account.avatar.title': 'Profile photo', @@ -857,4 +855,62 @@ export const en: Dict = { 'relations.void.confirm': 'Remove the relation', 'relations.void.done': 'Relation removed (entered by mistake).', 'relations.error.end_before_start': 'The end cannot come before the start.', + + // V1-2.5: catalogue and administration entries, access denied, MFA + 'auth.failure.aal2_required': 'Your account is protected by two-factor authentication: enter a code from your authenticator app first.', + 'shell.nav.anatomy': 'Anatomical sheets', + 'shell.nav.admin': 'Administration', + 'access_denied.title': 'Access denied', + 'access_denied.body': "You don't have permission to access this page.", + 'access_denied.back': 'Back to dashboard', + 'admin.sheets.title': 'Official sheets', + 'admin.sheets.new': 'New sheet', + 'admin.species.title': 'Species', + 'admin.access.title': 'Access and permissions', + 'admin.step_up.title': 'Two-factor authentication required', + 'admin.step_up.body': 'Administration needs a strengthened session: enter the 6-digit code from your authenticator app.', + 'admin.step_up.no_factor': 'Administration requires two-factor authentication. First add a factor in My account, Security.', + 'admin.step_up.to_security': 'Open My account, Security', + 'mfa.description': 'A 6-digit code from an authenticator app, on top of your password. Required for administration.', + 'mfa.factor.loading': 'Loading factors…', + 'mfa.factor.none': 'No factor yet.', + 'mfa.factor.list_label': 'Authentication factors', + 'mfa.factor.unnamed': 'Unnamed factor', + 'mfa.factor.verified': 'Verified', + 'mfa.factor.unverified': 'Not verified', + 'mfa.factor.added_on': 'Added on {date}', + 'mfa.factor.remove': 'Remove', + 'mfa.factor.removed': 'Factor removed.', + 'mfa.remove.title': 'Remove this factor?', + 'mfa.remove.body': '“{name}” will no longer strengthen your session. Removing a verified factor needs a strengthened session.', + 'mfa.remove.confirm': 'Remove', + 'mfa.enrol.start': 'Add a factor', + 'mfa.enrol.name': 'Factor name', + 'mfa.enrol.name_hint': 'To recognise it in the list, for example “Personal phone”.', + 'mfa.enrol.continue': 'Continue', + 'mfa.enrol.creating': 'Creating…', + 'mfa.enrol.scan': 'Scan this QR code with your authenticator app, then enter the code it shows.', + 'mfa.enrol.qr_alt': 'QR code to scan with your authenticator app', + 'mfa.enrol.secret_label': 'Setup key for manual entry', + 'mfa.enrol.secret_hint': 'If you cannot scan the QR code. It is shown only once: do not keep it anywhere else.', + 'mfa.enrol.done': 'Factor added and verified.', + 'mfa.code.label': 'Verification code', + 'mfa.code.hint': 'The 6 digits shown by your authenticator app.', + 'mfa.code.verify': 'Verify', + 'mfa.code.verifying': 'Verifying…', + 'mfa.step_up.factor': 'Factor', + 'mfa.step_up.required': 'This action needs a strengthened session: enter a code from your authenticator app.', + 'mfa.error.code_format': 'The code has 6 digits.', + 'mfa.error.name_required': 'Give the factor a name.', + 'mfa.error.name_too_long': 'Name too long ({max} characters maximum).', + 'mfa.failure.aal2_required': 'This action needs a session strengthened by two-factor authentication.', + 'mfa.failure.invalid_code': 'Incorrect or expired code. Enter the code shown now.', + 'mfa.failure.factor_not_found': 'This factor no longer exists. Reload the page.', + 'mfa.failure.challenge_expired': 'The verification expired. Enter a new code.', + 'mfa.failure.too_many_factors': 'Maximum number of factors reached. Remove one before adding another.', + 'mfa.failure.name_taken': 'A factor already has this name. Choose another one.', + 'mfa.failure.rate_limited': 'Too many attempts. Wait a few minutes before trying again.', + 'mfa.failure.session_expired': 'Your session has expired. Sign in again.', + 'mfa.failure.network': 'Cannot reach the server. Check your network.', + 'mfa.failure.unavailable': 'Two-factor authentication is temporarily unavailable. Try again later.', } diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 90e4d7c0..6108240d 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -462,8 +462,6 @@ export const fr: Dict = { 'account.security.changing_password': 'Mise à jour…', 'account.security.password_changed': 'Mot de passe mis à jour.', 'account.security.mfa_title': 'Double authentification', - 'account.security.mfa_note': - 'Pas encore disponible dans cette version. Elle sera proposée, puis exigée pour les rôles plateforme.', 'account.security.sign_out_everywhere_note': 'Se déconnecter ferme la session sur cet appareil.', 'account.avatar.title': 'Photo de profil', @@ -888,4 +886,62 @@ export const fr: Dict = { 'relations.void.confirm': 'Retirer la relation', 'relations.void.done': 'Relation retirée (erreur de saisie).', 'relations.error.end_before_start': 'La fin ne peut pas précéder le début.', + + // V1-2.5: catalogue and administration entries, access denied, MFA + 'auth.failure.aal2_required': "Votre compte est protégé par la double authentification : saisissez d'abord un code de votre application d'authentification.", + 'shell.nav.anatomy': 'Fiches anatomiques', + 'shell.nav.admin': 'Administration', + 'access_denied.title': 'Accès non autorisé', + 'access_denied.body': 'Vous ne disposez pas des autorisations nécessaires pour accéder à cette page.', + 'access_denied.back': 'Retour au tableau de bord', + 'admin.sheets.title': 'Fiches officielles', + 'admin.sheets.new': 'Nouvelle fiche', + 'admin.species.title': 'Espèces', + 'admin.access.title': 'Accès et habilitations', + 'admin.step_up.title': 'Double authentification requise', + 'admin.step_up.body': "L'administration demande une session renforcée : saisissez le code à 6 chiffres de votre application d'authentification.", + 'admin.step_up.no_factor': "L'administration demande la double authentification. Ajoutez d'abord un facteur dans Mon compte, Sécurité.", + 'admin.step_up.to_security': 'Ouvrir Mon compte, Sécurité', + 'mfa.description': "Un code à 6 chiffres d'une application d'authentification, en plus du mot de passe. Exigée pour l'administration.", + 'mfa.factor.loading': 'Chargement des facteurs…', + 'mfa.factor.none': 'Aucun facteur pour le moment.', + 'mfa.factor.list_label': "Facteurs d'authentification", + 'mfa.factor.unnamed': 'Facteur sans nom', + 'mfa.factor.verified': 'Vérifié', + 'mfa.factor.unverified': 'Non vérifié', + 'mfa.factor.added_on': 'Ajouté le {date}', + 'mfa.factor.remove': 'Supprimer', + 'mfa.factor.removed': 'Facteur supprimé.', + 'mfa.remove.title': 'Supprimer ce facteur ?', + 'mfa.remove.body': '« {name} » ne servira plus à renforcer votre session. Supprimer un facteur vérifié demande une session renforcée.', + 'mfa.remove.confirm': 'Supprimer', + 'mfa.enrol.start': 'Ajouter un facteur', + 'mfa.enrol.name': 'Nom du facteur', + 'mfa.enrol.name_hint': 'Pour le reconnaître dans la liste, par exemple « Téléphone personnel ».', + 'mfa.enrol.continue': 'Continuer', + 'mfa.enrol.creating': 'Création…', + 'mfa.enrol.scan': "Scannez ce QR code avec votre application d'authentification, puis saisissez le code qu'elle affiche.", + 'mfa.enrol.qr_alt': "QR code à scanner avec votre application d'authentification", + 'mfa.enrol.secret_label': 'Clé de configuration manuelle', + 'mfa.enrol.secret_hint': "Si vous ne pouvez pas scanner le QR code. Elle n'est affichée qu'une fois : ne la conservez pas ailleurs.", + 'mfa.enrol.done': 'Facteur ajouté et vérifié.', + 'mfa.code.label': 'Code de vérification', + 'mfa.code.hint': "Les 6 chiffres affichés par votre application d'authentification.", + 'mfa.code.verify': 'Vérifier', + 'mfa.code.verifying': 'Vérification…', + 'mfa.step_up.factor': 'Facteur', + 'mfa.step_up.required': "Cette action demande une session renforcée : saisissez un code de votre application d'authentification.", + 'mfa.error.code_format': 'Le code comporte 6 chiffres.', + 'mfa.error.name_required': 'Donnez un nom au facteur.', + 'mfa.error.name_too_long': 'Nom trop long ({max} caractères maximum).', + 'mfa.failure.aal2_required': 'Cette action demande une session renforcée par la double authentification.', + 'mfa.failure.invalid_code': 'Code incorrect ou expiré. Saisissez le code affiché maintenant.', + 'mfa.failure.factor_not_found': "Ce facteur n'existe plus. Rechargez la page.", + 'mfa.failure.challenge_expired': 'La vérification a expiré. Saisissez un nouveau code.', + 'mfa.failure.too_many_factors': "Nombre maximal de facteurs atteint. Supprimez-en un avant d'en ajouter un autre.", + 'mfa.failure.name_taken': 'Un facteur porte déjà ce nom. Choisissez-en un autre.', + 'mfa.failure.rate_limited': 'Trop de tentatives. Patientez quelques minutes avant de réessayer.', + 'mfa.failure.session_expired': 'Votre session a expiré. Reconnectez-vous.', + 'mfa.failure.network': 'Connexion au serveur impossible. Vérifiez votre réseau.', + 'mfa.failure.unavailable': 'La double authentification est momentanément indisponible. Réessayez plus tard.', } diff --git a/apps/app/src/state/authStore.ts b/apps/app/src/state/authStore.ts index 99a155ab..e1ec1252 100644 --- a/apps/app/src/state/authStore.ts +++ b/apps/app/src/state/authStore.ts @@ -14,6 +14,8 @@ import { downloadAvatar, fetchOwnAvatarState, fetchPersonalWorkspaceId, + listOwnCatalogGrants, + type OwnCatalogGrant, classifyRecordError, type FaunosteoClient, type RecordFailureKind, @@ -60,6 +62,12 @@ export interface AuthState { /** Blob URL of the clean photo (downloaded under RLS), revoked on change or sign-out. */ avatarUrl: string | null workspace: WorkspaceState + /** + * The account's own catalogue grant rows, for the navigation hint only + * (contract §5.3, `navigationHint`): never a control, the server decides. + * Empty until loaded and when the read fails. + */ + catalogGrants: OwnCatalogGrant[] /** Subscribes to the client; returns the unsubscribe. Safe to call twice. */ start: () => () => void refreshAccount: () => Promise @@ -141,6 +149,9 @@ async function loadAccount(client: FaunosteoClient, user: User, set: Set, get: G await Promise.all([ loadWorkspace(client, user, profile, setOwn, get), syncAvatar(client, user, setOwn, get).catch(() => setOwn({ avatar: null })), + listOwnCatalogGrants(client, user.id) + .then((catalogGrants) => setOwn({ catalogGrants })) + .catch(() => setOwn({ catalogGrants: [] })), ]) } @@ -153,6 +164,7 @@ function accountReset(get: Get): Partial { avatar: null, avatarUrl: null, workspace: { status: 'idle' }, + catalogGrants: [], } } @@ -223,6 +235,7 @@ export const useAuthStore = create((set, get) => ({ avatar: null, avatarUrl: null, workspace: { status: 'idle' }, + catalogGrants: [], start: () => { const client = getSupabaseClient() diff --git a/apps/app/tests/helpers/fakeSupabase.ts b/apps/app/tests/helpers/fakeSupabase.ts index 1f5d56cd..0bde29f8 100644 --- a/apps/app/tests/helpers/fakeSupabase.ts +++ b/apps/app/tests/helpers/fakeSupabase.ts @@ -160,9 +160,43 @@ export interface FakeSupabase { updateUser: ReturnType resetPasswordForEmail: ReturnType signInWithOAuth: ReturnType + mfa: { + listFactors: ReturnType + enroll: ReturnType + challengeAndVerify: ReturnType + unenroll: ReturnType + getAuthenticatorAssuranceLevel: ReturnType + } } } +/** A GoTrue factor row as `listFactors().all` returns it. */ +export function fakeFactor(patch: Record = {}) { + return { + id: 'factor-1', + friendly_name: 'Phone', + factor_type: 'totp', + status: 'verified', + created_at: '2026-11-01T10:00:00Z', + updated_at: '2026-11-01T10:00:00Z', + ...patch, + } +} + +/** Programs the account's factors (listFactors) and the session level. */ +export function setMfa( + fake: FakeSupabase, + factors: Array>, + currentLevel: 'aal1' | 'aal2' = 'aal1', +) { + fake.auth.mfa.listFactors.mockResolvedValue({ data: { all: factors, totp: [] }, error: null }) + const nextLevel = factors.some((f) => f.status === 'verified') ? 'aal2' : 'aal1' + fake.auth.mfa.getAuthenticatorAssuranceLevel.mockResolvedValue({ + data: { currentLevel, nextLevel, currentAuthenticationMethods: [] }, + error: null, + }) +} + export function createFakeSupabase( tables: Record = { profiles: [fakeProfile()], profile_roles: [], assets: [] }, ): FakeSupabase { @@ -186,6 +220,16 @@ export function createFakeSupabase( updateUser: vi.fn(), resetPasswordForEmail: vi.fn(), signInWithOAuth: vi.fn(), + mfa: { + listFactors: vi.fn(async () => ({ data: { all: [], totp: [] }, error: null })), + enroll: vi.fn(), + challengeAndVerify: vi.fn(async () => ({ data: {}, error: null })), + unenroll: vi.fn(async () => ({ data: {}, error: null })), + getAuthenticatorAssuranceLevel: vi.fn(async () => ({ + data: { currentLevel: 'aal1', nextLevel: 'aal1', currentAuthenticationMethods: [] }, + error: null, + })), + }, } const client = { auth, diff --git a/apps/app/tests/unit/components.SecurityPanel.test.tsx b/apps/app/tests/unit/components.SecurityPanel.test.tsx new file mode 100644 index 00000000..e047814e --- /dev/null +++ b/apps/app/tests/unit/components.SecurityPanel.test.tsx @@ -0,0 +1,191 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { cleanup, render, screen, waitFor, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter } from 'react-router-dom' +import { + createFakeSupabase, + fakeFactor, + fakeUser, + setMfa, + type FakeSupabase, +} from '../helpers/fakeSupabase' + +const mocks = vi.hoisted(() => ({ fake: null as unknown })) +vi.mock('@/lib/supabase', () => ({ + getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null, + isSupabaseConfigured: () => mocks.fake !== null, +})) + +import SecurityPanel from '@/components/account/SecurityPanel' +import { useAuthStore } from '@/state/authStore' +import { useLocaleStore } from '@/state/localeStore' +import { fr } from '@/i18n/fr' + +const QR = 'data:image/svg+xml;utf-8,%3Csvg%3E%3C/svg%3E' +const SECRET = 'JBSWY3DPEHPK3PXP' +const AAL_REFUSED = { name: 'AuthApiError', code: 'insufficient_aal', status: 403, message: 'raw' } + +let fake: FakeSupabase + +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + fake = createFakeSupabase() + mocks.fake = fake + useAuthStore.setState({ status: 'signed_in', user: fakeUser() }) + fake.auth.mfa.enroll.mockResolvedValue({ + data: { id: 'new-1', type: 'totp', friendly_name: 'Laptop', totp: { qr_code: QR, secret: SECRET, uri: 'otpauth://x' } }, + error: null, + }) +}) +afterEach(cleanup) + +function mount() { + return render( + + + , + ) +} + +function factorList() { + return screen.getByRole('list', { name: fr['mfa.factor.list_label'] }) +} + +async function startEnrolment(user: ReturnType, name = 'Laptop') { + await user.click(await screen.findByRole('button', { name: fr['mfa.enrol.start'] })) + await user.type(screen.getByLabelText(fr['mfa.enrol.name']), name) + await user.click(screen.getByRole('button', { name: fr['mfa.enrol.continue'] })) +} + +describe('Security, factors', () => { + it('lists verified and unverified factors with their state and date', async () => { + setMfa(fake, [ + fakeFactor({ id: 'f-1', friendly_name: 'Phone' }), + fakeFactor({ id: 'f-2', friendly_name: '', status: 'unverified' }), + ]) + mount() + await screen.findByText('Phone') + const rows = within(factorList()).getAllByRole('listitem') + expect(rows).toHaveLength(2) + expect(rows[0]).toHaveTextContent(fr['mfa.factor.verified']) + expect(rows[0]).toHaveTextContent(new Date('2026-11-01T10:00:00Z').toLocaleDateString('fr')) + expect(rows[1]).toHaveTextContent(fr['mfa.factor.unnamed']) + expect(rows[1]).toHaveTextContent(fr['mfa.factor.unverified']) + expect(screen.queryByText(fr['mfa.factor.none'])).toBeNull() + }) + + it('enrols: name, QR code as an image, secret once, then the code verifies it', async () => { + const user = userEvent.setup() + mount() + expect(await screen.findByText(fr['mfa.factor.none'])).toBeInTheDocument() + await startEnrolment(user) + expect(fake.auth.mfa.enroll).toHaveBeenCalledWith({ factorType: 'totp', friendlyName: 'Laptop' }) + const qr = await screen.findByRole('img', { name: fr['mfa.enrol.qr_alt'] }) + expect(qr).toHaveAttribute('src', QR) + expect(screen.getByText(SECRET)).toBeInTheDocument() + + setMfa(fake, [fakeFactor({ id: 'new-1', friendly_name: 'Laptop' })], 'aal2') + await user.type(screen.getByLabelText(fr['mfa.code.label']), '123456') + await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] })) + expect(fake.auth.mfa.challengeAndVerify).toHaveBeenCalledWith({ factorId: 'new-1', code: '123456' }) + expect(await screen.findByText(fr['mfa.enrol.done'])).toBeInTheDocument() + expect(screen.queryByText(SECRET)).toBeNull() + expect(screen.queryByRole('img', { name: fr['mfa.enrol.qr_alt'] })).toBeNull() + expect(within(factorList()).getByText('Laptop')).toBeInTheDocument() + expect(fake.auth.mfa.unenroll).not.toHaveBeenCalled() + expect(JSON.stringify(useAuthStore.getState())).not.toContain(SECRET) + }) + + it('cancel removes the unverified factor it created and clears the secret', async () => { + const user = userEvent.setup() + mount() + await startEnrolment(user) + await screen.findByText(SECRET) + await user.click(screen.getByRole('button', { name: fr['common.cancel'] })) + expect(fake.auth.mfa.unenroll).toHaveBeenCalledWith({ factorId: 'new-1' }) + expect(screen.queryByText(SECRET)).toBeNull() + expect(await screen.findByRole('button', { name: fr['mfa.enrol.start'] })).toBeInTheDocument() + }) + + it('leaving the page mid-enrolment removes the unverified factor', async () => { + const user = userEvent.setup() + const view = mount() + await startEnrolment(user) + await screen.findByText(SECRET) + view.unmount() + expect(fake.auth.mfa.unenroll).toHaveBeenCalledWith({ factorId: 'new-1' }) + }) + + it('refuses an empty name without calling GoTrue', async () => { + const user = userEvent.setup() + mount() + await user.click(await screen.findByRole('button', { name: fr['mfa.enrol.start'] })) + await user.click(screen.getByRole('button', { name: fr['mfa.enrol.continue'] })) + expect(screen.getByText(fr['mfa.error.name_required'])).toBeInTheDocument() + expect(fake.auth.mfa.enroll).not.toHaveBeenCalled() + }) + + it('a second factor at aal1 steps up first, then enrols again', async () => { + const user = userEvent.setup() + setMfa(fake, [fakeFactor({ id: 'f-1' })]) + fake.auth.mfa.enroll.mockResolvedValueOnce({ data: null, error: AAL_REFUSED }) + mount() + await startEnrolment(user) + expect(await screen.findByText(fr['mfa.step_up.required'])).toBeInTheDocument() + await user.type(screen.getByLabelText(fr['mfa.code.label']), '654321') + await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] })) + expect(fake.auth.mfa.challengeAndVerify).toHaveBeenCalledWith({ factorId: 'f-1', code: '654321' }) + expect(await screen.findByText(SECRET)).toBeInTheDocument() + expect(fake.auth.mfa.enroll).toHaveBeenCalledTimes(2) + }) + + it('removes a factor after the confirmation', async () => { + const user = userEvent.setup() + setMfa(fake, [fakeFactor({ id: 'f-1', friendly_name: 'Phone', status: 'unverified' })]) + mount() + await user.click(await screen.findByRole('button', { name: fr['mfa.factor.remove'] })) + const dialog = await screen.findByRole('dialog', { name: fr['mfa.remove.title'] }) + expect(dialog).toHaveTextContent('Phone') + expect(fake.auth.mfa.unenroll).not.toHaveBeenCalled() + setMfa(fake, []) + await user.click(within(dialog).getByRole('button', { name: fr['mfa.remove.confirm'] })) + expect(fake.auth.mfa.unenroll).toHaveBeenCalledWith({ factorId: 'f-1' }) + expect(await screen.findByText(fr['mfa.factor.removed'])).toBeInTheDocument() + expect(await screen.findByText(fr['mfa.factor.none'])).toBeInTheDocument() + }) + + it('removing a verified factor at aal1 explains aal2, steps up in place, then removes it', async () => { + const user = userEvent.setup() + setMfa(fake, [fakeFactor({ id: 'f-1', friendly_name: 'Phone' })]) + fake.auth.mfa.unenroll.mockResolvedValueOnce({ data: null, error: { ...AAL_REFUSED, status: 422 } }) + mount() + await user.click(await screen.findByRole('button', { name: fr['mfa.factor.remove'] })) + const dialog = await screen.findByRole('dialog', { name: fr['mfa.remove.title'] }) + await user.click(within(dialog).getByRole('button', { name: fr['mfa.remove.confirm'] })) + expect(await screen.findByText(fr['mfa.step_up.required'])).toBeInTheDocument() + await user.type(screen.getByLabelText(fr['mfa.code.label']), '111111') + await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] })) + await waitFor(() => expect(fake.auth.mfa.unenroll).toHaveBeenCalledTimes(2)) + expect(await screen.findByText(fr['mfa.factor.removed'])).toBeInTheDocument() + }) +}) + +describe('Security, password', () => { + it('steps up when GoTrue wants aal2 for the password, then sends it again', async () => { + const user = userEvent.setup() + setMfa(fake, [fakeFactor({ id: 'f-1' })]) + fake.auth.updateUser + .mockResolvedValueOnce({ data: null, error: { ...AAL_REFUSED, status: 401 } }) + .mockResolvedValueOnce({ data: {}, error: null }) + mount() + await user.type(screen.getByLabelText(fr['account.security.new_password']), 'CorrectHorse12') + await user.type(screen.getByLabelText(fr['auth.password_confirm']), 'CorrectHorse12') + await user.click(screen.getByRole('button', { name: fr['account.security.change_password'] })) + expect(await screen.findByText(fr['mfa.step_up.required'])).toBeInTheDocument() + await user.type(screen.getByLabelText(fr['mfa.code.label']), '222222') + await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] })) + expect(await screen.findByText(fr['account.security.password_changed'])).toBeInTheDocument() + expect(fake.auth.updateUser).toHaveBeenCalledTimes(2) + expect(fake.auth.updateUser).toHaveBeenLastCalledWith({ password: 'CorrectHorse12' }) + }) +}) diff --git a/apps/app/tests/unit/guards.RequireAdmin.test.tsx b/apps/app/tests/unit/guards.RequireAdmin.test.tsx new file mode 100644 index 00000000..db3564a9 --- /dev/null +++ b/apps/app/tests/unit/guards.RequireAdmin.test.tsx @@ -0,0 +1,178 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { cleanup, render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter, Route, Routes } from 'react-router-dom' +import { + createFakeSupabase, + fakeFactor, + fakeUser, + setMfa, + type FakeSupabase, +} from '../helpers/fakeSupabase' + +const mocks = vi.hoisted(() => ({ fake: null as unknown })) +vi.mock('@/lib/supabase', () => ({ + getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null, + isSupabaseConfigured: () => mocks.fake !== null, +})) + +import RequireAdmin from '@/app/guards/RequireAdmin' +import RequireAuth from '@/app/guards/RequireAuth' +import RequireCatalog from '@/app/guards/RequireCatalog' +import AccessDenied from '@/components/shell/AccessDenied' +import { useAuthStore } from '@/state/authStore' +import { useLocaleStore } from '@/state/localeStore' +import { fr } from '@/i18n/fr' +import { en } from '@/i18n/en' + +let fake: FakeSupabase +/** Stands for an admin page: it would request admin data as soon as it renders. */ +const adminFetch = vi.fn() + +function AdminPage() { + adminFetch() + return

    admin page

    +} + +function mount(path = '/app/admin') { + return render( + + + login page

    } /> + }> + dashboard page

    } /> + account page

    } /> + }> + } /> + + }> + } /> + + +
    +
    , + ) +} + +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + fake = createFakeSupabase() + mocks.fake = fake + adminFetch.mockClear() + useAuthStore.setState({ status: 'signed_in', user: fakeUser(), roles: [], catalogGrants: [] }) +}) +afterEach(cleanup) + +describe('RequireAdmin', () => { + it('renders the admin pages at once on an aal2 session', async () => { + setMfa(fake, [fakeFactor()], 'aal2') + mount() + expect(await screen.findByText('admin page')).toBeInTheDocument() + }) + + it('asks for a code at aal1 with a verified factor, and requests nothing before it succeeds', async () => { + const user = userEvent.setup() + setMfa(fake, [fakeFactor({ id: 'f-1' })], 'aal1') + mount() + expect(await screen.findByRole('heading', { name: fr['admin.step_up.title'] })).toBeInTheDocument() + expect(adminFetch).not.toHaveBeenCalled() + + await user.type(screen.getByLabelText(fr['mfa.code.label']), '12') + await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] })) + expect(await screen.findByText(fr['mfa.error.code_format'])).toBeInTheDocument() + expect(fake.auth.mfa.challengeAndVerify).not.toHaveBeenCalled() + + fake.auth.mfa.challengeAndVerify.mockImplementationOnce(async () => { + setMfa(fake, [fakeFactor({ id: 'f-1' })], 'aal2') + return { data: {}, error: null } + }) + await user.clear(screen.getByLabelText(fr['mfa.code.label'])) + await user.type(screen.getByLabelText(fr['mfa.code.label']), '123 456') + await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] })) + expect(fake.auth.mfa.challengeAndVerify).toHaveBeenCalledWith({ factorId: 'f-1', code: '123456' }) + expect(await screen.findByText('admin page')).toBeInTheDocument() + expect(adminFetch).toHaveBeenCalled() + }) + + it('phrases a refused code and stays on the challenge', async () => { + const user = userEvent.setup() + setMfa(fake, [fakeFactor()], 'aal1') + fake.auth.mfa.challengeAndVerify.mockResolvedValueOnce({ + data: null, + error: { name: 'AuthApiError', code: 'mfa_verification_failed', status: 422, message: 'raw' }, + }) + mount() + await user.type(await screen.findByLabelText(fr['mfa.code.label']), '000000') + await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] })) + expect(await screen.findByText(fr['mfa.failure.invalid_code'])).toBeInTheDocument() + expect(screen.queryByText('raw')).toBeNull() + expect(adminFetch).not.toHaveBeenCalled() + }) + + it('offers a choice of factor when the account has several verified ones', async () => { + setMfa(fake, [ + fakeFactor({ id: 'f-1', friendly_name: 'Phone' }), + fakeFactor({ id: 'f-2', friendly_name: 'Tablet' }), + fakeFactor({ id: 'f-3', friendly_name: 'Old', status: 'unverified' }), + ]) + mount() + const select = await screen.findByLabelText(fr['mfa.step_up.factor']) + expect(Array.from((select as HTMLSelectElement).options).map((o) => o.text)).toEqual([ + 'Phone', + 'Tablet', + ]) + }) + + it('sends an account without a verified factor to Mon compte, Sécurité', async () => { + setMfa(fake, [fakeFactor({ status: 'unverified' })], 'aal1') + mount() + expect(await screen.findByText(fr['admin.step_up.no_factor'])).toBeInTheDocument() + expect(screen.getByRole('link', { name: fr['admin.step_up.to_security'] })).toHaveAttribute( + 'href', + '/app/account#security-title', + ) + expect(screen.queryByLabelText(fr['mfa.code.label'])).toBeNull() + expect(adminFetch).not.toHaveBeenCalled() + }) + + it('says when the level cannot be read, then reads it again', async () => { + const user = userEvent.setup() + setMfa(fake, [fakeFactor()], 'aal2') + fake.auth.mfa.getAuthenticatorAssuranceLevel.mockResolvedValueOnce({ + data: null, + error: { name: 'AuthRetryableFetchError', status: 0, message: 'raw' }, + }) + mount() + expect(await screen.findByText(fr['mfa.failure.network'])).toBeInTheDocument() + await user.click(screen.getByRole('button', { name: fr['common.retry'] })) + expect(await screen.findByText('admin page')).toBeInTheDocument() + }) + + it('sends a signed-out visitor to the login page', () => { + useAuthStore.setState({ status: 'signed_out', user: null }) + mount() + expect(screen.getByText('login page')).toBeInTheDocument() + expect(fake.auth.mfa.getAuthenticatorAssuranceLevel).not.toHaveBeenCalled() + }) +}) + +describe('Accès non autorisé', () => { + it('names the refusal, echoes nothing from the address and leads back to /app', async () => { + const user = userEvent.setup() + mount('/app/anatomy?sheet=secret-id') + const heading = screen.getByRole('heading', { name: fr['access_denied.title'] }) + expect(heading).toHaveFocus() + expect(screen.getByText(fr['access_denied.body'])).toBeInTheDocument() + expect(document.body).not.toHaveTextContent('secret-id') + await user.click(screen.getByRole('link', { name: fr['access_denied.back'] })) + expect(await screen.findByText('dashboard page')).toBeInTheDocument() + }) + + it('reads in English', () => { + useLocaleStore.setState({ locale: 'en' }) + mount('/app/anatomy') + expect(screen.getByRole('heading', { name: en['access_denied.title'] })).toBeInTheDocument() + expect(screen.getByText("You don't have permission to access this page.")).toBeInTheDocument() + expect(screen.getByRole('link', { name: 'Back to dashboard' })).toHaveAttribute('href', '/app') + }) +}) diff --git a/apps/app/tests/unit/routes.AccountRoute.test.tsx b/apps/app/tests/unit/routes.AccountRoute.test.tsx index a4c43b2d..7093c0ac 100644 --- a/apps/app/tests/unit/routes.AccountRoute.test.tsx +++ b/apps/app/tests/unit/routes.AccountRoute.test.tsx @@ -39,7 +39,7 @@ function mount() { } describe('AccountRoute', () => { - it('shows the four sections, the roles and the sign-in address', () => { + it('shows the four sections, the roles and the sign-in address', async () => { mount() for (const key of [ 'account.personal.title', @@ -51,7 +51,7 @@ describe('AccountRoute', () => { } expect(screen.getByText(fr['shell.role.owner'])).toBeInTheDocument() expect(screen.getByText('alice@example.test')).toBeInTheDocument() - expect(screen.getByText(fr['account.security.mfa_note'])).toBeInTheDocument() + expect(await screen.findByText(fr['mfa.factor.none'])).toBeInTheDocument() }) it('saves personal information, empty optionals as null', async () => { diff --git a/apps/app/tests/unit/routes.ResetPasswordRoute.test.tsx b/apps/app/tests/unit/routes.ResetPasswordRoute.test.tsx new file mode 100644 index 00000000..72bd8c3e --- /dev/null +++ b/apps/app/tests/unit/routes.ResetPasswordRoute.test.tsx @@ -0,0 +1,108 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { cleanup, render, screen } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter, Route, Routes } from 'react-router-dom' +import { + createFakeSupabase, + fakeFactor, + fakeUser, + setMfa, + type FakeSupabase, +} from '../helpers/fakeSupabase' + +const mocks = vi.hoisted(() => ({ fake: null as unknown })) +vi.mock('@/lib/supabase', () => ({ + getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null, + isSupabaseConfigured: () => mocks.fake !== null, +})) + +import ResetPasswordRoute from '@/app/routes/auth/ResetPasswordRoute' +import { useAuthStore } from '@/state/authStore' +import { useLocaleStore } from '@/state/localeStore' +import { fr } from '@/i18n/fr' + +let fake: FakeSupabase + +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + fake = createFakeSupabase() + mocks.fake = fake + fake.auth.updateUser.mockResolvedValue({ data: {}, error: null }) + useAuthStore.setState({ status: 'signed_in', user: fakeUser(), recovery: true }) +}) +afterEach(cleanup) + +function mount() { + return render( + + + } /> + dashboard page

    } /> +
    +
    , + ) +} + +async function submitPassword(user: ReturnType) { + await user.type(screen.getByLabelText(fr['auth.password']), 'CorrectHorse12') + await user.type(screen.getByLabelText(fr['auth.password_confirm']), 'CorrectHorse12') + await user.click(screen.getByRole('button', { name: fr['auth.reset.submit'] })) +} + +describe('ResetPasswordRoute', () => { + it('saves the new password at once for an account without a factor', async () => { + const user = userEvent.setup() + mount() + await submitPassword(user) + expect(await screen.findByText('dashboard page')).toBeInTheDocument() + expect(fake.auth.updateUser).toHaveBeenCalledWith({ password: 'CorrectHorse12' }) + expect(fake.auth.mfa.challengeAndVerify).not.toHaveBeenCalled() + expect(useAuthStore.getState().recovery).toBe(false) + }) + + it('with a verified factor, asks for a code before sending the password', async () => { + const user = userEvent.setup() + setMfa(fake, [fakeFactor({ id: 'f-1' })], 'aal1') + mount() + await submitPassword(user) + expect(await screen.findByText(fr['mfa.step_up.required'])).toBeInTheDocument() + expect(fake.auth.updateUser).not.toHaveBeenCalled() + await user.type(screen.getByLabelText(fr['mfa.code.label']), '123456') + await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] })) + expect(fake.auth.mfa.challengeAndVerify).toHaveBeenCalledWith({ factorId: 'f-1', code: '123456' }) + expect(await screen.findByText('dashboard page')).toBeInTheDocument() + expect(fake.auth.updateUser).toHaveBeenCalledWith({ password: 'CorrectHorse12' }) + }) + + it('steps up when GoTrue refuses for insufficient_aal, then sends it again', async () => { + const user = userEvent.setup() + // The level read says nothing (no factor in the session yet), GoTrue knows better. + fake.auth.mfa.listFactors.mockResolvedValue({ + data: { all: [fakeFactor({ id: 'f-1' })], totp: [] }, + error: null, + }) + fake.auth.updateUser.mockResolvedValueOnce({ + data: null, + error: { name: 'AuthApiError', code: 'insufficient_aal', status: 401, message: 'raw' }, + }) + mount() + await submitPassword(user) + expect(await screen.findByText(fr['mfa.step_up.required'])).toBeInTheDocument() + await user.type(screen.getByLabelText(fr['mfa.code.label']), '123456') + await user.click(screen.getByRole('button', { name: fr['mfa.code.verify'] })) + expect(await screen.findByText('dashboard page')).toBeInTheDocument() + expect(fake.auth.updateUser).toHaveBeenCalledTimes(2) + }) + + it('phrases insufficient_aal when the account has no factor to step up with', async () => { + const user = userEvent.setup() + fake.auth.updateUser.mockResolvedValueOnce({ + data: null, + error: { name: 'AuthApiError', code: 'insufficient_aal', status: 401, message: 'raw' }, + }) + mount() + await submitPassword(user) + expect(await screen.findByText(fr['auth.failure.aal2_required'])).toBeInTheDocument() + expect(screen.queryByText('raw')).toBeNull() + }) +}) diff --git a/apps/app/tests/unit/shell.navigation.test.tsx b/apps/app/tests/unit/shell.navigation.test.tsx new file mode 100644 index 00000000..c951ba01 --- /dev/null +++ b/apps/app/tests/unit/shell.navigation.test.tsx @@ -0,0 +1,135 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest' +import { cleanup, render, screen, within } from '@testing-library/react' +import userEvent from '@testing-library/user-event' +import { MemoryRouter, Route, Routes } from 'react-router-dom' +import type { OwnCatalogGrant, PlatformRole } from '@faunosteo/supabase' +import { createFakeSupabase, fakeProfile, fakeUser, type FakeSupabase } from '../helpers/fakeSupabase' + +const mocks = vi.hoisted(() => ({ fake: null as unknown })) +vi.mock('@/lib/supabase', () => ({ + getSupabaseClient: () => (mocks.fake as FakeSupabase | null)?.client ?? null, + isSupabaseConfigured: () => mocks.fake !== null, +})) + +import AppLayout from '@/components/shell/AppLayout' +import { navigationHint } from '@/auth/navigationHint' +import { useAuthStore } from '@/state/authStore' +import { useLocaleStore } from '@/state/localeStore' +import { fr } from '@/i18n/fr' + +const NOW = Date.parse('2026-11-02T12:00:00Z') + +function grant(kind: OwnCatalogGrant['kind'], patch: Partial = {}): OwnCatalogGrant { + return { kind, expires_at: null, revoked_at: null, ...patch } +} + +describe('navigationHint', () => { + it('shows nothing extra without a grant or the owner role', () => { + expect(navigationHint([], [], NOW)).toEqual({ catalog: false, admin: false }) + expect(navigationHint([], ['admin', 'support'], NOW)).toEqual({ catalog: false, admin: false }) + }) + + it('shows the catalogue to a catalogue reader only', () => { + expect(navigationHint([grant('catalog_reader')], [], NOW)).toEqual({ catalog: true, admin: false }) + }) + + it('shows both entries to any capability holder', () => { + for (const kind of ['sheet_editor', 'sheet_reviewer', 'sheet_publisher'] as const) { + expect(navigationHint([grant(kind)], [], NOW)).toEqual({ catalog: true, admin: true }) + } + }) + + it('shows the administration to the owner role, the catalogue only with a grant', () => { + expect(navigationHint([], ['owner'], NOW)).toEqual({ catalog: false, admin: true }) + }) + + it('ignores revoked and expired grants, keeps one expiring later', () => { + const revoked = grant('sheet_editor', { revoked_at: '2026-10-01T00:00:00Z' }) + const expired = grant('catalog_reader', { expires_at: '2026-11-01T00:00:00Z' }) + expect(navigationHint([revoked, expired], [], NOW)).toEqual({ catalog: false, admin: false }) + const later = grant('catalog_reader', { expires_at: '2026-12-01T00:00:00Z' }) + expect(navigationHint([later], [], NOW).catalog).toBe(true) + }) +}) + +function mount(grants: OwnCatalogGrant[], roles: PlatformRole[] = []) { + useAuthStore.setState({ catalogGrants: grants, roles }) + return render( + + + }> + dashboard page

    } /> +
    +
    +
    , + ) +} + +function sidebar() { + return screen.getByRole('navigation', { name: fr['shell.nav_label'] }) +} + +beforeEach(() => { + useLocaleStore.setState({ locale: 'fr' }) + mocks.fake = createFakeSupabase() satisfies FakeSupabase + useAuthStore.setState({ + status: 'signed_in', + user: fakeUser(), + profile: fakeProfile(), + avatar: null, + avatarUrl: null, + }) +}) +afterEach(cleanup) + +describe('SidebarNav entries', () => { + it('hides both V1-2 entries from an account without a right', () => { + mount([]) + expect(within(sidebar()).queryByRole('link', { name: fr['shell.nav.anatomy'] })).toBeNull() + expect(within(sidebar()).queryByRole('link', { name: fr['shell.nav.admin'] })).toBeNull() + expect(within(sidebar()).queryByRole('separator')).toBeNull() + }) + + it('shows « Fiches anatomiques » to a catalogue reader, without the administration', () => { + mount([grant('catalog_reader')]) + expect(within(sidebar()).getByRole('link', { name: fr['shell.nav.anatomy'] })).toHaveAttribute( + 'href', + '/app/anatomy', + ) + expect(within(sidebar()).queryByRole('link', { name: fr['shell.nav.admin'] })).toBeNull() + }) + + it('shows both to a capability holder, « Administration » set apart before « Mon compte »', () => { + mount([grant('sheet_reviewer')]) + const links = within(sidebar()).getAllByRole('link').map((link) => link.textContent) + expect(links).toEqual([ + fr['shell.nav.dashboard'], + fr['shell.nav.clients'], + fr['shell.nav.animals'], + fr['shell.nav.anatomy'], + fr['shell.nav.admin'], + fr['shell.nav.account'], + fr['shell.nav.local_tool'] + fr['shell.nav.local_tool_hint'], + ]) + expect(within(sidebar()).getByRole('link', { name: fr['shell.nav.admin'] })).toHaveAttribute( + 'href', + '/app/admin', + ) + expect(within(sidebar()).getAllByRole('separator')).toHaveLength(2) + }) + + it('shows « Administration » to the owner role without a grant', () => { + mount([], ['owner']) + expect(within(sidebar()).getByRole('link', { name: fr['shell.nav.admin'] })).toBeInTheDocument() + expect(within(sidebar()).queryByRole('link', { name: fr['shell.nav.anatomy'] })).toBeNull() + }) + + it('carries the same entries into the mobile drawer', async () => { + const user = userEvent.setup() + mount([grant('sheet_editor')]) + await user.click(screen.getByRole('button', { name: fr['shell.open_menu'] })) + const drawer = await screen.findByRole('dialog', { name: fr['shell.nav_label'] }) + expect(within(drawer).getByRole('link', { name: fr['shell.nav.anatomy'] })).toBeInTheDocument() + expect(within(drawer).getByRole('link', { name: fr['shell.nav.admin'] })).toBeInTheDocument() + }) +}) diff --git a/apps/app/tests/unit/state.authStore.test.ts b/apps/app/tests/unit/state.authStore.test.ts index 7a9bec6e..5073fac0 100644 --- a/apps/app/tests/unit/state.authStore.test.ts +++ b/apps/app/tests/unit/state.authStore.test.ts @@ -28,6 +28,7 @@ const INITIAL = { avatar: null, avatarUrl: null, workspace: { status: 'idle' as const }, + catalogGrants: [], } let fake: FakeSupabase @@ -94,6 +95,24 @@ describe('authStore', () => { expect(useAuthStore.getState().urlFailure).toBe('link_expired') }) + it('loads the own grant rows for the navigation hint and drops them on a change of account', async () => { + const grant = { user_id: 'user-1', kind: 'catalog_reader', expires_at: null, revoked_at: null } + fake.tables.anatomical_catalog_grants = [grant] + fake.tables.profiles = [fakeProfile(), fakeProfile({ id: 'user-2' })] + stop = useAuthStore.getState().start() + fake.emit('SIGNED_IN', fakeSession()) + await flush() + await flush() + expect(useAuthStore.getState().catalogGrants).toEqual([grant]) + fake.emit('SIGNED_IN', fakeSession(fakeUser({ id: 'user-2' }))) + expect(useAuthStore.getState().catalogGrants).toEqual([]) + await flush() + await flush() + expect(useAuthStore.getState().catalogGrants).toEqual([]) + fake.emit('SIGNED_OUT', null) + expect(useAuthStore.getState().catalogGrants).toEqual([]) + }) + it('updateProfile writes the row and keeps the store in sync', async () => { stop = useAuthStore.getState().start() fake.emit('SIGNED_IN', fakeSession()) diff --git a/packages/supabase/src/auth.ts b/packages/supabase/src/auth.ts index 84b1bab9..4deec185 100644 --- a/packages/supabase/src/auth.ts +++ b/packages/supabase/src/auth.ts @@ -19,6 +19,7 @@ export type AuthFailureKind = | 'link_expired' | 'session_expired' | 'reauthentication_needed' + | 'aal2_required' | 'provider_disabled' | 'network' | 'unknown' @@ -52,6 +53,8 @@ const CODE_TO_KIND: Record = { refresh_token_not_found: 'session_expired', reauthentication_needed: 'reauthentication_needed', reauthentication_not_valid: 'reauthentication_needed', + // A password change with a verified factor needs an aal2 session (IDENTITY.md §4.1). + insufficient_aal: 'aal2_required', provider_disabled: 'provider_disabled', oauth_provider_not_supported: 'provider_disabled', email_provider_disabled: 'provider_disabled', diff --git a/packages/supabase/tests/auth.test.ts b/packages/supabase/tests/auth.test.ts index 3ef648e1..4dbbe57e 100644 --- a/packages/supabase/tests/auth.test.ts +++ b/packages/supabase/tests/auth.test.ts @@ -14,6 +14,7 @@ describe('classifyAuthError', () => { expect(classifyAuthError(err({ code: 'weak_password', status: 422 }))).toBe('weak_password') expect(classifyAuthError(err({ code: 'otp_expired', status: 403 }))).toBe('link_expired') expect(classifyAuthError(err({ code: 'bad_code_verifier', status: 400 }))).toBe('link_expired') + expect(classifyAuthError(err({ code: 'insufficient_aal', status: 401 }))).toBe('aal2_required') }) it('falls back on the HTTP status, then network, then unknown', () => {