Audit : corrections de bugs, sécurité et performances (sans changement de fonctionnement)

Données et synchro
- Import « remplacer » atomique (plus de bibliothèque vidée si l'écriture échoue).
- Deux onglets sur le même compte : mise à jour croisée, file d'envoi partagée sans perte.
- Réception : une modification locale faite pendant la synchro n'est plus écrasée ; une seule transaction.
- Envoi : file vidée paquet par paquet, fiche invalide isolée (quota : gardée en attente), taille en octets réels,
  délai proportionnel à la taille ; grandes affiches décodées sans fetch (bloqué par la CSP).
- Plus d'écriture dans la base d'un autre compte après déconnexion ; base fermée proprement (iOS).
- Revisionnages journalisés à part (rewatchLog) : les défis ne sous-estiment plus le 1er visionnage ;
  décocher des épisodes un autre jour ne gonfle plus les défis.

Comptes et social
- Renouvellement de session : plus de déconnexion de tous les onglets avec un jeton déjà utilisé,
  plus de rafale de renouvellements, déconnexion qui révoque bien la session serveur.
- Délais maximum sur les appels réseau, écran blanc évité au retour de Google.
- Abonnés/abonnements au-delà de 50, pagination du fil et des profils, fil hors-ligne, listes bloquées.
- Code mort retiré (CommentsSheet et options jamais utilisées).

Interface et logique
- Toast qui ne disparaissait plus, focus sur « Annuler » dans les confirmations, Échap pendant la saisie IME.
- Demi-étoile en arabe, flèches RTL, fonds d'overlay en jeton de thème, couleur du thème étoilé.
- Séries en cours sans total connu : les nouveaux épisodes se cochent à nouveau ; épisodes spéciaux ignorés.
- Catalogue, accueil et calendrier plus rapides sur les grosses bibliothèques.

Sources externes
- Proxy TMDB : les 18 langues acceptées (9 étaient refusées), 429 transmis, délais, paramètres durcis.
- Contenus adultes AniList filtrés des recommandations, cache d'import borné, imports plus sûrs.

Serveur (migration 20261122140000_audit_hardening.sql, déjà appliquée en ligne)
- Fonctions admin et « comptes suspendus » versionnées ; blocage effectif ; avis robustes ;
  fiches supprimées vidées ; comptes suspendus sans abonnement ni réaction ; objets morts supprimés.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
Claude committed 2026-11-24 15:11:01 +00:00
1 parent 0683f77e54
commit 459101bbf8
73 files changed
+2074 -2162

No files matched your search

+5 -3
View File
@@ -55,8 +55,9 @@ function OverviewTab() {
if (error) return <EmptyState title={t('admin.loadError')} />
if (!data) return <Spinner />
const max = data.signups_by_day.reduce((m, d) => Math.max(m, d.n), 1)
const days = data.signups_by_day
// Réponse inattendue du serveur (ancienne version) : pas de graphique plutôt qu'un plantage
const days = Array.isArray(data.signups_by_day) ? data.signups_by_day : []
const max = days.reduce((m, d) => Math.max(m, Number(d?.n) || 0), 1)
return (
<div className="mt-6">
@@ -150,7 +151,8 @@ function UsersTab() {
} catch {
/* on garde la liste en l'état */
} finally {
if (reqId.current === id) setLoadingMore(false)
// Toujours remis à zéro (sinon, recherche changée entre-temps : bouton bloqué pour de bon)
setLoadingMore(false)
}
}
+23 -8
View File
@@ -1,7 +1,7 @@
import { genreLabel, subtypeLabel } from '../lib/genres'
import { locale, t } from '../i18n'
import { CheckSquare, Hash, Heart, Search, SlidersHorizontal, X } from 'lucide-react'
import { useEffect, useMemo, useState } from 'react'
import { useDeferredValue, useEffect, useMemo, useState } from 'react'
import { StatusDot } from '../components/Badges'
import JournalView from '../components/JournalView'
import ListsView from '../components/ListsView'
@@ -77,8 +77,18 @@ export default function CatalogPage({ onOpen, onAdd }: Props) {
return next
})
// Texte de recherche de chaque fiche, normalisé une fois par bibliothèque (et non à chaque touche)
const haystacks = useMemo(() => {
const map = new Map<string, string>()
for (const i of items)
map.set(i.id, normalizeText([i.title, i.originalTitle, i.subtype, i.subtype && subtypeLabel(i.subtype), i.platform, ...i.genres, ...i.genres.map(genreLabel), ...(i.tags ?? [])].filter(Boolean).join(' ')))
return map
}, [items])
// La saisie reste fluide : le filtrage suit la frappe sans la bloquer
const deferredQuery = useDeferredValue(query)
const results = useMemo(() => {
const q = normalizeText(query)
const q = normalizeText(deferredQuery)
const filtered = items.filter((i) => {
if (types.size && !types.has(i.type)) return false
if (status && i.status !== status) return false
@@ -86,10 +96,7 @@ export default function CatalogPage({ onOpen, onAdd }: Props) {
if (minRating && (i.rating ?? 0) < minRating) return false
if (favOnly && !i.favorite) return false
if (tag && !hasTag(i, tag)) return false
if (q) {
const haystack = normalizeText([i.title, i.originalTitle, i.subtype, i.subtype && subtypeLabel(i.subtype), i.platform, ...i.genres, ...i.genres.map(genreLabel), ...(i.tags ?? [])].filter(Boolean).join(' '))
if (!haystack.includes(q)) return false
}
if (q && !haystacks.get(i.id)?.includes(q)) return false
return true
})
const sorted = [...filtered]
@@ -98,7 +105,7 @@ export default function CatalogPage({ onOpen, onAdd }: Props) {
else if (sort === 'watched')
sorted.sort((a, b) => (b.endDate ?? b.startDate ?? '').localeCompare(a.endDate ?? a.startDate ?? ''))
return sorted
}, [items, query, types, status, genre, minRating, favOnly, tag, sort])
}, [items, haystacks, deferredQuery, types, status, genre, minRating, favOnly, tag, sort])
const activeAdvanced = (genre ? 1 : 0) + (minRating ? 1 : 0) + (favOnly ? 1 : 0) + (tag ? 1 : 0)
const anyFilter = query || types.size || status || activeAdvanced
@@ -164,7 +171,15 @@ export default function CatalogPage({ onOpen, onAdd }: Props) {
{t('select.count', { count: selected.length })}
</p>
<button
onClick={() => setSelection(allShownSelected ? new Set() : new Set([...selection, ...results.map((i) => i.id)]))}
onClick={() => {
// « Tout désélectionner » ne retire que les fiches affichées (les autres, masquées par un filtre, restent choisies)
const shown = results.map((i) => i.id)
if (allShownSelected) {
const next = new Set(selection)
for (const id of shown) next.delete(id)
setSelection(next)
} else setSelection(new Set([...selection, ...shown]))
}}
className="chip py-1 text-xs"
disabled={!results.length}
>
+22 -11
View File
@@ -73,7 +73,9 @@ export default function HomePage({ onOpen, onAdd, onNavigate, onRoulette, onCale
const info = next[i.id]
if (!info) return []
const patch: Partial<MediaItem> = {}
if (i.status !== 'termine' && info.aired > (i.episodesTotal ?? 0)) patch.episodesTotal = info.aired
// Total relevé aux épisodes sortis. Aussi pour une fiche « Terminé » dont la série continue :
// sinon, une fois à jour, les nouveaux épisodes ne pouvaient plus jamais être cochés (le statut ne change pas ici)
if ((i.status !== 'termine' || !info.ended) && info.aired > (i.episodesTotal ?? 0)) patch.episodesTotal = info.aired
// Découpage par saison (nouvelle saison annoncée, ou fiche ajoutée avant le suivi par saison)
if (info.seasonSizes && info.seasonSizes.join() !== (i.seasons ?? []).join()) patch.seasons = info.seasonSizes
if (info.backdrop && !i.backdrop) patch.backdrop = info.backdrop
@@ -112,7 +114,8 @@ export default function HomePage({ onOpen, onAdd, onNavigate, onRoulette, onCale
}, [])
const soon = useMemo(() => {
const today = todayISO()
const d = new Date(Date.now() + 7 * 86400000)
const now = new Date()
const d = new Date(now.getFullYear(), now.getMonth(), now.getDate() + 7)
const end = `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
return calendarEvents(items).filter((e) => e.date >= today && e.date <= end).length
// eslint-disable-next-line react-hooks/exhaustive-deps
@@ -122,18 +125,26 @@ export default function HomePage({ onOpen, onAdd, onNavigate, onRoulette, onCale
const airing = useMemo(() => loadAiring(), [cacheVersion]) // eslint-disable-line react-hooks/exhaustive-deps
// Pendant la vérification, une série suivie dont on ne connaît pas encore les sorties reste masquée :
// sinon elle s'affichait puis disparaissait quelques secondes après (une fois vue « à jour »).
const unknownWhileChecking = (i: MediaItem) => (checkingAiring || loading) && !airing[i.id] && trackable([i]).length > 0
// Listes de l'accueil recalculées seulement quand la bibliothèque ou les sorties changent
const hideUnknown = checkingAiring || loading
// Un revisionnage en cours apparaît comme une série en cours (avec sa propre progression)
const inProgress = items.map(progressView).filter((i) => i.status === 'en_cours' && !isCaughtUp(i, airing) && !unknownWhileChecking(i))
const inProgress = useMemo(
() => items.map(progressView).filter((i) => i.status === 'en_cours' && !isCaughtUp(i, airing) && !(hideUnknown && !airing[i.id] && trackable([i]).length > 0)),
[items, airing, hideUnknown],
)
// Bannière : ce que je regarde en ce moment (le plus récemment touché), sinon le prochain « à voir »
const byRecent = [...inProgress].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt))
const byRecent = useMemo(() => [...inProgress].sort((a, b) => b.updatedAt.localeCompare(a.updatedAt)), [inProgress])
const firstToWatch = items.find((i) => i.status === 'a_voir')
const featured = (byRecent.length ? byRecent.slice(0, 8) : firstToWatch ? [firstToWatch] : [])
const toWatch = items.filter((i) => i.status === 'a_voir').slice(0, 12)
const recent = items
.filter((i) => i.status === 'termine')
.sort((a, b) => (b.endDate ?? b.updatedAt).localeCompare(a.endDate ?? a.updatedAt))
.slice(0, 12)
const toWatch = useMemo(() => items.filter((i) => i.status === 'a_voir').slice(0, 12), [items])
const recent = useMemo(
() =>
items
.filter((i) => i.status === 'termine')
.sort((a, b) => (b.endDate ?? b.updatedAt).localeCompare(a.endDate ?? a.updatedAt))
.slice(0, 12),
[items],
)
const seeAll = <LinkArrow onClick={() => onNavigate('catalog')}>{t('home.seeAll')}</LinkArrow>
@@ -199,7 +210,7 @@ export default function HomePage({ onOpen, onAdd, onNavigate, onRoulette, onCale
{stats.toWatch ? t('home.rouletteHint', { count: stats.toWatch }) : t('home.rouletteHintAll')}
</span>
</span>
<span className="text-accent">→</span>
<span className="inline-block text-accent rtl:-scale-x-100">→</span>
</button>
+43 -18
View File
@@ -1,7 +1,7 @@
import { t } from '../i18n'
import { LanguageSelect } from '../i18n/react'
import { Check, Download, ExternalLink, Eye, EyeOff, HardDrive, Import, ShieldCheck, Smartphone, Trash2, Upload, UserX } from 'lucide-react'
import { useEffect, useRef, useState, type ReactNode } from 'react'
import { useEffect, useId, useRef, useState, type ReactNode } from 'react'
import AccountSection from '../components/AccountSection'
import ConfirmDialog from '../components/ConfirmDialog'
import ImportWizard from '../components/ImportWizard'
@@ -16,6 +16,7 @@ import { isAdmin } from '../lib/cloud/admin'
import { cx } from '../lib/utils'
import { useEscape } from '../lib/escape'
import { useBackToClose } from '../lib/backNav'
import { useScrollLock } from '../lib/scrollLock'
import { useMedia } from '../store'
import { mergeImportedSettings } from '../lib/challenges'
import { BugReportRow } from '../components/moderation/BugReport'
@@ -31,11 +32,17 @@ function Row({ icon, title, hint, onClick, danger }: { icon: ReactNode; title: s
<span className="block font-medium">{title}</span>
{hint && <span className="mt-0.5 block text-xs text-ink-3">{hint}</span>}
</span>
<span className={danger ? 'text-accent' : 'text-ink-3'}>→</span>
<span className={cx('inline-block rtl:-scale-x-100', danger ? 'text-accent' : 'text-ink-3')}>→</span>
</button>
)
}
/** Bloque le défilement de la page tant qu'il est affiché (fenêtre d'installation). */
function ScrollLock() {
useScrollLock()
return null
}
export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void }) {
const { items, settings, updateSettings, importItems, clearAll, lists, mergeLists, account, guest, requestAccount } = useMedia()
const { canInstall, installed, install } = useInstallPrompt()
@@ -43,8 +50,16 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void
// Une seule vérification par connexion (et pas à chaque changement d'état de la synchro)
const signedIn = !!account
useEffect(() => {
if (signedIn) void isAdmin().then(setAdmin)
// Réponse arrivée après une déconnexion (ou la fermeture de la page) : ignorée
let alive = true
if (signedIn)
void isAdmin()
.then((ok) => alive && setAdmin(ok))
.catch(() => alive && setAdmin(false))
else setAdmin(false)
return () => {
alive = false
}
}, [signedIn])
const adminHint = alertsSummary(useAdminAlerts(admin))
const fileRef = useRef<HTMLInputElement>(null)
@@ -120,14 +135,18 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void
const confirmImport = async (mode: 'merge' | 'replace') => {
if (!pending) return
setConfirm(null)
await importItems(pending.items, mode)
if (pending.settings) updateSettings(mode === 'merge' ? mergeImportedSettings(pending.settings, settings) : pending.settings)
if (pending.lists) mergeLists(pending.lists, mode)
setMessage({
kind: 'ok',
text: pending.skipped ? t('settings.importedSkipped', { n: pending.items.length, skipped: pending.skipped }) : t('settings.imported', { count: pending.items.length }),
})
setPending(undefined)
try {
await importItems(pending.items, mode)
if (pending.settings) updateSettings(mode === 'merge' ? mergeImportedSettings(pending.settings, settings) : pending.settings)
if (pending.lists) mergeLists(pending.lists, mode)
setMessage({
kind: 'ok',
text: pending.skipped ? t('settings.importedSkipped', { n: pending.items.length, skipped: pending.skipped }) : t('settings.imported', { count: pending.items.length }),
})
setPending(undefined)
} catch (e) {
setMessage({ kind: 'error', text: (e as Error).message })
}
}
const onDeleteAccount = async () => {
@@ -144,14 +163,19 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void
const onReset = async () => {
setConfirm(null)
await clearAll()
setMessage({ kind: 'ok', text: t('settings.cleared') })
try {
await clearAll()
setMessage({ kind: 'ok', text: t('settings.cleared') })
} catch (e) {
setMessage({ kind: 'error', text: (e as Error).message })
}
}
const [showImport, setShowImport] = useState(false)
const [showInstall, setShowInstall] = useState(false)
useEscape(() => setShowInstall(false), showInstall)
useBackToClose(() => setShowInstall(false), showInstall)
const installTitleId = useId()
const platform = detectPlatform()
const doNativeInstall = async () => {
@@ -281,16 +305,17 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void
<button onClick={() => setShowInstall(true)} className="flex w-full items-center gap-3.5 px-4 py-4 text-start transition-colors active:bg-surface-2">
<span className="text-ink-2"><Smartphone size={19} /></span>
<span className="flex-1 font-medium">{t('settings.installApp')}</span>
<span className="text-ink-3">→</span>
<span className="inline-block text-ink-3 rtl:-scale-x-100">→</span>
</button>
)}
</div>
<p className="mt-2.5 text-xs text-ink-3">{t('settings.installHint')}</p>
{showInstall && (
<div className="fixed inset-0 z-[70] flex items-end justify-center bg-black/70 p-4 sm:items-center" onClick={() => setShowInstall(false)}>
<div role="dialog" aria-modal="true" className="sheet-in safe-bottom w-full max-w-sm rounded-3xl border border-line-strong bg-surface p-5" onClick={(e) => e.stopPropagation()}>
<h2 className="flex items-center gap-2 text-lg"><Smartphone size={20} className="text-accent" /> {t('install.title')}</h2>
<div className="fixed inset-0 z-[70] flex items-end justify-center bg-scrim p-4 sm:items-center" onClick={() => setShowInstall(false)}>
<ScrollLock />
<div role="dialog" aria-modal="true" aria-labelledby={installTitleId} className="sheet-in safe-bottom w-full max-w-sm rounded-3xl border border-line-strong bg-surface p-5" onClick={(e) => e.stopPropagation()}>
<h2 id={installTitleId} className="flex items-center gap-2 text-lg"><Smartphone size={20} className="text-accent" /> {t('install.title')}</h2>
<ol className="mt-4 space-y-3">
{t(`install.${platform}`).split('\n').map((step, i) => (
<li key={i} className="flex gap-3 text-sm leading-relaxed text-ink-2">
@@ -353,7 +378,7 @@ export default function SettingsPage({ onOpenAdmin }: { onOpenAdmin: () => void
</p>
{proxy !== 'ok' && proxy !== 'checking' && (
<button onClick={() => void runProxyCheck()} className="mt-2 text-xs font-medium text-ink-3">
{t('settings.recheck')} <span className="text-accent">→</span>
{t('settings.recheck')} <span className="inline-block text-accent rtl:-scale-x-100">→</span>
</button>
)}
</div>
+2 -1
View File
@@ -416,7 +416,8 @@ export function BugsTab({ onChange }: { onChange: () => void }) {
setBusyId(b.id)
try {
await adminSetBugStatus(b.id, s)
setRows((p) => p.map((x) => (x.id === b.id ? { ...x, status: s } : x)))
// Filtre actif : le signalement qui n'y correspond plus quitte la liste (comme au rechargement)
setRows((p) => (filter !== 'all' && filter !== s ? p.filter((x) => x.id !== b.id) : p.map((x) => (x.id === b.id ? { ...x, status: s } : x))))
onChange()
} catch {
/* inchangé */