feat(app): admin and catalogue entries, step-up guard, MFA in Mon compte (V1-2.5 E, F)

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.
This commit is contained in:
bchanot committed 2026-11-02 16:49:37 +01:00
1 parent 99488d71d9
commit 4744e28986
38 files changed
+1818 -55

No files matched your search

@@ -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.
+23
View File
@@ -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() {
<Route path=":animalId/edit" element={<AnimalEditRoute />} />
</Route>
</Route>
{/* V1-2 (§11.1): the server decides every read; these gates never use the nav hint. */}
<Route path="anatomy" element={<RequireCatalog />}>
<Route index element={<CatalogRoute />} />
</Route>
<Route path="admin" element={<RequireAdmin />}>
<Route index element={<AdminHomeRoute />} />
<Route path="sheets">
<Route index element={<AdminSheetsRoute />} />
<Route path="new" element={<AdminSheetCreateRoute />} />
<Route path=":sheetId" element={<AdminSheetRoute />} />
</Route>
<Route path="species" element={<AdminSpeciesRoute />} />
<Route path="access" element={<AdminAccessRoute />} />
</Route>
<Route path="*" element={<NotFoundRoute />} />
</Route>
</Route>
+108
View File
@@ -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 (
<Card as="section" className="space-y-3 p-5 sm:p-6">
<h1 ref={heading} tabIndex={-1} className="outline-none font-serif text-2xl text-[var(--color-ink)]">
{t('admin.step_up.title')}
</h1>
{children}
</Card>
)
}
/**
* 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<Gate>({ 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 <Outlet />
if (gate.status === 'checking') {
return (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('shell.loading_session')}
</p>
)
}
if (gate.status === 'challenge') {
return (
<StepUpCard>
<p className="text-sm text-[var(--color-ink-muted)]">{t('admin.step_up.body')}</p>
<TotpCodeForm factors={gate.factors} onVerified={check} />
</StepUpCard>
)
}
if (gate.status === 'no_factor') {
return (
<StepUpCard>
<Notice tone="info">{t('admin.step_up.no_factor')}</Notice>
<Link
to="/app/account#security-title"
className="inline-flex min-h-11 items-center text-sm font-medium text-[var(--color-accent-strong)] underline underline-offset-2"
>
{t('admin.step_up.to_security')}
</Link>
</StepUpCard>
)
}
return (
<div className="space-y-3">
<Notice tone="error">{describe(gate.error)}</Notice>
<Button type="button" variant="secondary" onClick={check}>
{t('common.retry')}
</Button>
</div>
)
}
@@ -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 <Outlet />
}
@@ -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 <PlaceholderPage titleKey="admin.access.title" />
}
@@ -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 <PlaceholderPage titleKey="shell.nav.admin" />
}
@@ -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 <PlaceholderPage titleKey="admin.sheets.new" />
}
@@ -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 <PlaceholderPage titleKey="admin.sheets.title" />
}
@@ -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 <PlaceholderPage titleKey="admin.sheets.title" />
}
@@ -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 <PlaceholderPage titleKey="admin.species.title" />
}
@@ -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 <PlaceholderPage titleKey="shell.nav.anatomy" />
}
@@ -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<FieldErrors<Values>>({})
const [failure, setFailure] = useState<string | null>(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<boolean> {
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 <SessionLoading />
if (status !== 'signed_in') return <NoSession />
if (stepUp.challenge) {
return (
<AuthLayout title={t('auth.reset.title')} subtitle={t('auth.reset.subtitle')}>
<InlineStepUp challenge={stepUp.challenge} />
</AuthLayout>
)
}
return (
<AuthLayout title={t('auth.reset.title')} subtitle={t('auth.reset.subtitle')}>
<form onSubmit={submit} noValidate className="space-y-4">
+39
View File
@@ -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<OwnCatalogGrant['kind']> = 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'),
}
}
+24
View File
@@ -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<TotpFactor[]> {
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<TotpFactor[] | null> {
const level = await assuranceLevel(client)
if (level.current === 'aal2') return null
return verifiedFactors(client)
}
@@ -0,0 +1,8 @@
import { classifyMfaError } from '@faunosteo/supabase'
import { useT } from '@/i18n/useT'
/** One sentence per MFA failure kind (`mfa.failure.<kind>`); GoTrue's own message never shows. */
export function useMfaFailureMessage(): (error: unknown) => string {
const t = useT()
return (error) => t(`mfa.failure.${classifyMfaError(error)}`)
}
+59
View File
@@ -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<PendingStepUp | null>(null)
async function open(resume: () => void): Promise<boolean> {
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 }
}
+19
View File
@@ -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<T> = Partial<Record<keyof T & string, string>>
/** First issue per field, as an i18n key. */
@@ -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<FieldErrors<{ name: string }>>({})
const [failure, setFailure] = useState<string | null>(null)
const [busy, setBusy] = useState(false)
const [enrolment, setEnrolment] = useState<TotpEnrolment | null>(null)
const unverifiedId = useRef<string | null>(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 (
<div className="space-y-4 rounded-lg border border-[var(--color-border)] p-4">
<p className="text-sm text-[var(--color-ink)]">{t('mfa.enrol.scan')}</p>
{/* A data: URI built by supabase-js, shown as an image: no markup enters the page. */}
<img
src={enrolment.qrCode}
alt={t('mfa.enrol.qr_alt')}
width={192}
height={192}
className="h-48 w-48 rounded-lg border border-[var(--color-border)] bg-white p-2"
/>
<div className="space-y-1">
<p className="text-sm font-medium text-[var(--color-ink)]">{t('mfa.enrol.secret_label')}</p>
<p className="text-xs text-[var(--color-ink-muted)]">{t('mfa.enrol.secret_hint')}</p>
<code className="block break-all rounded-md bg-[var(--color-surface-strong)] px-3 py-2 font-mono text-sm text-[var(--color-ink)]">
{enrolment.secret}
</code>
</div>
<TotpCodeForm
factors={[{ id: enrolment.factorId, friendlyName: name.trim() }]}
onVerified={verified}
onCancel={() => void cancel()}
/>
</div>
)
}
return (
<div className="space-y-4 rounded-lg border border-[var(--color-border)] p-4">
{stepUp.challenge ? (
<InlineStepUp challenge={stepUp.challenge} />
) : (
<form onSubmit={submitName} noValidate className="space-y-4">
<FormField
id="factor-name"
label={t('mfa.enrol.name')}
hint={t('mfa.enrol.name_hint')}
error={errors.name && t(errors.name).replace('{max}', String(FACTOR_NAME_MAX_LENGTH))}
>
<Input
id="factor-name"
value={name}
onChange={(e) => setName(e.target.value)}
autoComplete="off"
aria-invalid={Boolean(errors.name)}
aria-describedby={fieldDescribedBy('factor-name', 'hint', errors.name)}
/>
</FormField>
{failure && <Notice tone="error">{failure}</Notice>}
<div className="flex flex-wrap gap-2">
<Button type="submit" disabled={busy}>
{busy ? t('mfa.enrol.creating') : t('mfa.enrol.continue')}
</Button>
<Button type="button" variant="ghost" onClick={onClose} disabled={busy}>
{t('common.cancel')}
</Button>
</div>
</form>
)}
</div>
)
}
@@ -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<ListState>({ 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 (
<li className="flex flex-wrap items-center justify-between gap-3 py-3">
<div className="min-w-0 space-y-1">
<p className="flex flex-wrap items-center gap-2 text-sm font-medium text-[var(--color-ink)]">
<span className="break-words">{factorLabel(factor, t('mfa.factor.unnamed'))}</span>
<Badge tone={verified ? 'accent' : 'warn'}>
{t(verified ? 'mfa.factor.verified' : 'mfa.factor.unverified')}
</Badge>
</p>
<p className="text-xs text-[var(--color-ink-muted)]">
{t('mfa.factor.added_on').replace(
'{date}',
new Date(factor.createdAt).toLocaleDateString(locale),
)}
</p>
</div>
<Button type="button" variant="secondary" onClick={onRemove}>
{t('mfa.factor.remove')}
</Button>
</li>
)
}
/**
* 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<TotpFactor | null>(null)
const [removing, setRemoving] = useState(false)
const [failure, setFailure] = useState<string | null>(null)
const [notice, setNotice] = useState<string | null>(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 (
<div className="space-y-3">
<div>
<p className="text-sm font-medium text-[var(--color-ink)]">
{t('account.security.mfa_title')}
</p>
<p className="text-sm text-[var(--color-ink-muted)]">{t('mfa.description')}</p>
</div>
{state.status === 'loading' && (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('mfa.factor.loading')}
</p>
)}
{state.status === 'error' && (
<div className="space-y-2">
<Notice tone="error">{describe(state.error)}</Notice>
<Button type="button" variant="secondary" onClick={refresh}>
{t('common.retry')}
</Button>
</div>
)}
{state.status === 'ready' && factors.length === 0 && (
<p className="text-sm text-[var(--color-ink-muted)]">{t('mfa.factor.none')}</p>
)}
{factors.length > 0 && (
<ul aria-label={t('mfa.factor.list_label')} className="divide-y divide-[var(--color-border)]">
{factors.map((factor) => (
<FactorRow key={factor.id} factor={factor} onRemove={() => setToRemove(factor)} />
))}
</ul>
)}
{stepUp.challenge && <InlineStepUp challenge={stepUp.challenge} />}
{failure && <Notice tone="error">{failure}</Notice>}
{notice && <Notice tone="success">{notice}</Notice>}
{enrolling ? (
<EnrolTotp onDone={enrolled} onClose={closeEnrolment} />
) : (
<Button
type="button"
variant="secondary"
onClick={() => {
setNotice(null)
setFailure(null)
setEnrolling(true)
}}
>
{t('mfa.enrol.start')}
</Button>
)}
<Dialog
open={toRemove !== null}
onClose={() => setToRemove(null)}
title={t('mfa.remove.title')}
description={
<p className="text-sm text-[var(--color-ink-muted)]">
{t('mfa.remove.body').replace(
'{name}',
toRemove ? factorLabel(toRemove, t('mfa.factor.unnamed')) : '',
)}
</p>
}
size="sm"
>
<div className="mt-4 flex justify-end gap-2">
<Button type="button" variant="ghost" onClick={() => setToRemove(null)} disabled={removing}>
{t('common.cancel')}
</Button>
<Button
type="button"
variant="danger"
onClick={() => toRemove && void remove(toRemove)}
disabled={removing}
>
{t('mfa.remove.confirm')}
</Button>
</div>
</Dialog>
</div>
)
}
@@ -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<FieldErrors<Values>>({})
const [failure, setFailure] = useState<string | null>(null)
const [state, setState] = useState<State>('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 <InlineStepUp challenge={stepUp.challenge} />
return (
<form onSubmit={submit} noValidate className="space-y-4">
<FormField
@@ -113,14 +125,7 @@ export default function SecurityPanel() {
<p className="text-sm text-[var(--color-ink-muted)]">{email}</p>
</div>
<ChangePasswordForm />
<div className="rounded-lg border border-dashed border-[var(--color-border)] p-4">
<p className="text-sm font-medium text-[var(--color-ink)]">
{t('account.security.mfa_title')}
</p>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('account.security.mfa_note')}
</p>
</div>
<MfaFactors />
<div className="space-y-2 border-t border-[var(--color-border)] pt-4">
<p className="text-xs text-[var(--color-ink-muted)]">
{t('account.security.sign_out_everywhere_note')}
@@ -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 (
<div className="space-y-3 rounded-lg border border-[var(--color-border)] p-4">
<Notice tone="info">{t('mfa.step_up.required')}</Notice>
<TotpCodeForm {...challenge} />
</div>
)
}
@@ -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<TotpFactor, 'id' | 'friendlyName'>
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<FieldErrors<{ code: string }>>({})
const [failure, setFailure] = useState<string | null>(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 (
<form onSubmit={submit} noValidate className="space-y-4">
{factors.length > 1 && (
<FormField id={`${id}-factor`} label={t('mfa.step_up.factor')}>
<Select
id={`${id}-factor`}
value={factorId}
onChange={(e) => setFactorId(e.target.value)}
>
{factors.map((factor) => (
<option key={factor.id} value={factor.id}>
{factorLabel(factor, t('mfa.factor.unnamed'))}
</option>
))}
</Select>
</FormField>
)}
<FormField
id={codeId}
label={t('mfa.code.label')}
hint={t('mfa.code.hint')}
error={errors.code && t(errors.code)}
>
<Input
id={codeId}
value={code}
onChange={(e) => setCode(e.target.value)}
inputMode="numeric"
autoComplete="one-time-code"
maxLength={7}
aria-invalid={Boolean(errors.code)}
aria-describedby={fieldDescribedBy(codeId, 'hint', errors.code)}
/>
</FormField>
{failure && <Notice tone="error">{failure}</Notice>}
<div className="flex flex-wrap gap-2">
<Button type="submit" disabled={busy}>
{busy ? t('mfa.code.verifying') : t('mfa.code.verify')}
</Button>
{onCancel && (
<Button type="button" variant="ghost" onClick={onCancel} disabled={busy}>
{t('common.cancel')}
</Button>
)}
</div>
</form>
)
}
@@ -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 (
<Card as="section" className="space-y-3 p-5 sm:p-6">
<h1 ref={heading} tabIndex={-1} className="outline-none font-serif text-2xl text-[var(--color-ink)]">
{t('access_denied.title')}
</h1>
<p className="text-sm text-[var(--color-ink-muted)]">{t('access_denied.body')}</p>
<ButtonLink to="/app" variant="secondary">
{t('access_denied.back')}
</ButtonLink>
</Card>
)
}
@@ -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 (
<h1 ref={heading} tabIndex={-1} className="outline-none font-serif text-2xl sm:text-3xl text-[var(--color-ink)]">
{t(titleKey)}
</h1>
)
}
+46 -19
View File
@@ -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 (
<nav aria-label={t('shell.nav_label')} className="space-y-1">
{NAV_ITEMS.map((item) => (
<NavLink
key={item.to}
to={item.to}
end={item.end}
onClick={onNavigate}
className={({ isActive }) => linkClass(isActive)}
>
<Icon name={item.icon} size={20} className="shrink-0" />
<span className="flex min-w-0 flex-col leading-tight">
<span className="truncate">{t(item.labelKey)}</span>
{item.hintKey && (
<span className="truncate text-xs font-normal text-[var(--color-ink-muted)]">
{t(item.hintKey)}
</span>
)}
</span>
</NavLink>
{items.map((item) => (
<Fragment key={item.to}>
{item.separated && <hr className="my-3 border-[var(--color-border)]" />}
<NavLink
to={item.to}
end={item.end}
onClick={onNavigate}
className={({ isActive }) => linkClass(isActive)}
>
<Icon name={item.icon} size={20} className="shrink-0" />
<span className="flex min-w-0 flex-col leading-tight">
<span className="truncate">{t(item.labelKey)}</span>
{item.hintKey && (
<span className="truncate text-xs font-normal text-[var(--color-ink-muted)]">
{t(item.hintKey)}
</span>
)}
</span>
</NavLink>
{item.separated && <hr className="my-3 border-[var(--color-border)]" />}
</Fragment>
))}
</nav>
)
+4
View File
@@ -7,6 +7,8 @@ export type IconName =
| 'user'
| 'users'
| 'paw'
| 'book'
| 'shield'
| 'tool'
| 'logout'
| 'eye'
@@ -24,6 +26,8 @@ const PATHS: Record<IconName, string> = {
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',
+58 -2
View File
@@ -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.',
}
+58 -2
View File
@@ -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.',
}
+13
View File
@@ -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<void>
@@ -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<AuthState> {
avatar: null,
avatarUrl: null,
workspace: { status: 'idle' },
catalogGrants: [],
}
}
@@ -223,6 +235,7 @@ export const useAuthStore = create<AuthState>((set, get) => ({
avatar: null,
avatarUrl: null,
workspace: { status: 'idle' },
catalogGrants: [],
start: () => {
const client = getSupabaseClient()
+44
View File
@@ -160,9 +160,43 @@ export interface FakeSupabase {
updateUser: ReturnType<typeof vi.fn>
resetPasswordForEmail: ReturnType<typeof vi.fn>
signInWithOAuth: ReturnType<typeof vi.fn>
mfa: {
listFactors: ReturnType<typeof vi.fn>
enroll: ReturnType<typeof vi.fn>
challengeAndVerify: ReturnType<typeof vi.fn>
unenroll: ReturnType<typeof vi.fn>
getAuthenticatorAssuranceLevel: ReturnType<typeof vi.fn>
}
}
}
/** A GoTrue factor row as `listFactors().all` returns it. */
export function fakeFactor(patch: Record<string, unknown> = {}) {
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<Record<string, unknown>>,
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<string, Row[]> = { 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,
@@ -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(
<MemoryRouter>
<SecurityPanel />
</MemoryRouter>,
)
}
function factorList() {
return screen.getByRole('list', { name: fr['mfa.factor.list_label'] })
}
async function startEnrolment(user: ReturnType<typeof userEvent.setup>, 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' })
})
})
@@ -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 <p>admin page</p>
}
function mount(path = '/app/admin') {
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
<Route path="/login" element={<p>login page</p>} />
<Route path="/app" element={<RequireAuth />}>
<Route index element={<p>dashboard page</p>} />
<Route path="account" element={<p>account page</p>} />
<Route path="admin" element={<RequireAdmin />}>
<Route index element={<AdminPage />} />
</Route>
<Route path="anatomy" element={<RequireCatalog />}>
<Route index element={<AccessDenied />} />
</Route>
</Route>
</Routes>
</MemoryRouter>,
)
}
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')
})
})
@@ -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 () => {
@@ -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(
<MemoryRouter initialEntries={['/reset-password']}>
<Routes>
<Route path="/reset-password" element={<ResetPasswordRoute />} />
<Route path="/app" element={<p>dashboard page</p>} />
</Routes>
</MemoryRouter>,
)
}
async function submitPassword(user: ReturnType<typeof userEvent.setup>) {
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()
})
})
@@ -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> = {}): 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(
<MemoryRouter initialEntries={['/app']}>
<Routes>
<Route path="/app" element={<AppLayout />}>
<Route index element={<p>dashboard page</p>} />
</Route>
</Routes>
</MemoryRouter>,
)
}
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()
})
})
@@ -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())
+3
View File
@@ -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<string, AuthFailureKind> = {
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',
+1
View File
@@ -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', () => {