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,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())