From 51225cacf6b79e2e3ce95b10ade01bfba6e74fc8 Mon Sep 17 00:00:00 2001 From: bchanot Date: Mon, 2 Nov 2026 21:29:33 +0100 Subject: [PATCH] fix(app): grant expiry ends the chosen day in Paris; species order 0..9999 (V1-2.5 L2) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Owner checkpoint 2026-11-02: expiry 23:59:59.999 Europe/Paris (picker, validation, display), tests under non-Paris zones and DST days; M7 redefines create_species and update_inactive_species with the range check; pgTAP 015 and 022; « Relecteur ou relectrice »; object_conflict EN; setup key selectable, no Copy. --- .../2026-11-02-v1-2-5-label-proposals.md | 4 +- .claude/tasks/TODO.md | 2 +- apps/app/src/admin/labels.ts | 9 +- apps/app/src/admin/validation.ts | 24 +++-- apps/app/src/components/admin/GrantList.tsx | 3 +- apps/app/src/components/admin/GrantPanel.tsx | 4 +- apps/app/src/i18n/en.ts | 2 +- apps/app/src/i18n/fr.ts | 2 +- apps/app/src/lib/dates.ts | 68 ++++++++++++ apps/app/tests/unit/admin.validation.test.ts | 102 ++++++++++++++++++ .../unit/components.SecurityPanel.test.tsx | 26 +++++ apps/app/tests/unit/lib.dates.test.ts | 55 +++++++++- apps/app/tests/unit/routes.admin.test.tsx | 37 +------ docs/development/V1-2_ANATOMICAL_SHEETS.md | 2 +- .../20261102100000_sheet_admin_reads.sql | 71 +++++++++++- supabase/tests/015_catalog_access.sql | 53 ++++++++- supabase/tests/022_sheet_admin_reads.sql | 34 +++++- 17 files changed, 437 insertions(+), 61 deletions(-) create mode 100644 apps/app/tests/unit/admin.validation.test.ts diff --git a/.claude/audits/2026-11-02-v1-2-5-label-proposals.md b/.claude/audits/2026-11-02-v1-2-5-label-proposals.md index dca7c471..8c3d0ad7 100644 --- a/.claude/audits/2026-11-02-v1-2-5-label-proposals.md +++ b/.claude/audits/2026-11-02-v1-2-5-label-proposals.md @@ -3,7 +3,7 @@ Ratified wordings used verbatim (V1-2 contract §3, §17.9, REVUE.md): Fiches anatomiques / Anatomical sheets; Administration; Accès non autorisé / Access denied, its explanation and « Retour au tableau de bord » / « Back to dashboard » (L32); Fiches officielles / Official sheets; Espèces / Species; Accès et habilitations / Access and -permissions (L14). Everything below is a proposal, not ratified. +permissions (L14). Everything below is a proposal, not ratified: the owner (2026-11-02) did not approve the roughly 350 new labels of V1-2.5, which get a separate review. Ratified at that checkpoint: « Relecteur ou relectrice »; the EN `catalogue.failure.drawing_hash_mismatch` « The illustration file's contents do not match its recorded SHA-256 hash. » (= `object_conflict` EN); the MFA factor name limit of 64 characters; no Copy button for the setup key. ## Slices E and F (shell, step-up, MFA) @@ -71,7 +71,7 @@ Ratified wordings reused verbatim: §3 round and version statuses, grant kind la | admin.person.unnamed | Compte sans nom | Unnamed account | | admin.grant_kind.catalog_reader | Accès au catalogue | Catalogue access | | admin.grant_kind.sheet_editor | Éditeur de fiches | Sheet editor | -| admin.grant_kind.sheet_reviewer | Relecteur, relectrice | Reviewer | +| admin.grant_kind.sheet_reviewer | Relecteur ou relectrice (ratified, owner 2026-11-02) | Reviewer | | admin.grant_kind.sheet_publisher | Responsable de publication | Publisher | | admin.grant_state.active | En vigueur | In force | | admin.grant_state.expiring | Expire sous 30 jours | Expires within 30 days | diff --git a/.claude/tasks/TODO.md b/.claude/tasks/TODO.md index fe1d777c..57c5d1ee 100644 --- a/.claude/tasks/TODO.md +++ b/.claude/tasks/TODO.md @@ -668,7 +668,7 @@ Order (BDR-071): P0 docs + decisions → V1-1 clients and animals → V1-2 sheet - [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 + - [x] L2 expiry end of day Europe/Paris, species order 0..9 999 in M7, labels, TOTP key test: app 696, supabase 148, pgTAP 1965 fresh + upgrade, types match - [ ] 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) diff --git a/apps/app/src/admin/labels.ts b/apps/app/src/admin/labels.ts index 5e914af9..4f8dd918 100644 --- a/apps/app/src/admin/labels.ts +++ b/apps/app/src/admin/labels.ts @@ -83,12 +83,17 @@ export function personName( return person?.display_name || t('admin.person.unnamed') } -/** A server timestamp as a date in the interface language. */ -export function formatDay(iso: string, locale: Locale): string { +/** A server timestamp as a date in the interface language (in `timeZone` when given). */ +export function formatDay( + iso: string, + locale: Locale, + timeZone?: string, +): string { return new Date(iso).toLocaleDateString(locale, { day: 'numeric', month: 'long', year: 'numeric', + ...(timeZone ? { timeZone } : {}), }) } diff --git a/apps/app/src/admin/validation.ts b/apps/app/src/admin/validation.ts index 75a5cedf..fb998847 100644 --- a/apps/app/src/admin/validation.ts +++ b/apps/app/src/admin/validation.ts @@ -1,6 +1,6 @@ import { z } from 'zod' import { codePointLength } from '@faunosteo/supabase' -import { localDateIso } from '@/lib/dates' +import { endOfParisDayIso, parisDateIso } from '@/lib/dates' /** * The administration forms (contract §5.2, §7.2, §7.4). Bounds and patterns @@ -173,11 +173,20 @@ export interface GrantFields { kind: GrantKind reason: string verification_note?: string - /** The end of the chosen day, device time zone. */ + /** The end of the chosen day, Europe/Paris (owner 2026-11-02). */ expires_at?: string } -/** The expiry is a day after today (device date): the server refuses a past one. */ +/** YYYY-MM-DD naming a real calendar day (no 2026-02-30). */ +function isRealDay(day: string): boolean { + const match = day.match(/^(\d{4})-(\d{2})-(\d{2})$/) + if (!match) return false + const [y, mo, d] = [Number(match[1]), Number(match[2]), Number(match[3])] + const date = new Date(Date.UTC(y, mo - 1, d)) + return date.getUTCMonth() === mo - 1 && date.getUTCDate() === d +} + +/** The expiry is a real day after today (Paris date): the server refuses a past one. */ function grantSchema(today: string) { return z .object({ @@ -195,8 +204,7 @@ function grantSchema(today: string) { expires_on: z .string() .refine( - (day) => - day === '' || (/^\d{4}-\d{2}-\d{2}$/.test(day) && day > today), + (day) => day === '' || (isRealDay(day) && day > today), 'admin.access.error.expiry', ), }) @@ -228,9 +236,7 @@ function grantSchema(today: string) { : {}), ...(values.expires_on ? { - expires_at: new Date( - `${values.expires_on}T23:59:59`, - ).toISOString(), + expires_at: endOfParisDayIso(values.expires_on), } : {}), }), @@ -239,7 +245,7 @@ function grantSchema(today: string) { export function parseGrant( values: GrantFormValues, - today: string = localDateIso(), + today: string = parisDateIso(), ): Parsed { return parse(grantSchema(today), values) } diff --git a/apps/app/src/components/admin/GrantList.tsx b/apps/app/src/components/admin/GrantList.tsx index 010bd89d..5d237aa0 100644 --- a/apps/app/src/components/admin/GrantList.tsx +++ b/apps/app/src/components/admin/GrantList.tsx @@ -7,6 +7,7 @@ import FormField from '@/components/ui/FormField' import Notice from '@/components/ui/Notice' import Select from '@/components/ui/Select' import { formatDay } from '@/admin/labels' +import { PARIS_TIME_ZONE } from '@/lib/dates' import type { Locale } from '@/i18n/types' import { useLocaleStore } from '@/state/localeStore' import { useT } from '@/i18n/useT' @@ -51,7 +52,7 @@ function GrantItem({ const expiry = grant.expires_at ? t('admin.access.list.expires').replace( '{date}', - formatDay(grant.expires_at, locale), + formatDay(grant.expires_at, locale, PARIS_TIME_ZONE), ) : t('admin.access.list.no_expiry') const live = grant.state === 'active' || grant.state === 'expiring' diff --git a/apps/app/src/components/admin/GrantPanel.tsx b/apps/app/src/components/admin/GrantPanel.tsx index b1a8f775..87796ef1 100644 --- a/apps/app/src/components/admin/GrantPanel.tsx +++ b/apps/app/src/components/admin/GrantPanel.tsx @@ -23,7 +23,7 @@ import { type GrantFormValues, } from '@/admin/validation' import { translateFieldError } from '@/account/validation' -import { localDateIso } from '@/lib/dates' +import { parisTomorrowIso } from '@/lib/dates' import { getSupabaseClient } from '@/lib/supabase' import { useT } from '@/i18n/useT' @@ -277,7 +277,7 @@ export default function GrantPanel({ onGranted }: { onGranted: () => void }) { set('expires_on')(e.target.value)} aria-invalid={Boolean(errors.expires_on)} diff --git a/apps/app/src/i18n/en.ts b/apps/app/src/i18n/en.ts index 13409361..dfcea42e 100644 --- a/apps/app/src/i18n/en.ts +++ b/apps/app/src/i18n/en.ts @@ -1171,7 +1171,7 @@ export const en: Dict = { 'catalogue.failure.rate_limited': 'Too many requests. Wait a few minutes before trying again.', 'catalogue.failure.unavailable': 'The catalogue is temporarily unavailable. Try again later.', 'catalogue.failure.drawing_missing': 'A drawing of this version cannot be found.', - 'catalogue.failure.drawing_hash_mismatch': "A drawing's file content does not match its recorded SHA-256 fingerprint.", + 'catalogue.failure.drawing_hash_mismatch': "The illustration file's contents do not match its recorded SHA-256 hash.", 'catalogue.failure.fingerprint_mismatch': "This version's fingerprint does not match the one recorded at its publication.", 'catalogue.failure.invalid_document': "This version's content cannot be read.", 'catalogue.failure.caps': 'This version exceeds the size limits of a sheet.', diff --git a/apps/app/src/i18n/fr.ts b/apps/app/src/i18n/fr.ts index 0b4b5a33..536136f0 100644 --- a/apps/app/src/i18n/fr.ts +++ b/apps/app/src/i18n/fr.ts @@ -987,7 +987,7 @@ export const fr: Dict = { 'admin.person.unnamed': 'Compte sans nom', 'admin.grant_kind.catalog_reader': 'Accès au catalogue', 'admin.grant_kind.sheet_editor': 'Éditeur de fiches', - 'admin.grant_kind.sheet_reviewer': 'Relecteur, relectrice', + 'admin.grant_kind.sheet_reviewer': 'Relecteur ou relectrice', 'admin.grant_kind.sheet_publisher': 'Responsable de publication', 'admin.grant_state.active': 'En vigueur', 'admin.grant_state.expiring': 'Expire sous 30 jours', diff --git a/apps/app/src/lib/dates.ts b/apps/app/src/lib/dates.ts index 38680bb4..6ee11161 100644 --- a/apps/app/src/lib/dates.ts +++ b/apps/app/src/lib/dates.ts @@ -11,6 +11,74 @@ export function localDateIso(date: Date = new Date()): string { return `${date.getFullYear()}-${month}-${day}` } +/** The zone of the French perimeter: grant expiries are days there (owner 2026-11-02). */ +export const PARIS_TIME_ZONE = 'Europe/Paris' + +const PARIS_PARTS = new Intl.DateTimeFormat('en-US', { + timeZone: PARIS_TIME_ZONE, + year: 'numeric', + month: 'numeric', + day: 'numeric', + hour: 'numeric', + minute: 'numeric', + second: 'numeric', + hourCycle: 'h23', +}) + +/** The Paris wall clock at an instant, as numbers (month 1-12). */ +function parisParts(instant: number) { + const parts: Record = {} + for (const part of PARIS_PARTS.formatToParts(instant)) + if (part.type !== 'literal') parts[part.type] = Number(part.value) + return parts +} + +function isoDay(year: number, month: number, day: number): string { + const pad = (n: number, width: number) => String(n).padStart(width, '0') + return `${pad(year, 4)}-${pad(month, 2)}-${pad(day, 2)}` +} + +/** The date in Paris as YYYY-MM-DD, whatever the device zone. */ +export function parisDateIso(date: Date = new Date()): string { + const p = parisParts(date.getTime()) + return isoDay(p.year, p.month, p.day) +} + +/** The calendar day after the Paris date (day arithmetic, never + 24 h). */ +export function parisTomorrowIso(date: Date = new Date()): string { + const p = parisParts(date.getTime()) + const next = new Date(Date.UTC(p.year, p.month - 1, p.day + 1)) + return isoDay( + next.getUTCFullYear(), + next.getUTCMonth() + 1, + next.getUTCDate(), + ) +} + +/** + * The last millisecond of a Paris day (YYYY-MM-DD) as a UTC ISO instant, + * with the offset in force at that instant. Paris changes offset at 01:00 + * UTC, so one correction is exact for 23:59 local. + */ +export function endOfParisDayIso(day: string): string { + const match = day.match(/^(\d{4})-(\d{2})-(\d{2})$/) + if (!match) throw new Error(`Invalid ISO date: ${day}`) + const [y, mo, d] = [Number(match[1]), Number(match[2]), Number(match[3])] + const guess = Date.UTC(y, mo - 1, d, 23, 59, 59, 999) + const check = new Date(guess) + if ( + check.getUTCFullYear() !== y || + check.getUTCMonth() !== mo - 1 || + check.getUTCDate() !== d + ) + throw new Error(`Invalid ISO date: ${day}`) + const p = parisParts(guess) + const offset = + Date.UTC(p.year, p.month - 1, p.day, p.hour, p.minute, p.second, 999) - + guess + return new Date(guess - offset).toISOString() +} + export function nowIso(): string { return new Date().toISOString() } diff --git a/apps/app/tests/unit/admin.validation.test.ts b/apps/app/tests/unit/admin.validation.test.ts new file mode 100644 index 00000000..71e9f49a --- /dev/null +++ b/apps/app/tests/unit/admin.validation.test.ts @@ -0,0 +1,102 @@ +import { createElement } from 'react' +import { afterAll, beforeAll, describe, expect, it } from 'vitest' +import { cleanup, render, screen } from '@testing-library/react' +import type { CatalogGrant } from '@faunosteo/supabase' +import GrantList from '@/components/admin/GrantList' +import { useLocaleStore } from '@/state/localeStore' +import { parseGrant } from '@/admin/validation' + +const GRANT = { + kind: 'catalog_reader' as const, + reason: ' Lecture ', + verification_note: '', +} + +const EXPIRING: CatalogGrant = { + id: 'g-1', + user_id: 'user-2', + display_name: 'Paul', + email: 'paul@example.test', + kind: 'catalog_reader', + reason: 'Essai', + verification_note: null, + granted_by: 'user-1', + granted_by_name: 'Alice', + granted_at: '2026-11-01T10:00:00Z', + expires_at: '2026-12-31T22:59:59.999Z', + revoked_at: null, + revoked_by: null, + revocation_reason: null, + state: 'active', + effective: true, +} + +// Zones on both sides of Paris: the expiry never follows the device. +describe.each(['America/Los_Angeles', 'Pacific/Kiritimati'])( + 'grant expiry under the device zone %s', + (zone) => { + const previous = process.env.TZ + beforeAll(() => { + process.env.TZ = zone + expect(Intl.DateTimeFormat().resolvedOptions().timeZone).toBe(zone) + }) + afterAll(() => { + if (previous === undefined) delete process.env.TZ + else process.env.TZ = previous + }) + + it('the reader needs no note; the expiry is the end of the Paris day', () => { + expect( + parseGrant({ ...GRANT, expires_on: '2026-12-31' }, '2026-11-02'), + ).toEqual({ + ok: true, + value: { + kind: 'catalog_reader', + reason: 'Lecture', + expires_at: '2026-12-31T22:59:59.999Z', + }, + }) + expect( + parseGrant({ ...GRANT, expires_on: '2026-07-15' }, '2026-07-01'), + ).toMatchObject({ + ok: true, + value: { expires_at: '2026-07-15T21:59:59.999Z' }, + }) + }) + + it('refuses today, accepts tomorrow', () => { + expect( + parseGrant({ ...GRANT, expires_on: '2026-11-02' }, '2026-11-02'), + ).toMatchObject({ + ok: false, + errors: { expires_on: 'admin.access.error.expiry' }, + }) + expect( + parseGrant({ ...GRANT, expires_on: '2026-11-03' }, '2026-11-02'), + ).toMatchObject({ ok: true }) + }) + + it('refuses a day that does not exist', () => { + expect( + parseGrant({ ...GRANT, expires_on: '2026-02-30' }, '2026-01-01'), + ).toMatchObject({ + ok: false, + errors: { expires_on: 'admin.access.error.expiry' }, + }) + }) + + it('the grant list shows the Paris expiry day', () => { + // 23:59:59.999 Paris on 31 December; the device day would be 1 January east of Paris. + useLocaleStore.setState({ locale: 'fr' }) + render( + createElement(GrantList, { + grants: [EXPIRING], + onChanged: () => undefined, + }), + ) + expect(screen.getByText(/31 décembre 2026/)).toBeInTheDocument() + expect(screen.queryByText(/1 janvier 2027/)).toBeNull() + cleanup() + }) + }, +) diff --git a/apps/app/tests/unit/components.SecurityPanel.test.tsx b/apps/app/tests/unit/components.SecurityPanel.test.tsx index e047814e..c3632413 100644 --- a/apps/app/tests/unit/components.SecurityPanel.test.tsx +++ b/apps/app/tests/unit/components.SecurityPanel.test.tsx @@ -96,6 +96,17 @@ describe('Security, factors', () => { expect(JSON.stringify(useAuthStore.getState())).not.toContain(SECRET) }) + it('shows the setup key in full as selectable text, with no Copy button', async () => { + const user = userEvent.setup() + mount() + await startEnrolment(user) + const key = await screen.findByText(SECRET) + expect(key.textContent).toBe(SECRET) + expect(key.className).not.toMatch(/select-none/) + expect((key as HTMLElement).style.userSelect).not.toBe('none') + expect(screen.queryByRole('button', { name: /cop(y|ier)/i })).toBeNull() + }) + it('cancel removes the unverified factor it created and clears the secret', async () => { const user = userEvent.setup() mount() @@ -125,6 +136,21 @@ describe('Security, factors', () => { expect(fake.auth.mfa.enroll).not.toHaveBeenCalled() }) + it('refuses a 65-character name without calling GoTrue, accepts 64', async () => { + const user = userEvent.setup() + mount() + await user.click(await screen.findByRole('button', { name: fr['mfa.enrol.start'] })) + const field = screen.getByLabelText(fr['mfa.enrol.name']) + await user.type(field, 'a'.repeat(65)) + await user.click(screen.getByRole('button', { name: fr['mfa.enrol.continue'] })) + expect(screen.getByText(fr['mfa.error.name_too_long'].replace('{max}', '64'))).toBeInTheDocument() + expect(fake.auth.mfa.enroll).not.toHaveBeenCalled() + await user.clear(field) + await user.type(field, 'b'.repeat(64)) + await user.click(screen.getByRole('button', { name: fr['mfa.enrol.continue'] })) + expect(fake.auth.mfa.enroll).toHaveBeenCalledWith({ factorType: 'totp', friendlyName: 'b'.repeat(64) }) + }) + it('a second factor at aal1 steps up first, then enrols again', async () => { const user = userEvent.setup() setMfa(fake, [fakeFactor({ id: 'f-1' })]) diff --git a/apps/app/tests/unit/lib.dates.test.ts b/apps/app/tests/unit/lib.dates.test.ts index 7cefaa75..ef3ee214 100644 --- a/apps/app/tests/unit/lib.dates.test.ts +++ b/apps/app/tests/unit/lib.dates.test.ts @@ -1,5 +1,12 @@ -import { describe, it, expect } from 'vitest' -import { formatDate, todayIso, nowIso } from '@/lib/dates' +import { afterAll, beforeAll, describe, it, expect } from 'vitest' +import { + endOfParisDayIso, + formatDate, + nowIso, + parisDateIso, + parisTomorrowIso, + todayIso, +} from '@/lib/dates' describe('formatDate fr', () => { it('formats "2026-05-18" as "18 mai 2026"', () => { @@ -38,3 +45,47 @@ describe('nowIso', () => { expect(nowIso()).toMatch(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/) }) }) + +// A zone west and a zone east of Paris: the Paris rules never follow the device. +describe.each(['America/Los_Angeles', 'Pacific/Kiritimati'])( + 'Paris days under the device zone %s', + (zone) => { + const previous = process.env.TZ + beforeAll(() => { + process.env.TZ = zone + expect(Intl.DateTimeFormat().resolvedOptions().timeZone).toBe(zone) + }) + afterAll(() => { + if (previous === undefined) delete process.env.TZ + else process.env.TZ = previous + }) + + it.each([ + ['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'], + ])('endOfParisDayIso(%s) is %s', (day, instant) => { + expect(endOfParisDayIso(day)).toBe(instant) + }) + + it('refuses an impossible or malformed day', () => { + expect(() => endOfParisDayIso('2026-02-30')).toThrow() + expect(() => endOfParisDayIso('2026-1-5')).toThrow() + }) + + it('parisDateIso reads the Paris date', () => { + expect(parisDateIso(new Date('2026-11-02T23:30:00Z'))).toBe('2026-11-03') + }) + + it('parisTomorrowIso is the next Paris calendar day, DST included', () => { + expect(parisTomorrowIso(new Date('2026-03-28T22:30:00Z'))).toBe( + '2026-03-29', + ) + expect(parisTomorrowIso(new Date('2026-03-28T23:30:00Z'))).toBe( + '2026-03-30', + ) + }) + }, +) diff --git a/apps/app/tests/unit/routes.admin.test.tsx b/apps/app/tests/unit/routes.admin.test.tsx index 58468ade..7d8eabdd 100644 --- a/apps/app/tests/unit/routes.admin.test.tsx +++ b/apps/app/tests/unit/routes.admin.test.tsx @@ -33,7 +33,7 @@ import AdminSheetRoute from '@/app/routes/app/admin/AdminSheetRoute' import AdminSpeciesRoute from '@/app/routes/app/admin/AdminSpeciesRoute' import AdminAccessRoute from '@/app/routes/app/admin/AdminAccessRoute' import { NO_FILTER, filterSheets } from '@/admin/filters' -import { parseGrant, proposeSlug } from '@/admin/validation' +import { proposeSlug } from '@/admin/validation' import { setCoreRuntime } from '@/core/runtime' import { useAuthStore } from '@/state/authStore' import { useLocaleStore } from '@/state/localeStore' @@ -489,7 +489,7 @@ describe('Rights (A0, §5.2)', () => { await user.click(screen.getByRole('button', { name: 'Attribuer' })) expect(screen.getByText(fr['admin.access.error.kind'])).toBeInTheDocument() - await user.click(screen.getByLabelText('Relecteur, relectrice')) + await user.click(screen.getByLabelText('Relecteur ou relectrice')) await user.type(screen.getByLabelText('Motif'), 'Relecture') await user.type(screen.getByLabelText(/Échéance/), '2020-01-01') await user.click(screen.getByRole('button', { name: 'Attribuer' })) @@ -582,39 +582,6 @@ describe('Rights (A0, §5.2)', () => { ) expect(await screen.findByText('Droit révoqué.')).toBeInTheDocument() }) - - it('parseGrant: the reader needs no note; the expiry is the end of the chosen day', () => { - const parsed = parseGrant( - { - kind: 'catalog_reader', - reason: ' Lecture ', - verification_note: '', - expires_on: '2026-12-31', - }, - '2026-11-02', - ) - expect(parsed).toEqual({ - ok: true, - value: { - kind: 'catalog_reader', - reason: 'Lecture', - expires_at: new Date('2026-12-31T23:59:59').toISOString(), - }, - }) - const today = parseGrant( - { - kind: 'catalog_reader', - reason: 'x', - verification_note: '', - expires_on: '2026-11-02', - }, - '2026-11-02', - ) - expect(today).toMatchObject({ - ok: false, - errors: { expires_on: 'admin.access.error.expiry' }, - }) - }) }) describe('Official sheets list (H1)', () => { diff --git a/docs/development/V1-2_ANATOMICAL_SHEETS.md b/docs/development/V1-2_ANATOMICAL_SHEETS.md index 361dcc0c..890e1a89 100644 --- a/docs/development/V1-2_ANATOMICAL_SHEETS.md +++ b/docs/development/V1-2_ANATOMICAL_SHEETS.md @@ -137,7 +137,7 @@ sources. | Groupe de revue, groupe lu | Review group, group read | review group, acknowledgment (§6.3) | | Accès au catalogue | Catalogue access | right `catalog_reader` (§5.3) | | Habilitation | Permission (owner, 2026-11-02, BDR-097: `capability` stays the technical term) | right `sheet_editor`, `sheet_reviewer`, `sheet_publisher` (§5.2) | -| Relecteur, relectrice | Reviewer | `sheet_reviewer` | +| Relecteur ou relectrice | Reviewer | `sheet_reviewer` | | Éditeur de fiches | Sheet editor | `sheet_editor` | | Responsable de publication | Publisher | `sheet_publisher` | | À confirmer, relu, hérité, non relu | To confirm, reviewed, inherited, not reviewed | `to_confirm`, `reviewed`, `inherited` | diff --git a/supabase/migrations/20261102100000_sheet_admin_reads.sql b/supabase/migrations/20261102100000_sheet_admin_reads.sql index 81dd9df8..3dabf4bb 100644 --- a/supabase/migrations/20261102100000_sheet_admin_reads.sql +++ b/supabase/migrations/20261102100000_sheet_admin_reads.sql @@ -13,8 +13,10 @@ -- rounds, with the names of the people who acted. -- Capability holders at aal2 only (`caller_is_catalog_staff`, the predicate -- of the draft reads); an unknown or forbidden sheet gets one answer. No --- write, no grant, no policy and no rule changes here. Also: `get_sheet_version` --- returns the fingerprint of a deprecated version (§10, BDR-098). +-- table, grant, policy or rule changes here. Also: `get_sheet_version` +-- returns the fingerprint of a deprecated version (§10, BDR-098); and +-- `create_species` / `update_inactive_species` refuse a sort order outside +-- 0..9 999 (owner 2026-11-02), their privileges restated. -- =========================================================================== -- 1. Helpers @@ -247,3 +249,68 @@ grant execute on function public.get_official_sheet_admin(uuid) to authenticated -- Kept by `create or replace`, stated again so this file stands alone. revoke all on function public.get_sheet_version(uuid) from public, anon, service_role; grant execute on function public.get_sheet_version(uuid) to authenticated; + +-- =========================================================================== +-- 5. Species order range (owner 2026-11-02) +-- =========================================================================== +-- The M5 bodies, with the sort order bounded 0..9 999 (null keeps today's +-- meaning: the default 100 on creation, the stored value on update). +create or replace function public.create_species(id text, name_fr text, name_en text, sort_order integer default 100) +returns text +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_actor uuid := private.require_capability('sheet_editor'); +begin + if create_species.id is null or create_species.id !~ '^[a-z0-9][a-z0-9_-]{0,63}$' or create_species.id = 'other' + or char_length(name_fr) not between 1 and 80 or char_length(name_en) not between 1 and 80 + or (create_species.sort_order is not null and create_species.sort_order not between 0 and 9999) then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + if exists (select 1 from public.species s where s.id = create_species.id) then + raise exception 'species.exists' using errcode = 'P0001'; + end if; + perform private.consume_catalog_write_budget(v_actor); + insert into public.species (id, name_fr, name_en, sort_order, active) + values (create_species.id, name_fr, name_en, coalesce(sort_order, 100), false); + perform private.log_event(v_actor, 'species.created', 'species', null, null, null, + jsonb_build_object('id', create_species.id)); + return create_species.id; +end; +$$; + +create or replace function public.update_inactive_species(id text, name_fr text, name_en text, sort_order integer) +returns text +language plpgsql +volatile +security definer +set search_path = '' +as $$ +#variable_conflict use_column +declare + v_actor uuid := private.require_capability('sheet_editor'); +begin + if char_length(name_fr) not between 1 and 80 or char_length(name_en) not between 1 and 80 + or (update_inactive_species.sort_order is not null and update_inactive_species.sort_order not between 0 and 9999) then + raise exception 'invalid_input' using errcode = 'P0001'; + end if; + perform 1 from public.species s where s.id = update_inactive_species.id and not s.active for update; + if not found then + raise exception 'species.not_inactive' using errcode = 'P0001'; + end if; + perform private.consume_catalog_write_budget(v_actor); + update public.species s set name_fr = update_inactive_species.name_fr, name_en = update_inactive_species.name_en, + sort_order = coalesce(update_inactive_species.sort_order, s.sort_order) where s.id = update_inactive_species.id; + perform private.log_event(v_actor, 'species.updated', 'species', null, null, null, jsonb_build_object('id', update_inactive_species.id)); + return update_inactive_species.id; +end; +$$; + +revoke all on function public.create_species(text, text, text, integer) from public, anon, service_role; +revoke all on function public.update_inactive_species(text, text, text, integer) from public, anon, service_role; +grant execute on function public.create_species(text, text, text, integer) to authenticated; +grant execute on function public.update_inactive_species(text, text, text, integer) to authenticated; diff --git a/supabase/tests/015_catalog_access.sql b/supabase/tests/015_catalog_access.sql index 9b5a3ca7..2257c4ee 100644 --- a/supabase/tests/015_catalog_access.sql +++ b/supabase/tests/015_catalog_access.sql @@ -5,7 +5,7 @@ -- proven in packages/supabase/tests/sandbox/sheets.sandbox.ts, the seed owner's -- factors on an upgraded stack in seed-owner-mfa.sandbox.ts. begin; -select plan(37); +select plan(44); insert into auth.users (id, email, email_confirmed_at) values ('d0000000-0000-0000-0000-000000000001', 'own@t.local', now()), -- owner @@ -190,6 +190,57 @@ select ok(not private.grant_active('d0000000-0000-0000-0000-00000000000c','catal set local role authenticated; select pg_temp.act('d0000000-0000-0000-0000-000000000001', 'd1000000-0000-0000-0000-000000000001', 'aal2'); +-- Expiry instants (owner 2026-11-02, Europe/Paris end of day): the stored +-- instant is the same whatever the session TimeZone; the DST days are future +-- ones the RPC accepts. One fresh account per grant (one active row per kind). +reset role; +insert into auth.users (id, email, email_confirmed_at) values + ('d0000000-0000-0000-0000-0000000000b1', 'tz1@t.local', now()), + ('d0000000-0000-0000-0000-0000000000b2', 'tz2@t.local', now()), + ('d0000000-0000-0000-0000-0000000000b3', 'tz3@t.local', now()), + ('d0000000-0000-0000-0000-0000000000b4', 'tz4@t.local', now()), + ('d0000000-0000-0000-0000-0000000000b5', 'st1@t.local', now()), + ('d0000000-0000-0000-0000-0000000000b6', 'st2@t.local', now()), + ('d0000000-0000-0000-0000-0000000000b7', 'st3@t.local', now()); +set local role authenticated; +select pg_temp.act('d0000000-0000-0000-0000-000000000001', 'd1000000-0000-0000-0000-000000000001', 'aal2'); +set local timezone to 'UTC'; +select public.grant_catalog_right('d0000000-0000-0000-0000-0000000000b1', 'catalog_reader', 'tz', null, '2027-03-28T23:59:59.999+02:00'); +select public.grant_catalog_right('d0000000-0000-0000-0000-0000000000b2', 'catalog_reader', 'tz', null, '2027-10-31T23:59:59.999+01:00'); +set local timezone to 'America/New_York'; +select public.grant_catalog_right('d0000000-0000-0000-0000-0000000000b3', 'catalog_reader', 'tz', null, '2027-03-28T23:59:59.999+02:00'); +select public.grant_catalog_right('d0000000-0000-0000-0000-0000000000b4', 'catalog_reader', 'tz', null, '2027-10-31T23:59:59.999+01:00'); +reset role; +select is((select string_agg(to_char(expires_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS'), ',' order by user_id) + from public.anatomical_catalog_grants where user_id in ( + 'd0000000-0000-0000-0000-0000000000b1', 'd0000000-0000-0000-0000-0000000000b2')), + '2027-03-28T21:59:59.999,2027-10-31T22:59:59.999', 'the 2027 DST days store the same instants under UTC'); +select is((select string_agg(to_char(expires_at at time zone 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.MS'), ',' order by user_id) + from public.anatomical_catalog_grants where user_id in ( + 'd0000000-0000-0000-0000-0000000000b3', 'd0000000-0000-0000-0000-0000000000b4')), + '2027-03-28T21:59:59.999,2027-10-31T22:59:59.999', 'the 2027 DST days store the same instants under America/New_York'); +select is((select count(*)::int from public.anatomical_catalog_grants where user_id in ( + 'd0000000-0000-0000-0000-0000000000b1', 'd0000000-0000-0000-0000-0000000000b2') + and expires_at in ('2027-03-28T21:59:59.999Z'::timestamptz, '2027-10-31T22:59:59.999Z'::timestamptz)), 2, + 'the stored instants equal the Paris end of day (summer +02:00, winter +01:00)'); +set local timezone to 'UTC'; +-- The list state at each boundary (direct inserts with an earlier granted_at). +insert into public.anatomical_catalog_grants (user_id, grant_kind, reason, granted_by, granted_at, expires_at) values + ('d0000000-0000-0000-0000-0000000000b5', 'catalog_reader', 'x', 'd0000000-0000-0000-0000-000000000001', now() - interval '2 days', now() - interval '1 minute'), + ('d0000000-0000-0000-0000-0000000000b6', 'catalog_reader', 'x', 'd0000000-0000-0000-0000-000000000001', now() - interval '2 days', now() + interval '1 minute'), + ('d0000000-0000-0000-0000-0000000000b7', 'catalog_reader', 'x', 'd0000000-0000-0000-0000-000000000001', now() - interval '2 days', now() + interval '30 days 1 minute'); +set local role authenticated; +select pg_temp.act('d0000000-0000-0000-0000-000000000001', 'd1000000-0000-0000-0000-000000000001', 'aal2'); +create function pg_temp.grant_state(p_user uuid) returns text language sql stable as $$ + select (e ->> 'state') || '/' || (e ->> 'effective') + from jsonb_array_elements(public.list_catalog_grants()) e where (e ->> 'user_id')::uuid = p_user; +$$; +grant execute on function pg_temp.grant_state(uuid) to authenticated; +select is(pg_temp.grant_state('d0000000-0000-0000-0000-0000000000b5'), 'expired/false', 'expiry 1 minute ago: expired, not effective'); +select is(pg_temp.grant_state('d0000000-0000-0000-0000-0000000000b6'), 'expiring/true', 'expiry in 1 minute: expiring, effective'); +select is(pg_temp.grant_state('d0000000-0000-0000-0000-0000000000b7'), 'active/true', 'expiry in 30 days and 1 minute: active, effective'); +select is(pg_temp.grant_state('d0000000-0000-0000-0000-0000000000b3') like 'expiring/%' or pg_temp.grant_state('d0000000-0000-0000-0000-0000000000b3') like 'active/%', true, 'a future DST-day grant is listed live'); + -- only the owner (aal2) lists grants select ok((select jsonb_typeof(public.list_catalog_grants()) = 'array'), 'owner lists grants'); select pg_temp.act('d0000000-0000-0000-0000-00000000000a', 'd1000000-0000-0000-0000-00000000000a', 'aal2'); diff --git a/supabase/tests/022_sheet_admin_reads.sql b/supabase/tests/022_sheet_admin_reads.sql index 3395e509..482f16c3 100644 --- a/supabase/tests/022_sheet_admin_reads.sql +++ b/supabase/tests/022_sheet_admin_reads.sql @@ -4,7 +4,7 @@ -- unknown, deleted, personal or forbidden sheet gets one answer. Fixtures are -- scoped to the ids created here. begin; -select plan(43); +select plan(60); -- Accounts. O owner, A admin, E admin + editor, V reviewer, P admin + -- publisher, R reader, N no right. Every one has a verified factor and a live @@ -193,5 +193,37 @@ select is((select string_agg(p.provolatile::text, ',' order by p.proname) from p where n.nspname = 'public' and p.proname in ('list_official_sheets_admin', 'get_official_sheet_admin')), 's,s', 'both reads are stable: no write path'); +-- ============ Species order range (owner 2026-11-02) ============ +-- The stored order of an inactive species, read with the owner's rights (RLS hides inactive rows). +create function pg_temp.stored_order(p_id text) returns text language plpgsql security definer as $$ +begin + return (select sort_order::text from public.species where id = p_id); +end $$; +grant execute on function pg_temp.stored_order(text) to authenticated; +select pg_temp.as_user('E', 'aal2'); +select is(pg_temp.val($$ select public.create_species('m22-neg', 'Négatif', 'Negative', -1) $$), 'P0001 invalid_input', 'create_species: -1 refused'); +select is(pg_temp.val($$ select public.create_species('m22-big', 'Grand', 'Big', 10000) $$), 'P0001 invalid_input', 'create_species: 10 000 refused'); +select is(pg_temp.val($$ select public.create_species('m22-zero', 'Zéro', 'Zero', 0) $$), 'm22-zero', 'create_species: 0 accepted'); +select is(pg_temp.val($$ select public.create_species('m22-max', 'Max', 'Max', 9999) $$), 'm22-max', 'create_species: 9 999 accepted'); +select is(pg_temp.val($$ select public.create_species('m22-null', 'Nul', 'Null', null) $$), 'm22-null', 'create_species: null accepted'); +select is(coalesce(pg_temp.stored_order('m22-neg'), 'none') || '/' || coalesce(pg_temp.stored_order('m22-big'), 'none'), 'none/none', 'create_species: refused orders store nothing'); +select is(pg_temp.stored_order('m22-zero') || ',' || pg_temp.stored_order('m22-max') || ',' || pg_temp.stored_order('m22-null'), + '0,9999,100', 'create_species: stored orders, null keeps the default 100'); +select is(pg_temp.val($$ select public.update_inactive_species('m22-zero', 'Zéro', 'Zero', -1) $$), 'P0001 invalid_input', 'update_inactive_species: -1 refused'); +select is(pg_temp.val($$ select public.update_inactive_species('m22-zero', 'Zéro', 'Zero', 10000) $$), 'P0001 invalid_input', 'update_inactive_species: 10 000 refused'); +select is(pg_temp.val($$ select public.update_inactive_species('m22-zero', 'Zéro', 'Zero', 9999) $$), 'm22-zero', 'update_inactive_species: 9 999 accepted'); +select is(pg_temp.stored_order('m22-zero'), '9999', 'update_inactive_species: 9 999 stored'); +select is(pg_temp.val($$ select public.update_inactive_species('m22-zero', 'Zéro', 'Zero', 0) $$), 'm22-zero', 'update_inactive_species: 0 accepted'); +select is(pg_temp.stored_order('m22-zero'), '0', 'update_inactive_species: 0 stored'); +select is(pg_temp.val($$ select public.update_inactive_species('m22-max', 'Max', 'Max', null) $$), 'm22-max', 'update_inactive_species: null accepted'); +select is(pg_temp.stored_order('m22-max'), '9999', 'update_inactive_species: null keeps the stored order'); +select pg_temp.as_user('V', 'aal2'); +select is(pg_temp.val($$ select public.create_species('m22-rev', 'Rev', 'Rev', 5) $$), '42501 rights.capability', 'create_species: a reviewer is still refused'); +reset role; +select is((select string_agg(p.prosecdef::text || '/' || (p.proconfig = array['search_path=""'])::text, ',' order by p.proname) from pg_proc p + join pg_namespace n on n.oid = p.pronamespace + where n.nspname = 'public' and p.proname in ('create_species', 'update_inactive_species')), + 'true/true,true/true', 'both species RPCs: security definer, empty search_path'); + select * from finish(); rollback;