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:
1 parent
99488d71d9
commit
4744e28986
38 files changed
+1818
-55
No files matched your search
@@ -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>
|
||||
|
||||
@@ -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">
|
||||
|
||||
@@ -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'),
|
||||
}
|
||||
}
|
||||
@@ -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)}`)
|
||||
}
|
||||
@@ -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 }
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
}
|
||||
@@ -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>
|
||||
)
|
||||
|
||||
@@ -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
@@ -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
@@ -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.',
|
||||
}
|
||||
@@ -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()
|
||||
|
||||
Reference in new issue
Block a user