fix(app): unreadable permissions show a retry, never the form (V1-2.5 L1)

Owner checkpoint 2026-11-02: creation page checks loading, server refusal, failed read, then the editor rule; Administration home shows the same notice. reloadAccess re-reads roles and grants without wiping held state; refreshAccount (no caller) removed. Zone panel live region always mounted. Unit and e2e for reviewer-only and editor.
This commit is contained in:
bchanot committed 2026-11-02 21:21:59 +01:00
1 parent 14ff890761
commit 4111efa1d1
15 files changed
+856 -56

No files matched your search

+5
View File
@@ -666,6 +666,11 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet
- [x] I catalogue list, sheet page, version page (C8); deprecated fingerprint fixed in M7 (BDR-098); app 650 (0176b31)
- [x] J e2e:shell A0 A1 S1 P1 + access + MFA + axe + viewports (C11): full suite 108 passed, 6 skipped by design
- [x] K docs, check:all, fresh verifier + security, memory, checkpoint (C10-C12): security PASS (MEDIUM + LOW fixed), verifier ECARTS(7) → three delta rounds → CONFORME on e39f69e; check:all green; e2e:shell 108 + 6 skipped on cea0f1c; phone flake root-caused
- [ ] L owner checkpoint corrections (brief « V1-2.5 : décisions propriétaire au checkpoint », 2026-11-02, on 14ff890; contract `.claude/tasks/contracts/2026-11-02-v1-2-5-owner-checkpoint-2041.md`, plan `.claude/tasks/plans/2026-11-02-v1-2-5-owner-checkpoint-2041.md`): sandbox only, no DEV, no merge, no V1-2.6
- [x] L1 three permission states (creation page + Administration home), reloadAccess, unit + e2e: app 671, e2e:shell 110 + 8 skipped, pgTAP 1941 (fresh sandbox)
- [ ] L2 expiry end of day Europe/Paris, species order 0..9 999 in M7, labels, TOTP key test
- [ ] L3 TOTP reuse measured, lost-authenticator review, decisions in docs
- [ ] L4 gates (check:all, sandbox test-db fresh + upgrade, test, e2e:shell), fresh verifier + security, memory, checkpoint with V1-2.6 scope
- [ ] V1-2.5 catalogue, admin space, rights, species, MFA · V1-2.6 editor level 1 · V1-2.7 preview, review, publication UI · V1-2.8 equine working copy and review preparation · V1-2.9 FR/EN acceptance and closure (owner checkpoints V1-2.3, V1-2.4, V1-2.6, V1-2.7, V1-2.8, V1-2.9 + each DEV operation of contract §16.11)
## Release readiness track (owner 2026-10-25, distinct from the functional roadmap; nothing here authorises a release or exposure)
@@ -0,0 +1,215 @@
# CONTRACT — v1-2-5-owner-checkpoint
- date: 2026-11-02 | flow: feat | branch: feature/v1-2-anatomical-sheets
- status: active
- worktree: /tmp/claude-1000/-home-bchanot-Documents-faunosteo/e641af9a-743e-46d0-9804-99667836040e/scratchpad/v1-2
(every command runs from this worktree; never from /home/bchanot/Documents/faunosteo, never against DEV)
## REQUEST (verbatim — IMMUTABLE)
# FAUNOSTEO — V1-2.5 : décisions propriétaire au checkpoint
J'ai examiné ton rapport au HEAD `14ff890`.
Les résultats techniques de V1-2.5 sont acceptés : pgTAP, tests unitaires, E2E, MFA GoTrue, check:all et revues indépendantes.
Je valide les choix suivants et demande de traiter les dernières corrections ciblées avant de déclarer l'étape définitivement VERIFIED.
## 1. Autorisations indisponibles
Je ne souhaite pas afficher un formulaire de création pleinement utilisable lorsque la lecture des permissions échoue.
Afficher plutôt :
- « Impossible de vérifier vos autorisations ».
- Une explication courte.
- Un bouton « Réessayer ».
Ne pas déduire une absence de droit d'une erreur technique.
Distinguer explicitement trois situations :
1. Utilisateur autorisé : formulaire disponible.
2. Utilisateur non autorisé : accès refusé.
3. Vérification indisponible : état temporaire avec nouvelle tentative.
Les contrôles serveur/RLS demeurent obligatoires.
Ajouter des tests pour ces trois cas, notamment pour un compte reviewer-only et un compte editor.
## 2. Différences graphiques acceptées
J'accepte :
- La sélection affichée dans le panneau plutôt que dans une étiquette au-dessus du dessin, à condition qu'elle reste identifiable et accessible.
- Une carte « Références » non repliable sur mobile, sous réserve qu'elle ne masque pas la zone anatomique.
Consigner ces deux écarts comme décisions UX acceptées, sans modifier les maquettes historiques.
Ne pas entreprendre de refonte graphique.
## 3. Choix complémentaires ratifiés
- Nom de facteur MFA : 64 caractères maximum.
- Clé TOTP : absence de bouton Copier acceptée, mais affichage lisible et sélectionnable pendant la configuration.
- Habilitations : validité jusqu'à la fin du jour sélectionné, selon Europe/Paris pour le périmètre français initial. Vérifier l'interprétation backend, notamment aux changements d'heure, sans modifier les données historiques.
- Ordre des espèces : entier entre 0 et 9 999, validé côté serveur.
- Terminologie : « relecteur ou relectrice ».
## 4. Libellés
Ratifier :
- L14 : « Access and permissions » dans l'interface ; `capability` reste technique.
- L15 : supprimer la seconde phrase redondante si la restriction de largeur est déjà explicite.
- `object_conflict` (EN) : « The illustration file's contents do not match its recorded SHA-256 hash. »
Ne pas déclarer les quelque 350 nouveaux libellés approuvés. Ils feront l'objet d'une revue distincte du propriétaire.
Conserver les formulations ratifiées de V1-2.4.
## 5. MFA et récupération de compte
Consigner le comportement observé de GoTrue concernant la réutilisation des codes TOTP dans une fenêtre de validité.
Examiner et documenter le parcours lorsqu'un utilisateur perd son authentificateur :
- Facteur secondaire éventuel.
- Récupération de compte.
- Intervention administrative autorisée.
- Contrôles d'identité et traces d'audit.
Ne pas créer de contournement de MFA ni affaiblir les protections AAL2.
Si un parcours de récupération sûr manque, le signaler explicitement comme prérequis à la mise en production.
## 6. Validation
Effectuer les corrections ciblées et les tests de non-régression.
Vérifier :
- Les trois états d'autorisation.
- Les droits reviewer/editor.
- Les invariants MFA.
- Les accès serveur/RLS.
- Les comportements mobiles concernés.
- Les dates de validité si le code les traite.
Relancer les contrôles pertinents et une revue indépendante du HEAD final.
Commiter et pousser sur `feature/v1-2-anatomical-sheets` uniquement après validation.
Aucune opération sur DEV, aucun worker DEV, aucune migration DEV, aucune fusion et aucun déploiement.
## 7. Checkpoint
Présenter les corrections, résultats des tests, éventuels risques résiduels et HEAD final.
Si tout est conforme, déclarer V1-2.5 VERIFIED.
Ne pas commencer V1-2.6 dans cette intervention. Présenter son périmètre contractuel et ses prérequis au checkpoint suivant, sans inventer de fonctionnalités.
## CLARIFICATIONS
Q: Where does the « verification unavailable » state apply? / A: [gated 2026-11-02] Creation page
(`/app/admin/sheets/new`: full unavailable screen) + Administration home (`/app/admin`: the « Vos habilitations »
line replaced by the same notice with Retry). Sheets and species lists keep their grant-dependent actions hidden
on a failed read (no false statement); no notice there.
Q: Expiry instant / A: delegated — internal: the instant stored is 23:59:59.999 Europe/Paris of the chosen day
(UTC offset of that instant, DST-aware); the backend compares instants (`expires_at > now()`), unchanged;
historical rows untouched; the expiry day is displayed in Europe/Paris.
Q: TOTP key display / A: delegated — no visible change: the key is already rendered as plain selectable text
(`<code>`, monospace, wrapped); a test pins that it stays selectable and complete.
Q: Species order server check / A: delegated — M7 (V1-2.5 migration, sandbox only) redefines `create_species`
and `update_inactive_species` with the 0..9 999 range (null keeps today's meaning), privileges restated; M5 and
earlier migrations untouched (forward-only).
Q: Creation page with failed own grants but a server `rights.*` refusal / A: delegated (plan challenge,
2026-11-02) — the server's refusal wins: « Accès non autorisé » (BDR-094 kept); the unavailable state covers a
failed client read only.
Q: What does Retry re-read? / A: delegated (plan challenge) — roles and own grants (and the creation page's species
list when it failed); a failed Retry never wipes the profile, roles or workspace already held.
## ACCEPTANCE CRITERIA
1. Three permission states on `/app/admin/sheets/new`, checked in this order: own grants `loading` → the
waiting status; the server refused (species read answered a `rights.*` kind) → « Accès non autorisé »
(BDR-094, the server's answer wins); own grants `failed` → the unavailable screen (title « Impossible de
vérifier vos autorisations » / EN proposal, one short explanation, a « Réessayer » button), never the form;
`ready` with an active `sheet_editor` grant → the form; `ready` without it (reviewer-only, publisher-only,
owner without capability) → « Accès non autorisé ». A failed client read never yields « Accès non autorisé »
by itself. Retry re-reads the roles and own grants through the store and the species list when it failed,
shows the waiting status, then lands on the state the new answers give.
2. `/app/admin`: own grants `loading` → the line shows the waiting status, not « aucune »; `failed` → the
line is replaced by the unavailable notice with Retry (section heading, not a second h1); `ready` → today's
line unchanged.
3. Store: a retry action (`reloadAccess`) sets `catalogGrantsStatus` to `loading`, re-reads the platform roles
and own grants, ends `ready` (roles and grants replaced) or `failed` (grants `[]`; profile, roles and
workspace already held are kept, never wiped by a technical error); it never rejects (no user or client →
`failed`); the account-change guard (`setForUser`) drops late answers. The unused `refreshAccount` is
removed (no caller).
4. Unit tests cover criteria 1-3, including a reviewer-only account and an editor account in each of the
three states, Retry recovering to the form (editor) and to « Accès non autorisé » (reviewer-only), Retry
recovering a failed species list, a failed Retry keeping roles/profile/workspace; the old « leaves a failed
read to the server » test is replaced; `pnpm test:run` is green on each lot.
CHECK: cd /tmp/claude-1000/-home-bchanot-Documents-faunosteo/e641af9a-743e-46d0-9804-99667836040e/scratchpad/v1-2 && pnpm --filter @faunosteo/app exec vitest run tests/unit/routes.admin.test.tsx tests/unit/state.authStore.test.ts tests/unit/lib.dates.test.ts tests/unit/admin.validation.test.ts tests/unit/components.SecurityPanel.test.tsx && echo UNIT-OK
EXPECT: UNIT-OK
EVIDENCE: pending
5. `e2e:shell` (sandbox) proves on desktop: an editor at `aal2` gets the form; a reviewer-only account gets
« Accès non autorisé » on `/app/admin/sheets/new`; with the own-grants request answered 500, the unavailable
screen shows (no form field present), axe clean, and Retry after the request is restored shows the form. At
320 and 375 px (viewport set explicitly) the catalogue sheet page's zone panel holds an `aria-live` region
before any pick, which then names the picked zone, and the « Références » card starts at or below the
drawing's bottom (1 px tolerance).
6. Grant expiry: the form converts the chosen day to 23:59:59.999 Europe/Paris with the offset in force at that
instant; « today » for the past-day check and the date picker's `min` (tomorrow) are Europe/Paris dates;
tests run with `process.env.TZ` set to non-Paris zones (asserted) and cover a winter day, a summer day,
2026-03-29 and 2026-10-25 (DST days); the grant list shows the expiry day in Europe/Paris (tested under a
non-Paris zone). pgTAP proves, through `grant_catalog_right` under two session `TimeZone` values, that the
stored instant for future DST days (2027-03-28, 2027-10-31) is the same, and that `list_catalog_grants`
gives `expired` (now - 1 min), `expiring` (now + 1 min) and `active` (now + 30 days + 1 min) with
`effective` as expected. No historical row is rewritten (no UPDATE, no migration touching existing
`expires_at`).
7. Species order: `create_species` and `update_inactive_species` refuse an order outside 0..9 999 with
`invalid_input`; 0 and 9 999 accepted; null keeps the current default/value; pgTAP covers -1, 10 000, 0,
9 999, null; the redefined RPCs keep `security definer` and `search_path=""` (pgTAP `proconfig`); types
unchanged (`db:types --check`); fresh install and upgrade from M6 (`pnpm db:sandbox up upgrade
20261102100000`) on the sandbox.
8. Labels: FR `admin.grant_kind.sheet_reviewer` = « Relecteur ou relectrice »; contract §3 nomenclature row
aligned; EN `catalogue.failure.drawing_hash_mismatch` = « The illustration file's contents do not match its
recorded SHA-256 hash. »; L14 EN card title stays « Access and permissions »; L15 recorded as the title alone
(no second sentence) for V1-2.6; MFA factor name max 64 (client and its test unchanged or tightened); no
other ratified V1-2.4 wording changed; the label-proposals file says the ~350 new labels are not approved.
9. TOTP enrolment: a test proves the setup key is rendered in full as text in a selectable element (no
`select-none`, no `user-select: none`) while enrolment is open; no Copy button added; the key is still never
stored, logged or sent by the app.
10. MFA docs: `IDENTITY.md` §4.1 records TOTP code reuse within its window as measured by a new asserted case of
`mfa-behaviour.sandbox.ts` (same code verified by a second aal1 session signed in after the first verify and
proven alive before the code is sent, again by the same session, and once more in the following 30 s step;
the measured span quoted);
a new `IDENTITY.md` subsection reviews the lost-authenticator paths (second factor, account recovery,
authorised administrative intervention, identity checks, audit trail), states each gap, and the V1-2 contract
lists the missing safe recovery as an explicit production prerequisite. No MFA bypass, no AAL2 weakening, no
new RPC, screen or service path that resets a factor.
11. Decisions recorded without touching any board image: V1-2 contract §12.3 M7 row and §17.10 row (M7 now
redefines two species RPCs), §13 new bullets (TOTP reuse residual; production prerequisite: rehearsed
lost-factor recovery), §17.11 (this checkpoint: three states and the creation-page order,
two accepted UX deviations with their conditions, ratified choices, labels), `docs/design/README.md`
(accepted deviations), `docs/design/v1-2-4/REVUE.md` label rows (L15, `object_conflict` EN), the V1-2.5
contract clarification on the failed read replaced.
12. Gates on the final code: `pnpm check:all` green; sandbox `test-db` (fresh install and upgrade from M6),
`pnpm db:sandbox test` (MFA suite included), `pnpm e2e:shell` green; nothing reported that did not run;
no DEV operation, no merge, no deploy.
## FILE SCOPE
- apps/app/src/state/authStore.ts
- apps/app/src/components/shell/PermissionsUnavailable.tsx (new)
- apps/app/src/components/shell/AccessDenied.tsx (doc comment only)
- apps/app/src/app/routes/app/admin/AdminSheetCreateRoute.tsx
- apps/app/src/app/routes/app/admin/AdminHomeRoute.tsx
- apps/app/src/lib/dates.ts
- apps/app/src/admin/validation.ts, apps/app/src/admin/labels.ts, apps/app/src/components/admin/{GrantList,GrantPanel}.tsx
- apps/app/src/components/catalogue/ZonePanel.tsx (live region always mounted, nothing visible changes)
- apps/app/src/i18n/fr.ts, apps/app/src/i18n/en.ts
- apps/app/tests/unit/{routes.admin.test.tsx,state.authStore.test.ts,lib.dates.test.ts,components.SecurityPanel.test.tsx},
new apps/app/tests/unit/admin.validation.test.ts
- apps/app/e2e/shell/{admin.spec.ts,catalogue spec}
- supabase/migrations/20261102100000_sheet_admin_reads.sql (M7), supabase/tests/{015_catalog_access,022_sheet_admin_reads}.sql
- packages/supabase/tests/sandbox/mfa-behaviour.sandbox.ts
- docs/development/IDENTITY.md, docs/development/V1-2_ANATOMICAL_SHEETS.md, docs/design/README.md,
docs/design/v1-2-4/REVUE.md, .claude/tasks/contracts/2026-11-02-v1-2-5-admin-catalogue.md,
.claude/audits/2026-11-02-v1-2-5-label-proposals.md
@@ -0,0 +1,209 @@
# Plan: V1-2.5 owner checkpoint corrections (revised after challenge)
Contract `.claude/tasks/contracts/2026-11-02-v1-2-5-owner-checkpoint-2041.md` (criteria 1-12). Branch
`feature/v1-2-anatomical-sheets`, worktree
`/tmp/claude-1000/-home-bchanot-Documents-faunosteo/e641af9a-743e-46d0-9804-99667836040e/scratchpad/v1-2`
(every command runs from there; never the main checkout `/home/bchanot/Documents/faunosteo`, never DEV, no
`pnpm e2e:sheet-assets`, no worker against DEV). Sandbox only (`pnpm db:sandbox …`). Three lots, one fresh
executor each, in order; the orchestrator commits each lot after `pnpm typecheck && pnpm lint && pnpm test:run`
are green (project rule), plus the lot's own checks.
In-force decisions honoured: BDR-094 (« Accès non autorisé » acts on the server's refusal: kept, and on the
creation page the server's `rights.*` answer is checked before the failed client read), BDR-096 (boards never
regenerated), BDR-097 (M7 = V1-2.5's migration, sandbox only), BDR-098 (M7 redefinitions restate privileges),
LRN-112 (GoTrue MFA, aal2 for factor changes: untouched), LRN-110 (sandbox-only runners). Server/RLS checks
unchanged.
## Lot 1 — three permission states (criteria 1-5)
- `apps/app/src/state/authStore.ts`
- delete `refreshAccount` (interface line ~75 and implementation ~263; no caller in src, tests or e2e).
- new action `reloadAccess: () => Promise<void>`, doc « Reads the platform roles and own grants again after a
failed permission read (owner 2026-11-02): pages wait, then show what the answer gives; a technical error
never wipes what the account already holds. Never rejects. »
Body: `const user = get().user; const client = getSupabaseClient()`; if either is missing →
`set({ catalogGrants: [], catalogGrantsStatus: 'failed' })` and return. Else `const setOwn =
setForUser(user, set, get)`; `setOwn({ catalogGrantsStatus: 'loading' })`; `try { const [roles,
catalogGrants] = await Promise.all([fetchOwnPlatformRoles(client, user.id), listOwnCatalogGrants(client,
user.id)]); setOwn({ roles, catalogGrants, catalogGrantsStatus: 'ready' }) } catch { setOwn({ catalogGrants:
[], catalogGrantsStatus: 'failed' }) }`. Profile and workspace untouched. `applyAuthEvent`'s catch unchanged.
- `catalogGrantsStatus` doc: `failed` = the read failed; pages show the unavailable state, never deduce an
absence of right from it.
- `apps/app/src/components/shell/PermissionsUnavailable.tsx` (new, modelled on `AccessDenied.tsx`): props
`{ asPage: boolean; onRetry?: () => void }`. Retry button `onClick={onRetry ?? (() => void
useAuthStore.getState().reloadAccess())}`. `asPage` → `<Card as="section" className="space-y-3 p-5 sm:p-6">`
with `<h1 ref={usePageHeading()} tabIndex={-1}>` (AccessDenied classes); else `<Card as="section"
aria-labelledby="permissions-unavailable-title">` with `<h2 id=…>` (`font-serif text-lg
text-[var(--color-ink)]`). Body `t('permissions_unavailable.body')`, button `<Button type="button"
variant="secondary">{t('common.retry')}</Button>`. Doc comment: owner 2026-11-02, a technical error never reads
as an absence of right; the server still decides.
- `apps/app/src/app/routes/app/admin/AdminSheetCreateRoute.tsx`: checks in this order:
1. `grantsStatus === 'loading'` → existing waiting status;
2. `species.state.status === 'error' && isRightsRefusal(species.state.failure)` → `<AccessDenied />`;
3. `grantsStatus === 'failed'` → `<PermissionsUnavailable asPage onRetry={retry} />` where `retry = () => {
void reloadAccess(); if (species.state.status === 'error') species.refresh() }` (`reloadAccess` read with a
selector);
4. `!editor` → `<AccessDenied />`.
Replace the comment block with the new rule, and state the invariant: every hook stays above the early returns
(form values survive a state switch; do not move form state into a child).
- `apps/app/src/app/routes/app/admin/AdminHomeRoute.tsx`: a wrapper `<div ref={access} tabIndex={-1}
className="outline-none">` under the h1 stays mounted in every state; inside it: `loading` → `<p
role="status" className="text-sm text-[var(--color-ink-muted)]">{t('shell.loading_session')}</p>`; `failed`
→ `<PermissionsUnavailable asPage={false} onRetry={retry} />`; `ready` → today's `permissionsLine` paragraph.
`retry = async () => { await reloadAccess(); access.current?.focus() }` (focus not lost when the button
unmounts). Cards unchanged.
- `apps/app/src/components/shell/AccessDenied.tsx`: doc comment only (shown on the creation page once the own
grants are read and hold no editor capability, or when the server refuses; never for a failed read).
- `apps/app/src/i18n/fr.ts`, `en.ts` next to `access_denied.*`: `permissions_unavailable.title` FR « Impossible
de vérifier vos autorisations » / EN « Unable to verify your permissions »; `permissions_unavailable.body` FR
« La vérification n'a pas abouti, probablement à cause d'un problème de connexion. Cette erreur ne modifie pas
vos droits. » / EN « The check did not complete, probably because of a connection problem. This error does not
change your permissions. ». Retry reuses `common.retry`.
- `apps/app/tests/unit/routes.admin.test.tsx`: in `beforeEach`/`afterEach`, save and restore the store's real
`reloadAccess` (no leak). Replace the test at ~658-665 (« leaves a failed read to the server ») by: for a
reviewer-only grant set and an editor grant set, each in `ready` / `failed` / `loading`: form / « Accès non
autorisé » / unavailable (no `input`, no `select`, no « Accès non autorisé ») / waiting. Retry: setState
`reloadAccess: vi.fn(async () => useAuthStore.setState({ catalogGrants, catalogGrantsStatus: 'ready' }))` →
form for the editor, « Accès non autorisé » for the reviewer-only. Species list failing with a network kind +
grants failed → Retry → species options present (the species accessor mock answers on the second call).
Server rights refusal + grants failed → « Accès non autorisé ». Admin home: `loading` status, `failed` notice +
Retry and no « aucune », `ready` unchanged, focus on the wrapper after Retry.
- `apps/app/tests/unit/state.authStore.test.ts`: `reloadAccess` → `loading` then `ready` (roles + grants
replaced); grants read rejects → `failed`, grants `[]`, roles/profile/workspace unchanged; roles read rejects
→ same; no user → `failed`, resolves; account change during the reload → late answer dropped.
- `apps/app/e2e/shell/admin.spec.ts`: in « access per right » (~603) add `page.goto('/app/admin/sheets/new')`
and the `access_denied.title` heading check for the reviewer. New test « creation page: unreadable permissions
show a retry, never the form » (desktop only, `test.skip(isPhone(info))` with the same comment as A0/A1/S1):
the A1 editor setup at `aal2` → form visible; then `page.route('**/rest/v1/anatomical_catalog_grants*', r =>
r.fulfill({ status: 500, contentType: 'application/json', body: '{}' }))`, reload the page → unavailable
heading, no `#sheet-species-id`, axe clean (the suite's helper); `page.unroute(…)`, click « Réessayer » → form
visible. Respect the suite's allowlist (a fulfilled route answers locally).
- `apps/app/src/components/catalogue/ZonePanel.tsx`: keep one `<div aria-live="polite" className="space-y-2">`
mounted in both branches (selection content, or the existing prompt `<p id="catalogue-zone-title">`); markup and
classes otherwise unchanged, nothing visible changes.
- `apps/app/e2e/shell/catalogue.spec.ts` (P1): for 320 and 375 px, set the viewport explicitly; before any pick
the panel holds `[aria-live="polite"]`; after the pick it contains the zone name; the « Références » card's top
≥ the drawing's bottom − 1 px, once the drawing is visible (reuse the file's box helper).
Lot checks: typecheck, lint, `pnpm test:run`, then on the sandbox (`pnpm db:sandbox up fresh` if not up; `pnpm
db:sandbox test-db` before e2e on one stack) `pnpm e2e:shell`.
## Lot 2 — expiry, species order, labels, TOTP key (criteria 6-9)
- `apps/app/src/lib/dates.ts`: `export const PARIS_TIME_ZONE = 'Europe/Paris'`; private `parisParts(instant:
number)` via `new Intl.DateTimeFormat('en-US', { timeZone: PARIS_TIME_ZONE, year: 'numeric', month:
'numeric', day: 'numeric', hour: 'numeric', minute: 'numeric', second: 'numeric', hourCycle: 'h23'
}).formatToParts(instant)` → numbers; `parisDateIso(date = new Date())` from those parts (YYYY-MM-DD, padded);
`parisTomorrowIso(date = new Date())` = the next calendar day of `parisDateIso(date)` (UTC date arithmetic on
the Y-M-D, never + 86 400 000 ms); `endOfParisDayIso(day: string): string`: validate `^\d{4}-\d{2}-\d{2}$`
and a real date (else throw); `guess = Date.UTC(y, m - 1, d, 23, 59, 59, 999)`; offset = `Date.UTC(parts at
guess, ms 999) - guess` (Paris changes offset at 01:00 UTC, so one pass is exact for 23:59 local); return `new
Date(guess - offset).toISOString()`. No `longOffset`, no `format()` string parsing.
- `apps/app/src/admin/validation.ts`: `parseGrant(values, today = parisDateIso())`; transform uses
`endOfParisDayIso`. Comments « the end of the chosen day, Europe/Paris (owner 2026-11-02) ». The `expires_on`
refine also checks the day is a real calendar date (round-trip through `Date.UTC`), so the transform never
sees `2026-02-30` (refused with `admin.access.error.expiry`; test it).
- `apps/app/src/components/admin/GrantPanel.tsx` ~280: `min={parisTomorrowIso()}`; drop the `localDateIso`
import if unused.
- `apps/app/src/admin/labels.ts`: `formatDay(iso, locale, timeZone?: string)` passes `timeZone` to
`toLocaleDateString` when given. `GrantList.tsx`: expiry `formatDay(grant.expires_at, locale,
PARIS_TIME_ZONE)`; granted date unchanged.
- `apps/app/tests/unit/lib.dates.test.ts`: a `describe` that sets `process.env.TZ = 'America/Los_Angeles'` in
`beforeAll` (and another with `'Pacific/Kiritimati'`), asserts `Intl.DateTimeFormat().resolvedOptions().timeZone`
is that zone, restores in `afterAll`. Cases: `endOfParisDayIso('2026-01-15')` → `2026-01-15T22:59:59.999Z`;
`'2026-07-15'` → `2026-07-15T21:59:59.999Z`; `'2026-03-28'` → `2026-03-28T22:59:59.999Z`; `'2026-03-29'` →
`2026-03-29T21:59:59.999Z`; `'2026-10-25'` → `2026-10-25T22:59:59.999Z`; `'2026-02-30'` and `'2026-1-5'`
throw; `parisDateIso(new Date('2026-11-02T23:30:00Z'))` → `'2026-11-03'`; `parisTomorrowIso(new
Date('2026-03-28T22:30:00Z'))` → `'2026-03-29'` (Paris still 03-28, 23:30 CET) and `parisTomorrowIso(new
Date('2026-03-28T23:30:00Z'))` → `'2026-03-30'` (Paris 03-29 00:30). New
`apps/app/tests/unit/admin.validation.test.ts` (same TZ setup): `parseGrant` → Paris instant; today refused,
tomorrow accepted; move the parseGrant case from `routes.admin.test.tsx` (~552-583) here and delete it there.
A GrantList render with `process.env.TZ = 'Pacific/Kiritimati'` (asserted; a zone east of Paris, where the
device-zone display would say « 1 janvier 2027 ») shows « 31 décembre 2026 » for `2026-12-31T22:59:59.999Z`
in FR — in the new file.
- `routes.admin.test.tsx` ~458: the label lookup « Relecteur, relectrice » → « Relecteur ou relectrice ».
- `supabase/migrations/20261102100000_sheet_admin_reads.sql` (M7): append « Species order range (owner
2026-11-02) »: the full M5 `create or replace function` statements of `public.create_species(id text, name_fr
text, name_en text, sort_order integer default 100)` and `public.update_inactive_species(id text, name_fr text,
name_en text, sort_order integer)` copied with signature, defaults and qualified names unchanged, adding only
`or (create_species.sort_order is not null and create_species.sort_order not between 0 and 9999)` (resp.
`update_inactive_species.sort_order`) to the `invalid_input` condition; then for both `revoke all on function …
from public, anon, service_role; grant execute on function … to authenticated;` (M5's loop). Header: replace
« No write, no grant, no policy and no rule changes here » with what M7 now changes (two species RPCs range
check, privileges restated).
- `supabase/tests/022_sheet_admin_reads.sql`: as an editor at aal2 (the file's helpers): `create_species` with -1
and 10000 → `invalid_input`; 0 and 9999 accepted; `update_inactive_species` -1/10000 refused, 0/9999 accepted,
null keeps the stored order; `prosecdef` true and `proconfig = array['search_path=""']` for both; bump `plan`.
- `supabase/tests/015_catalog_access.sql`: as the owner at aal2 (file helpers), under `set local timezone 'UTC'`
then `'America/New_York'`: `grant_catalog_right(..., expires_at => '2027-03-28T23:59:59.999+02:00')` (and
`'2027-10-31T23:59:59.999+01:00'`) stores `'2027-03-28T21:59:59.999Z'::timestamptz` (resp.
`'2027-10-31T22:59:59.999Z'`) — revoke between grants or use distinct accounts/kinds to avoid `grant.active`;
and via direct inserts with an explicit earlier `granted_at` (pattern at ~179), one fresh confirmed account
per state, kind `catalog_reader` (`effective` is per account and kind): now()-1 min → `expired`, effective
false; now()+1 min → `expiring`, effective true; now()+30 days+1 min → `active`, effective true. Bump `plan`. No
UPDATE of existing rows.
- Labels: `fr.ts` `admin.grant_kind.sheet_reviewer` → « Relecteur ou relectrice » (grep both dicts for other
« relectrice » forms); `en.ts` `catalogue.failure.drawing_hash_mismatch` → « The illustration file's contents do
not match its recorded SHA-256 hash. ».
- `apps/app/tests/unit/components.SecurityPanel.test.tsx` (reuse its fake `mfa.enroll` and `startEnrolment`):
the setup key is the full text of one element with no `select-none` class and no inline `user-select`; no
button named /cop(y|ier)/i; a 65-character name refused without calling GoTrue, 64 accepted.
Lot checks: typecheck, lint, `pnpm test:run` (includes PGlite pgTAP), `pnpm db:sandbox up fresh` + `test-db`,
`pnpm db:sandbox up upgrade 20261102100000` + `test-db`, `pnpm db:sandbox types --check`.
## Lot 3 — MFA reuse measure, recovery review, decisions in docs (criteria 8, 10, 11)
- `packages/supabase/tests/sandbox/mfa-behaviour.sandbox.ts` case « 11. TOTP code reuse »: account with a
verified factor (`withFactor` verifies with the enrolment step's code); wait into a fresh 30 s step N (so C is
not the enrolment code) with ≥ 8 s left; session A (password) takes code C of step N, verifies → aal2.
Then sign in session B (password, after A's verify), assert B is `aal1` and alive (a `getUser` or its
`auth.sessions` row, as the file does elsewhere) before sending C; B challenge + verify with C; assert the
answer is not `session_not_found` and record whether C is accepted. Then A challenges and verifies again with
C. Then wait into step N+1, sign in session D, verify with C once more (skew); then into step N+2, session E,
verify with C (upper bound of the span). Assertions pin the
observed outcome (first run measures; then the assertions are written to it and the suite re-run). No secret or
code printed on failure.
- `docs/development/IDENTITY.md` §4.1: replace « observed, not asserted » with the asserted outcome, the measured
span (one step or two with skew) and its consequence, citing the configuration that ran the measurement (the sandbox GoTrue environment in
`scripts/db-sandbox.sh`, image defaults plus its overrides) and, separately, `supabase/config.toml` `[auth.mfa]`
for the CLI/DEV stacks, before any claim about mitigations. New §4.2 « Lost authenticator: paths and gaps »: second factor
(enrol from `aal2`, recommended for every capability holder, two on independent devices for the owner, V1-2
§5.6); self-service recovery (none: no recovery codes; password reset and factor removal need `aal2`; an
ordinary account keeps `aal1` use, a capability holder loses administration); authorised administrative
intervention (operator procedure of V1-2 §5.6 and §5.7.7, server access, never an app path, no RPC or screen);
identity checks (out of band, owner present, reason recorded) and audit (`auth.mfa_factor_reset` row written by
the operator in the same session, GoTrue audit log); gaps: not rehearsed (V1-2.9), audit row depends on the
operator, single-owner platform has no second person, no recovery codes → « Production prerequisite: a recovery
runbook rehearsed on the sandbox and written here before any production use of MFA-protected rights. » No new
path, no weakening of `aal2`.
- `docs/development/V1-2_ANATOMICAL_SHEETS.md`: §3 nomenclature « Relecteur ou relectrice »; §12.3 M7 row and
§17.10 row: M7 also redefines `create_species` / `update_inactive_species` (order 0..9 999) with privileges
restated; §13: new bullets « TOTP code reuse within its window (measured, IDENTITY §4.1): residual » and
« Production prerequisite: the lost-factor recovery rehearsed and written (§5.7.7, IDENTITY §4.2) »; new §17.11
« V1-2.5 checkpoint decisions (owner, 2026-11-02) »: three permission states (creation page order: loading,
server refusal, failed read, editor or not; Administration home notice; lists keep actions hidden), accepted UX
deviations (selection in the zone panel with an always-mounted live region; « Références » card not collapsible
on mobile, below the drawing, measured at 320/375 px), MFA factor name 64, TOTP key without Copy (readable,
selectable), expiry end of day Europe/Paris (23:59:59.999, picker and display in Paris, backend compares
instants, historical rows untouched), species order 0..9 999 server-side (M7), « relecteur ou relectrice », L14,
L15 title alone, `object_conflict` EN, ~350 new labels not approved (separate owner review).
- `docs/design/README.md`: « Accepted deviations (owner 2026-11-02, V1-2.5) » with the two items and conditions;
boards unchanged.
- `docs/design/v1-2-4/REVUE.md`: L15 second-sentence row → decided (removed, title alone); `object_conflict` EN
row → ratified wording. No image touched.
- `.claude/tasks/contracts/2026-11-02-v1-2-5-admin-catalogue.md`: the C4 clarification sentence (« when their read
failed … shows the form and the server decides … Submitted for the owner's acknowledgement ») → the owner's
decision (unavailable state with Retry; server refusal first; owner 2026-11-02).
- `.claude/audits/2026-11-02-v1-2-5-label-proposals.md`: header: L14, L15, `object_conflict` EN, « relecteur ou
relectrice » ratified 2026-11-02; every other new label stays a proposal for a separate owner review; ~31 expiry
line → end of the chosen day Europe/Paris, species order → 0..9 999 checked in SQL; ~74 « Relecteur, relectrice »
→ « Relecteur ou relectrice »; add `permissions_unavailable.*` as proposals (FR title = owner wording).
Lot checks: `pnpm db:sandbox test` (MFA suite and the others) twice green after the assertions are pinned.
## After the lots (orchestrator)
GATE 0 `gates.sh`, fresh verifier, fresh security audit on the whole diff; `pnpm check:all`; `pnpm e2e:shell` on
the final code; commit + push per lot; memory (BDR for the checkpoint decisions, journal), TODO; V1-2.6 scope from
V1-2 contract §16.7 and §8.2 for the checkpoint report.
+40
View File
@@ -408,6 +408,43 @@ for (const [locale, dict] of LANGUAGES) {
).toBe('1')
})
test('creation page: unreadable permissions show a retry, never the form', async ({
page,
requests,
}, info) => {
test.skip(
isPhone(info),
'desktop journey (the admin screens at 375 px are covered below)',
)
const { account, secret } = await staff(locale, 'admin', ['sheet_editor'])
requests.forbid(account.email, account.password, account.displayName)
await openAdmin(page, dict, info, account, secret)
await page.goto('/app/admin/sheets/new')
await expect(heading(page, dict['admin.sheets.new'])).toBeVisible()
await expect(page.locator('#sheet-species-id')).toBeVisible()
// The own-grants read fails: the unavailable screen, no field.
const grants = '**/rest/v1/anatomical_catalog_grants*'
await page.route(grants, (route) =>
route.fulfill({
status: 500,
contentType: 'application/json',
body: '{}',
}),
)
await page.reload()
await expect(
heading(page, dict['permissions_unavailable.title']),
).toBeVisible()
await expect(page.locator('#sheet-species-id')).toHaveCount(0)
await expectAccessible(page, 'the unavailable permissions screen')
// Restored: Retry reads again and the form comes back.
await page.unroute(grants)
await page.getByRole('button', { name: dict['common.retry'] }).click()
await expect(page.locator('#sheet-species-id')).toBeVisible()
})
test('A1: an editor at aal2 creates a sheet on a new inactive species; it opens on draft v1', async ({
page,
requests,
@@ -641,6 +678,9 @@ for (const [locale, dict] of LANGUAGES) {
// The rights screen by its address: refused by the server.
await page.goto('/app/admin/access')
await expect(heading(page, dict['access_denied.title'])).toBeVisible()
// The creation page: no form for a reviewer-only account.
await page.goto('/app/admin/sheets/new')
await expect(heading(page, dict['access_denied.title'])).toBeVisible()
await signOut(page, dict, info)
const admin = await staff(locale, 'admin', [])
+34
View File
@@ -195,6 +195,40 @@ for (const [locale, dict] of LANGUAGES) {
await expectNoHorizontalOverflow(page, `the sheet page at ${width} px`)
}
// Narrow screens (viewport set here, whatever the project): the zone
// panel keeps its live region from the first render, and the references
// card never covers the drawing.
const original = page.viewportSize()!
for (const width of [320, 375]) {
await page.setViewportSize({ width, height: 667 })
await openSheet(page, `/app/anatomy/${listed.id}`, name(listed))
const panel = page.locator('[aria-live="polite"]', {
has: page.locator('#catalogue-zone-title'),
})
await expect(panel, `live region before a pick at ${width} px`).toHaveCount(1)
const chooser = page.getByRole('combobox', {
name: dict['catalogue.zone.choose'],
})
const first = await chooser.locator('option').nth(1).getAttribute('value')
await chooser.selectOption(first!)
const zoneName = (await chooser.locator('option:checked').textContent()) ?? ''
await expect(panel, `live region after a pick at ${width} px`).toContainText(zoneName)
const drawingBox = await page
.getByTestId('catalogue-canvas-drawing')
.locator('svg')
.first()
.boundingBox()
const referencesBox = await page
.getByRole('heading', { level: 2, name: dict['catalogue.references.title'] })
.locator('xpath=ancestor::section[1]')
.boundingBox()
expect(
referencesBox!.y,
`references below the drawing at ${width} px`,
).toBeGreaterThanOrEqual(drawingBox!.y + drawingBox!.height - 1)
}
await page.setViewportSize(original)
// A zone picked on the drawing, then one from the list: its panel shows.
const zone = page.getByRole('combobox', {
name: dict['catalogue.zone.choose'],
@@ -1,3 +1,4 @@
import { useRef } from 'react'
import { Link } from 'react-router-dom'
import {
listOfficialSheetsAdmin,
@@ -5,6 +6,7 @@ import {
} from '@faunosteo/supabase'
import SheetBadges from '@/components/admin/SheetBadges'
import WorkingCopyAction from '@/components/admin/WorkingCopyAction'
import PermissionsUnavailable from '@/components/shell/PermissionsUnavailable'
import Button from '@/components/ui/Button'
import ButtonLink from '@/components/ui/ButtonLink'
import Card from '@/components/ui/Card'
@@ -13,6 +15,7 @@ import { failureMessage, localized } from '@/admin/labels'
import { useAdminPermissions, type AdminPermissions } from '@/admin/permissions'
import { isRightsRefusal, useAdminQuery } from '@/admin/useAdminQuery'
import { usePageHeading } from '@/app/usePageHeading'
import { useAuthStore } from '@/state/authStore'
import { useLocaleStore } from '@/state/localeStore'
import { useT } from '@/i18n/useT'
@@ -164,6 +167,14 @@ export default function AdminHomeRoute() {
const t = useT()
const heading = usePageHeading()
const permissions = useAdminPermissions()
const grantsStatus = useAuthStore((s) => s.catalogGrantsStatus)
const reloadAccess = useAuthStore((s) => s.reloadAccess)
const access = useRef<HTMLDivElement>(null)
// Focus stays on the wrapper when the Retry button unmounts with the notice.
const retry = async () => {
await reloadAccess()
access.current?.focus()
}
return (
<div className="space-y-5">
<header className="space-y-1">
@@ -174,9 +185,21 @@ export default function AdminHomeRoute() {
>
{t('shell.nav.admin')}
</h1>
<p className="text-sm text-[var(--color-ink-muted)]">
{permissionsLine(t, permissions)}
</p>
<div ref={access} tabIndex={-1} className="outline-none">
{grantsStatus === 'loading' && (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
{t('shell.loading_session')}
</p>
)}
{grantsStatus === 'failed' && (
<PermissionsUnavailable asPage={false} onRetry={() => void retry()} />
)}
{grantsStatus === 'ready' && (
<p className="text-sm text-[var(--color-ink-muted)]">
{permissionsLine(t, permissions)}
</p>
)}
</div>
</header>
<div className="grid gap-4 md:grid-cols-2">
<SheetsCard editor={permissions.editor} />
@@ -11,6 +11,7 @@ import SpeciesDialog, {
type SpeciesDialogMode,
} from '@/components/admin/SpeciesDialog'
import AccessDenied from '@/components/shell/AccessDenied'
import PermissionsUnavailable from '@/components/shell/PermissionsUnavailable'
import Button, { buttonClassName } from '@/components/ui/Button'
import Card from '@/components/ui/Card'
import FormField, { fieldDescribedBy } from '@/components/ui/FormField'
@@ -97,6 +98,7 @@ export default function AdminSheetCreateRoute() {
const locale = useLocaleStore((s) => s.locale)
const { editor } = useAdminPermissions()
const grantsStatus = useAuthStore((s) => s.catalogGrantsStatus)
const reloadAccess = useAuthStore((s) => s.reloadAccess)
const species = useAdminQuery('species', listCatalogSpecies)
const [values, setValues] = useState<SheetFormValues>(EMPTY)
const [slugEdited, setSlugEdited] = useState(false)
@@ -112,11 +114,13 @@ export default function AdminSheetCreateRoute() {
if (first) document.getElementById(fieldId(first))?.focus()
}, [errorRound, errors])
// A display rule like the « Nouvelle fiche » button: once the caller's own
// grants are read, a reviewer or a publisher reaching the address is not
// offered the form. While they load nothing is decided; if the read failed
// the form shows and the server, which refuses creation to anyone without
// the editor capability, decides.
// Three states (owner 2026-11-02), checked in this order: own grants still
// loading (wait); the server refused (its `rights.*` answer wins, BDR-094);
// own grants unreadable (retry, never the form and never a refusal deduced
// from a technical error); then, grants read, the display rule: no editor
// capability, no form. The server decides creation either way. Every hook
// stays above these returns so the form values survive a state switch: do
// not move the form state into a child.
if (grantsStatus === 'loading')
return (
<p role="status" className="text-sm text-[var(--color-ink-muted)]">
@@ -124,11 +128,18 @@ export default function AdminSheetCreateRoute() {
</p>
)
if (
(grantsStatus === 'ready' && !editor) ||
(species.state.status === 'error' &&
isRightsRefusal(species.state.failure))
species.state.status === 'error' &&
isRightsRefusal(species.state.failure)
)
return <AccessDenied />
if (grantsStatus === 'failed') {
const retry = () => {
void reloadAccess()
if (species.state.status === 'error') species.refresh()
}
return <PermissionsUnavailable asPage onRetry={retry} />
}
if (!editor) return <AccessDenied />
const set = (key: keyof SheetFormValues) => (value: string) =>
setValues((v) => {
+31 -29
View File
@@ -96,36 +96,38 @@ export default function ZonePanel({ state, viewId, selectedId, onSelect }: ZoneP
))}
</select>
</label>
{annotation ? (
<div aria-live="polite" className="space-y-2">
<h2 id="catalogue-zone-title" className="font-serif text-lg text-[var(--color-ink)]">
{t('catalogue.zone.title').replace('{name}', nameOf(annotation.id))}
</h2>
<p className="text-sm text-[var(--color-ink-muted)]">
{zoneLine(state, annotation, locale, t)}
<div aria-live="polite" className="space-y-2">
{annotation ? (
<>
<h2 id="catalogue-zone-title" className="font-serif text-lg text-[var(--color-ink)]">
{t('catalogue.zone.title').replace('{name}', nameOf(annotation.id))}
</h2>
<p className="text-sm text-[var(--color-ink-muted)]">
{zoneLine(state, annotation, locale, t)}
</p>
{findingZone && findingZone.categories.length > 0 ? (
findingZone.categories.map((category) => (
<section key={category.id} className="space-y-1 pt-1">
<h3 className="text-xs font-semibold uppercase tracking-wide text-[var(--color-ink-muted)]">
{pickLabel(category.name, locale)}
</h3>
<ul className="divide-y divide-[var(--color-border)]">
{category.children.map((node) => (
<FindingItem key={node.id} node={node} locale={locale} />
))}
</ul>
</section>
))
) : (
<p className="text-sm text-[var(--color-ink-muted)]">{t('catalogue.zone.no_findings')}</p>
)}
</>
) : (
<p id="catalogue-zone-title" className="text-sm text-[var(--color-ink-muted)]">
{t('catalogue.zone.prompt')}
</p>
{findingZone && findingZone.categories.length > 0 ? (
findingZone.categories.map((category) => (
<section key={category.id} className="space-y-1 pt-1">
<h3 className="text-xs font-semibold uppercase tracking-wide text-[var(--color-ink-muted)]">
{pickLabel(category.name, locale)}
</h3>
<ul className="divide-y divide-[var(--color-border)]">
{category.children.map((node) => (
<FindingItem key={node.id} node={node} locale={locale} />
))}
</ul>
</section>
))
) : (
<p className="text-sm text-[var(--color-ink-muted)]">{t('catalogue.zone.no_findings')}</p>
)}
</div>
) : (
<p id="catalogue-zone-title" className="text-sm text-[var(--color-ink-muted)]">
{t('catalogue.zone.prompt')}
</p>
)}
)}
</div>
</Card>
)
}
@@ -7,9 +7,10 @@ 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;
* also the sheet creation page for an account whose own grants hold no editor
* capability (a display rule, the server still decides). Nothing from the
* address is echoed.
* also the sheet creation page once the own grants are read and hold no
* editor capability (a display rule, the server still decides). Never shown
* for a failed read (PermissionsUnavailable). Nothing from the address is
* echoed.
*/
export default function AccessDenied() {
const t = useT()
@@ -0,0 +1,50 @@
import Button from '@/components/ui/Button'
import Card from '@/components/ui/Card'
import { usePageHeading } from '@/app/usePageHeading'
import { useAuthStore } from '@/state/authStore'
import { useT } from '@/i18n/useT'
interface Props {
/** The whole page (h1, focused on open) or a section inside one (h2). */
asPage: boolean
onRetry?: () => void
}
/**
* « Impossible de vérifier vos autorisations » (owner 2026-11-02): the own
* grants could not be read. A technical error never reads as an absence of
* right, so no form and no refusal; Retry reads them again. The server still
* decides every action.
*/
export default function PermissionsUnavailable({ asPage, onRetry }: Props) {
const t = useT()
const heading = usePageHeading()
const retry = onRetry ?? (() => void useAuthStore.getState().reloadAccess())
const body = (
<>
<p className="text-sm text-[var(--color-ink-muted)]">
{t('permissions_unavailable.body')}
</p>
<Button type="button" variant="secondary" onClick={retry}>
{t('common.retry')}
</Button>
</>
)
if (asPage)
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('permissions_unavailable.title')}
</h1>
{body}
</Card>
)
return (
<Card as="section" aria-labelledby="permissions-unavailable-title" className="space-y-3 p-5 sm:p-6">
<h2 id="permissions-unavailable-title" className="font-serif text-lg text-[var(--color-ink)]">
{t('permissions_unavailable.title')}
</h2>
{body}
</Card>
)
}
+2
View File
@@ -863,6 +863,8 @@ export const en: Dict = {
'access_denied.title': 'Access denied',
'access_denied.body': "You don't have permission to access this page.",
'access_denied.back': 'Back to dashboard',
'permissions_unavailable.title': 'Unable to verify your permissions',
'permissions_unavailable.body': 'The check did not complete, probably because of a connection problem. This error does not change your permissions.',
'admin.sheets.title': 'Official sheets',
'admin.sheets.new': 'New sheet',
'admin.species.title': 'Species',
+2
View File
@@ -894,6 +894,8 @@ export const fr: Dict = {
'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',
'permissions_unavailable.title': 'Impossible de vérifier vos autorisations',
'permissions_unavailable.body': "La vérification n'a pas abouti, probablement à cause d'un problème de connexion. Cette erreur ne modifie pas vos droits.",
'admin.sheets.title': 'Fiches officielles',
'admin.sheets.new': 'Nouvelle fiche',
'admin.species.title': 'Espèces',
+22 -4
View File
@@ -68,11 +68,16 @@ export interface AuthState {
* Empty until loaded and when the read fails.
*/
catalogGrants: OwnCatalogGrant[]
/** Whether `catalogGrants` is read yet: a display rule waits for `ready`, and a `failed` read leaves the decision to the server. */
/** Whether `catalogGrants` is read yet: a display rule waits for `ready`; `failed` = the read failed, pages show the unavailable state and never deduce an absence of right from it. */
catalogGrantsStatus: 'loading' | 'ready' | 'failed'
/** Subscribes to the client; returns the unsubscribe. Safe to call twice. */
start: () => () => void
refreshAccount: () => Promise<void>
/**
* Reads the platform roles and own grants again after a failed permission
* read (owner 2026-11-02): pages wait, then show what the answer gives; a
* technical error never wipes what the account already holds. Never rejects.
*/
reloadAccess: () => Promise<void>
/** Reads the personal workspace again (after a failure). */
refreshWorkspace: () => Promise<void>
updateProfile: (patch: OwnProfilePatch) => Promise<Profile>
@@ -260,8 +265,21 @@ export const useAuthStore = create<AuthState>((set, get) => ({
return () => data.subscription.unsubscribe()
},
refreshAccount: async () => {
await loadAccount(requireClient(), requireUser(get().user), set, get)
reloadAccess: async () => {
const user = get().user
const client = getSupabaseClient()
if (!user || !client) return set({ catalogGrants: [], catalogGrantsStatus: 'failed' })
const setOwn = setForUser(user, set, get)
setOwn({ catalogGrantsStatus: 'loading' })
try {
const [roles, catalogGrants] = await Promise.all([
fetchOwnPlatformRoles(client, user.id),
listOwnCatalogGrants(client, user.id),
])
setOwn({ roles, catalogGrants, catalogGrantsStatus: 'ready' })
} catch {
setOwn({ catalogGrants: [], catalogGrantsStatus: 'failed' })
}
},
refreshWorkspace: async () => {
+112 -9
View File
@@ -148,8 +148,9 @@ function mount(
path: string,
grants: OwnCatalogGrant[],
roles: PlatformRole[] = [],
status: 'loading' | 'ready' | 'failed' = 'ready',
) {
useAuthStore.setState({ catalogGrants: grants, catalogGrantsStatus: 'ready', roles })
useAuthStore.setState({ catalogGrants: grants, catalogGrantsStatus: status, roles })
return render(
<MemoryRouter initialEntries={[path]}>
<Routes>
@@ -171,6 +172,7 @@ function mount(
beforeAll(async () => {
setCoreRuntime(await testCoreRuntime())
})
const realReloadAccess = useAuthStore.getState().reloadAccess
beforeEach(() => {
useLocaleStore.setState({ locale: 'fr' })
fake = createFakeSupabase()
@@ -180,7 +182,39 @@ beforeEach(() => {
fake.rpcResults.list_catalog_species = { data: SPECIES }
mocks.fake = fake
})
afterEach(() => cleanup())
afterEach(() => {
cleanup()
useAuthStore.setState({ reloadAccess: realReloadAccess })
})
describe('Administration page: own grants states', () => {
it('loading: the waiting status, not « aucune »', () => {
mount('/app/admin', [], [], 'loading')
expect(screen.getByText(fr['shell.loading_session'])).toHaveAttribute('role', 'status')
expect(screen.queryByText(/aucune/)).toBeNull()
})
it('failed: the unavailable notice as a section, Retry, focus kept on the wrapper', async () => {
const user = userEvent.setup()
const reloadAccess = vi.fn(async () =>
useAuthStore.setState({ catalogGrants: [grant('sheet_editor')], catalogGrantsStatus: 'ready' }),
)
mount('/app/admin', [], [], 'failed')
useAuthStore.setState({ reloadAccess })
expect(screen.getAllByRole('heading', { level: 1 })).toHaveLength(1)
expect(
screen.getByRole('heading', { level: 2, name: fr['permissions_unavailable.title'] }),
).toBeInTheDocument()
expect(screen.queryByText(/aucune/)).toBeNull()
await user.click(screen.getByRole('button', { name: 'Réessayer' }))
expect(reloadAccess).toHaveBeenCalledTimes(1)
await waitFor(() =>
expect(screen.getByText(/Vos habilitations : éditeur de fiches/)).toBeInTheDocument(),
)
const wrapper = screen.getByText(/Vos habilitations/).parentElement
expect(wrapper).toHaveFocus()
})
})
describe('Administration page (board 10)', () => {
it('editor and publisher: permissions line, sheets with badges, the working copy action disabled with its reason', async () => {
@@ -655,13 +689,82 @@ describe('Sheet creation (A1)', () => {
expect(rpcArgs('create_official_sheet')).toEqual([])
})
it('decides nothing while the own grants load, and leaves a failed read to the server', async () => {
mount('/app/admin/sheets/new', [])
useAuthStore.setState({ catalogGrantsStatus: 'loading' })
expect(await screen.findByRole('status')).toHaveTextContent(fr['shell.loading_session'])
expect(screen.queryByRole('heading', { name: fr['access_denied.title'] })).toBeNull()
useAuthStore.setState({ catalogGrantsStatus: 'failed' })
expect(await screen.findByLabelText('Espèce')).toBeInTheDocument()
describe.each([
['a reviewer-only account', [grant('sheet_reviewer')], false],
['an editor account', [grant('sheet_editor')], true],
] as const)('permission states for %s', (_, grants, canCreate) => {
const denied = () =>
screen.queryByRole('heading', { name: fr['access_denied.title'] })
const unavailable = () =>
screen.queryByRole('heading', {
name: fr['permissions_unavailable.title'],
})
it('ready: the form for the editor, « Accès non autorisé » otherwise', async () => {
mount('/app/admin/sheets/new', [...grants])
if (canCreate) {
expect(await screen.findByLabelText('Espèce')).toBeInTheDocument()
expect(denied()).toBeNull()
} else {
expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
expect(screen.queryByLabelText('Espèce')).toBeNull()
}
expect(unavailable()).toBeNull()
})
it('failed: the unavailable state, no form, no refusal deduced', async () => {
mount('/app/admin/sheets/new', [...grants], [], 'failed')
expect(await screen.findByRole('heading', { name: fr['permissions_unavailable.title'] })).toBeInTheDocument()
expect(screen.getByText(fr['permissions_unavailable.body'])).toBeInTheDocument()
expect(screen.getByRole('button', { name: 'Réessayer' })).toBeInTheDocument()
expect(document.querySelector('input, select')).toBeNull()
expect(denied()).toBeNull()
})
it('loading: waits, decides nothing', async () => {
mount('/app/admin/sheets/new', [...grants], [], 'loading')
expect(await screen.findByRole('status')).toHaveTextContent(fr['shell.loading_session'])
expect(denied()).toBeNull()
expect(unavailable()).toBeNull()
expect(document.querySelector('input, select')).toBeNull()
})
it('Retry lands on what the new answer gives', async () => {
const user = userEvent.setup()
const reloadAccess = vi.fn(async () =>
useAuthStore.setState({ catalogGrants: [...grants], catalogGrantsStatus: 'ready' }),
)
mount('/app/admin/sheets/new', [], [], 'failed')
useAuthStore.setState({ reloadAccess })
await user.click(await screen.findByRole('button', { name: 'Réessayer' }))
expect(reloadAccess).toHaveBeenCalledTimes(1)
if (canCreate) expect(await screen.findByLabelText('Espèce')).toBeInTheDocument()
else expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
})
})
it('Retry also reads a failed species list again', async () => {
const user = userEvent.setup()
let calls = 0
fake.rpcResults.list_catalog_species = () =>
++calls === 1 ? { error: new TypeError('fetch failed') } : { data: SPECIES }
mount('/app/admin/sheets/new', [], [], 'failed')
useAuthStore.setState({
reloadAccess: vi.fn(async () =>
useAuthStore.setState({ catalogGrants: [grant('sheet_editor')], catalogGrantsStatus: 'ready' }),
),
})
await user.click(await screen.findByRole('button', { name: 'Réessayer' }))
const species = await screen.findByLabelText('Espèce')
await waitFor(() => expect(within(species).getAllByRole('option')).toHaveLength(3))
expect(calls).toBe(2)
})
it('a server rights refusal wins over a failed grants read', async () => {
fake.rpcResults.list_catalog_species = refusal('rights.capability')
mount('/app/admin/sheets/new', [], [], 'failed')
expect(await screen.findByRole('heading', { name: fr['access_denied.title'] })).toBeInTheDocument()
expect(screen.queryByRole('heading', { name: fr['permissions_unavailable.title'] })).toBeNull()
})
it('proposes a slug from the French name', () => {
@@ -117,6 +117,91 @@ describe('authStore', () => {
expect(useAuthStore.getState().catalogGrantsStatus).toBe('loading')
})
describe('reloadAccess', () => {
type Answer = { data: unknown; error: unknown; status?: number }
const FAILED: Answer = { data: null, error: { code: '', message: 'FetchError' }, status: 0 }
const GRANT = { user_id: 'user-1', kind: 'sheet_editor', expires_at: null, revoked_at: null }
/** Every chain on `table` ends in `answer()`, as a dropped request or a late reply would. */
function answerTable(table: string, answer: () => Answer | Promise<Answer>) {
const from = fake.client.from.bind(fake.client)
const chain: unknown = new Proxy(() => undefined, {
get: (_, key) =>
key === 'then'
? (resolve: (v: unknown) => void, reject: (e: unknown) => void) =>
Promise.resolve(answer()).then(resolve, reject)
: () => chain,
})
;(fake.client as unknown as { from: (t: string) => unknown }).from = (t: string) =>
t === table ? chain : from(t as never)
}
async function signedIn() {
fake.tables.profiles = [fakeProfile(), fakeProfile({ id: 'user-2' })]
stop = useAuthStore.getState().start()
fake.emit('SIGNED_IN', fakeSession())
await flush()
await flush()
}
it('goes loading then ready, replacing the roles and the grants', async () => {
await signedIn()
expect(useAuthStore.getState().roles).toEqual(['admin'])
fake.tables.profile_roles = [{ user_id: 'user-1', role: 'owner', revoked_at: null }]
fake.tables.anatomical_catalog_grants = [GRANT]
const reload = useAuthStore.getState().reloadAccess()
expect(useAuthStore.getState().catalogGrantsStatus).toBe('loading')
await reload
const s = useAuthStore.getState()
expect(s.catalogGrantsStatus).toBe('ready')
expect(s.roles).toEqual(['owner'])
expect(s.catalogGrants).toEqual([GRANT])
})
it.each(['anatomical_catalog_grants', 'profile_roles'])(
'ends failed with no grants and keeps the roles, profile and workspace when the %s read rejects',
async (table) => {
fake.tables.workspaces = [{ id: 'ws-1', personal_user_id: 'user-1' }]
fake.tables.anatomical_catalog_grants = [GRANT]
await signedIn()
const before = useAuthStore.getState()
expect(before.catalogGrants).toEqual([GRANT])
answerTable(table, () => FAILED)
await expect(useAuthStore.getState().reloadAccess()).resolves.toBeUndefined()
const s = useAuthStore.getState()
expect(s.catalogGrantsStatus).toBe('failed')
expect(s.catalogGrants).toEqual([])
expect(s.roles).toEqual(['admin'])
expect(s.profile).toEqual(before.profile)
expect(s.workspace).toEqual({ status: 'ready', id: 'ws-1' })
},
)
it('ends failed and resolves without a user', async () => {
useAuthStore.setState({ catalogGrants: [], catalogGrantsStatus: 'ready' })
await expect(useAuthStore.getState().reloadAccess()).resolves.toBeUndefined()
expect(useAuthStore.getState().catalogGrantsStatus).toBe('failed')
})
it('drops a late answer once another account signed in', async () => {
await signedIn()
const releases: Array<(a: Answer) => void> = []
answerTable(
'anatomical_catalog_grants',
() => new Promise<Answer>((resolve) => releases.push(resolve)),
)
const reload = useAuthStore.getState().reloadAccess()
await flush()
fake.emit('SIGNED_IN', fakeSession(fakeUser({ id: 'user-2' })))
releases.forEach((release) => release({ data: [GRANT], error: null }))
await reload
await flush()
expect(useAuthStore.getState().catalogGrants).toEqual([])
expect(useAuthStore.getState().roles).not.toEqual(['owner'])
expect(useAuthStore.getState().user?.id).toBe('user-2')
})
})
it('updateProfile writes the row and keeps the store in sync', async () => {
stop = useAuthStore.getState().start()
fake.emit('SIGNED_IN', fakeSession())