fix(app): grant expiry ends the chosen day in Paris; species order 0..9999 (V1-2.5 L2)

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.
This commit is contained in:
bchanot committed 2026-11-02 21:29:33 +01:00
1 parent 4111efa1d1
commit 51225cacf6
17 files changed
+437 -61

No files matched your search

+7 -2
View File
@@ -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 } : {}),
})
}
+15 -9
View File
@@ -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<GrantFields, keyof GrantFormValues> {
return parse(grantSchema(today), values)
}
+2 -1
View File
@@ -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'
+2 -2
View File
@@ -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 }) {
<Input
id="grant-expiry"
type="date"
min={localDateIso(new Date(Date.now() + 86_400_000))}
min={parisTomorrowIso()}
value={values.expires_on}
onChange={(e) => set('expires_on')(e.target.value)}
aria-invalid={Boolean(errors.expires_on)}
+1 -1
View File
@@ -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.',
+1 -1
View File
@@ -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',
+68
View File
@@ -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<string, number> = {}
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()
}
@@ -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()
})
},
)
@@ -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' })])
+53 -2
View File
@@ -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',
)
})
},
)
+2 -35
View File
@@ -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)', () => {