Console d'administration séparée, joignable seulement par Tailscale
deploy / deploy (push) Successful in 48s
deploy / deploy (push) Successful in 48s
- Site à part (admin/, build:admin → dist-admin/), jamais dans l'app publique : tableau de bord, membres (suspendre / réactiver), avis (retirer), commentaires (supprimer), journal. Motif obligatoire. Session en mémoire seulement, 1 h maximum, déconnexion après 15 min d'inactivité. - Connexion : mot de passe + code de double authentification obligatoire (jeton aal2). - Fonction Edge « admin » : secret X-Admin-Gate (ajouté par nginx sur le VPS, sinon 404), jeton aal2, liste admin.admins ; accès à la base par connexion directe. Alertes e-mail si SMTP_PASSWORD est configuré. - Schéma « admin » (20261130150000, appliqué) non exposé par l'API : admins, journal en ajout seulement (modification, suppression et vidage refusés), fonctions de la console. - nginx : admin.conf sur 127.0.0.1:8081 (CSP stricte, sans cache, noindex), relais vers la fonction avec le secret lu dans /etc/nginx/bobinoo-admin-gate.conf (hors dépôt). Publié par « tailscale serve ». - Déploiement : build de la console et copie dans chaque release. Guide : docs/admin.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
21 files changed
+1372
-8
No files matched your search
@@ -0,0 +1,177 @@
|
||||
import { LogOut, ShieldCheck } from 'lucide-react'
|
||||
import { useCallback, useEffect, useRef, useState, type FormEvent } from 'react'
|
||||
import { ApiError, call, type Card } from './api'
|
||||
import { AuthError, expiresAt, signIn, signOut, verifyCode } from './auth'
|
||||
import { Comments, Dashboard, Journal, Members, Reviews } from './screens'
|
||||
|
||||
/** Déconnexion automatique après 15 minutes sans toucher à la console. */
|
||||
const IDLE_MS = 15 * 60_000
|
||||
|
||||
type Tab = 'dashboard' | 'members' | 'reviews' | 'comments' | 'journal'
|
||||
const TABS: { id: Tab; label: string }[] = [
|
||||
{ id: 'dashboard', label: 'Tableau de bord' },
|
||||
{ id: 'members', label: 'Membres' },
|
||||
{ id: 'reviews', label: 'Avis' },
|
||||
{ id: 'comments', label: 'Commentaires' },
|
||||
{ id: 'journal', label: 'Journal' },
|
||||
]
|
||||
|
||||
export default function App() {
|
||||
// Jeton gardé en mémoire seulement : recharger la page déconnecte
|
||||
const [session, setSession] = useState<{ token: string; me: Card }>()
|
||||
const [notice, setNotice] = useState<string>()
|
||||
|
||||
const logout = useCallback((why?: string) => {
|
||||
setSession((s) => {
|
||||
if (s) void signOut(s.token)
|
||||
return undefined
|
||||
})
|
||||
setNotice(why)
|
||||
}, [])
|
||||
|
||||
// Fin de validité du jeton, inactivité : retour à l'écran de connexion
|
||||
useEffect(() => {
|
||||
if (!session) return
|
||||
const end = window.setTimeout(() => logout('Session terminée (1 h) : reconnecte-toi.'), Math.max(0, expiresAt(session.token) - Date.now() - 30_000))
|
||||
let idle = window.setTimeout(() => logout('Déconnecté après 15 minutes sans activité.'), IDLE_MS)
|
||||
const touch = () => {
|
||||
window.clearTimeout(idle)
|
||||
idle = window.setTimeout(() => logout('Déconnecté après 15 minutes sans activité.'), IDLE_MS)
|
||||
}
|
||||
for (const ev of ['pointerdown', 'keydown'] as const) window.addEventListener(ev, touch)
|
||||
return () => {
|
||||
window.clearTimeout(end)
|
||||
window.clearTimeout(idle)
|
||||
for (const ev of ['pointerdown', 'keydown'] as const) window.removeEventListener(ev, touch)
|
||||
}
|
||||
}, [session, logout])
|
||||
|
||||
if (!session) return <Login notice={notice} onReady={(token, me) => (setNotice(undefined), setSession({ token, me }))} />
|
||||
return <Console token={session.token} me={session.me} onLogout={logout} />
|
||||
}
|
||||
|
||||
function Login({ notice, onReady }: { notice?: string; onReady: (token: string, me: Card) => void }) {
|
||||
const [step, setStep] = useState<{ token: string; factorId: string }>()
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [code, setCode] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const codeRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (busy) return
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
try {
|
||||
if (!step) {
|
||||
const r = await signIn(email, password)
|
||||
setPassword('')
|
||||
if (!r.factorId) {
|
||||
await signOut(r.token)
|
||||
throw new AuthError("Ce compte n'a pas la double authentification. Active-la d'abord dans l'app (Réglages → Mon compte), elle est obligatoire ici.")
|
||||
}
|
||||
setStep({ token: r.token, factorId: r.factorId })
|
||||
setTimeout(() => codeRef.current?.focus(), 0)
|
||||
} else {
|
||||
const token = await verifyCode(step.token, step.factorId, code.replace(/\s/g, ''))
|
||||
const me = await call<Card>(token, 'hello')
|
||||
onReady(token, me)
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof AuthError || err instanceof ApiError ? err.message : 'Erreur inattendue.')
|
||||
if (step) setCode('')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex min-h-dvh max-w-sm flex-col justify-center px-5 py-10">
|
||||
<div className="flex items-center gap-2 text-accent">
|
||||
<ShieldCheck size={22} />
|
||||
<span className="text-sm font-semibold uppercase tracking-wider">Console</span>
|
||||
</div>
|
||||
<h1 className="mt-2 text-3xl font-bold">Bobinoo</h1>
|
||||
<p className="mt-2 text-sm text-ink-3">Accès réservé. Chaque connexion est inscrite au journal et signalée par e-mail.</p>
|
||||
{notice && <p className="mt-5 border-s-2 border-accent ps-3 text-sm text-ink-2">{notice}</p>}
|
||||
<form onSubmit={submit} className="mt-7 space-y-3">
|
||||
{!step ? (
|
||||
<>
|
||||
<input className="field" type="email" autoComplete="username" placeholder="E-mail" value={email} onChange={(e) => setEmail(e.target.value)} required />
|
||||
<input className="field" type="password" autoComplete="current-password" placeholder="Mot de passe" value={password} onChange={(e) => setPassword(e.target.value)} required />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm text-ink-2">Code à 6 chiffres de ton application d'authentification :</p>
|
||||
<input
|
||||
ref={codeRef}
|
||||
className="field text-center text-2xl tracking-[0.4em]"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
pattern="[0-9 ]{6,7}"
|
||||
maxLength={7}
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{error && <p className="text-sm text-danger">{error}</p>}
|
||||
<button className="btn btn-primary w-full" disabled={busy}>
|
||||
{busy ? '…' : step ? 'Valider le code' : 'Continuer'}
|
||||
</button>
|
||||
{step && (
|
||||
<button type="button" className="btn w-full text-ink-3" onClick={() => (void signOut(step.token), setStep(undefined), setCode(''))}>
|
||||
Annuler
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
function Console({ token, me, onLogout }: { token: string; me: Card; onLogout: (why?: string) => void }) {
|
||||
const [tab, setTab] = useState<Tab>('dashboard')
|
||||
// Erreur de session renvoyée par le serveur : retour à la connexion
|
||||
const onAuthError = useCallback(
|
||||
(e: unknown) => {
|
||||
if (e instanceof ApiError && (e.status === 401 || e.status === 403)) onLogout(e.message)
|
||||
},
|
||||
[onLogout],
|
||||
)
|
||||
const props = { token, onAuthError }
|
||||
return (
|
||||
<div className="mx-auto min-h-dvh max-w-5xl px-4 pb-16 sm:px-6">
|
||||
<header className="sticky top-0 z-10 -mx-4 border-b border-line bg-bg px-4 pt-[max(0.75rem,env(safe-area-inset-top))] sm:-mx-6 sm:px-6">
|
||||
<div className="flex items-center gap-3">
|
||||
<ShieldCheck size={20} className="text-accent" />
|
||||
<span className="font-bold">Console Bobinoo</span>
|
||||
<span className="ms-auto truncate text-sm text-ink-3">@{me.username}</span>
|
||||
<button onClick={() => onLogout('Déconnecté.')} className="grid size-9 place-items-center text-ink-2 active:text-ink" aria-label="Se déconnecter">
|
||||
<LogOut size={18} />
|
||||
</button>
|
||||
</div>
|
||||
<nav className="-mx-1 mt-2 flex gap-1 overflow-x-auto pb-2">
|
||||
{TABS.map((t) => (
|
||||
<button
|
||||
key={t.id}
|
||||
onClick={() => setTab(t.id)}
|
||||
className={`shrink-0 rounded-md px-3 py-1.5 text-sm font-medium ${tab === t.id ? 'bg-surface-2 text-ink' : 'text-ink-3'}`}
|
||||
>
|
||||
{t.label}
|
||||
</button>
|
||||
))}
|
||||
</nav>
|
||||
</header>
|
||||
<main className="pt-5">
|
||||
{tab === 'dashboard' && <Dashboard {...props} />}
|
||||
{tab === 'members' && <Members {...props} meId={me.id} />}
|
||||
{tab === 'reviews' && <Reviews {...props} />}
|
||||
{tab === 'comments' && <Comments {...props} />}
|
||||
{tab === 'journal' && <Journal {...props} />}
|
||||
</main>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
/** Appels à la fonction serveur « admin », par le relais nginx du VPS (qui ajoute le secret). */
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
const MESSAGES: Record<string, string> = {
|
||||
session: 'Session expirée : reconnecte-toi.',
|
||||
mfa: 'Code de double authentification requis : reconnecte-toi.',
|
||||
interdit: "Ce compte n'est pas administrateur.",
|
||||
'trop de requêtes': 'Trop de requêtes, patiente une minute.',
|
||||
}
|
||||
|
||||
export async function call<T>(token: string, action: string, params: Record<string, unknown> = {}): Promise<T> {
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch('/api/admin', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify({ action, ...params }),
|
||||
credentials: 'omit',
|
||||
cache: 'no-store',
|
||||
})
|
||||
} catch {
|
||||
throw new ApiError(0, 'Serveur injoignable (VPN Tailscale activé ?).')
|
||||
}
|
||||
if (res.status === 404) throw new ApiError(404, 'La console n\'est pas reliée au serveur (secret du VPS absent ou différent).')
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string }
|
||||
if (!res.ok) throw new ApiError(res.status, MESSAGES[body.error ?? ''] ?? body.error ?? `Erreur ${res.status}`)
|
||||
return body as T
|
||||
}
|
||||
|
||||
export interface Card {
|
||||
id: string
|
||||
username: string
|
||||
display_name: string
|
||||
avatar_url?: string | null
|
||||
suspended: boolean
|
||||
}
|
||||
export interface Overview {
|
||||
members: number
|
||||
members_week: number
|
||||
active_week: number
|
||||
suspended: number
|
||||
private: number
|
||||
items: number
|
||||
reviews: number
|
||||
comments: number
|
||||
follows: number
|
||||
shared_lists: number
|
||||
latest: (Card & { created_at: string })[]
|
||||
}
|
||||
export interface Member extends Card {
|
||||
email: string
|
||||
created_at: string
|
||||
last_sign_in_at?: string | null
|
||||
items: number
|
||||
mfa: boolean
|
||||
is_admin: boolean
|
||||
}
|
||||
export interface Review {
|
||||
user: Card
|
||||
item_id: string
|
||||
title: string
|
||||
rating?: number | null
|
||||
spoiler: boolean
|
||||
notes: string
|
||||
updated_at: string
|
||||
comments: number
|
||||
}
|
||||
export interface Comment {
|
||||
id: number
|
||||
body: string
|
||||
created_at: string
|
||||
user: Card
|
||||
author: Card
|
||||
title?: string | null
|
||||
}
|
||||
export interface JournalEntry {
|
||||
id: number
|
||||
at: string
|
||||
action: string
|
||||
target?: string | null
|
||||
details: Record<string, unknown>
|
||||
admin?: string | null
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
/**
|
||||
* Connexion à la console : mot de passe, puis code de double authentification (obligatoire).
|
||||
* La session ne vit qu'en mémoire : recharger ou fermer l'onglet déconnecte. Pas de jeton de
|
||||
* renouvellement gardé : au bout d'une heure (durée du jeton Supabase), il faut se reconnecter.
|
||||
*/
|
||||
const URL = (import.meta.env.VITE_SUPABASE_URL ?? '').replace(/\/+$/, '')
|
||||
const KEY = import.meta.env.VITE_SUPABASE_ANON_KEY ?? ''
|
||||
|
||||
export class AuthError extends Error {}
|
||||
|
||||
type Json = Record<string, unknown>
|
||||
|
||||
async function gotrue(path: string, opts: { token?: string; body?: Json } = {}): Promise<Json> {
|
||||
if (!URL || !KEY) throw new AuthError('Console mal construite : adresse Supabase manquante.')
|
||||
const res = await fetch(`${URL}/auth/v1${path}`, {
|
||||
method: opts.body ? 'POST' : 'GET',
|
||||
headers: { apikey: KEY, 'Content-Type': 'application/json', ...(opts.token ? { Authorization: `Bearer ${opts.token}` } : {}) },
|
||||
body: opts.body ? JSON.stringify(opts.body) : undefined,
|
||||
credentials: 'omit',
|
||||
cache: 'no-store',
|
||||
})
|
||||
const data = (await res.json().catch(() => ({}))) as Json
|
||||
if (!res.ok) {
|
||||
const code = String(data.error_code ?? data.error ?? '')
|
||||
if (res.status === 400 && /invalid_credentials|invalid_grant/.test(code)) throw new AuthError('E-mail ou mot de passe incorrect.')
|
||||
if (res.status === 429) throw new AuthError('Trop de tentatives. Réessaie dans quelques minutes.')
|
||||
if (/mfa_verification_failed|invalid.*code/i.test(code + String(data.msg ?? ''))) throw new AuthError('Code incorrect ou expiré.')
|
||||
throw new AuthError(String(data.msg ?? data.message ?? data.error_description ?? `Erreur ${res.status}`))
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
/** Étape 1 : e-mail et mot de passe. Renvoie le facteur TOTP à valider (absent : pas de double authentification). */
|
||||
export async function signIn(email: string, password: string): Promise<{ token: string; factorId?: string }> {
|
||||
const d = await gotrue('/token?grant_type=password', { body: { email: email.trim().toLowerCase(), password } })
|
||||
const user = (d.user ?? {}) as { factors?: { id?: string; factor_type?: string; status?: string }[] }
|
||||
const factor = (user.factors ?? []).find((f) => f.factor_type === 'totp' && f.status === 'verified')
|
||||
if (typeof d.access_token !== 'string') throw new AuthError('Réponse inattendue du serveur.')
|
||||
return { token: d.access_token, factorId: factor?.id }
|
||||
}
|
||||
|
||||
/** Étape 2 : code à 6 chiffres → jeton « aal2 », le seul accepté par la console. */
|
||||
export async function verifyCode(token: string, factorId: string, code: string): Promise<string> {
|
||||
const ch = await gotrue(`/factors/${encodeURIComponent(factorId)}/challenge`, { token, body: {} })
|
||||
if (typeof ch.id !== 'string') throw new AuthError('Réponse inattendue du serveur.')
|
||||
const v = await gotrue(`/factors/${encodeURIComponent(factorId)}/verify`, { token, body: { challenge_id: ch.id, code } })
|
||||
if (typeof v.access_token !== 'string') throw new AuthError('Réponse inattendue du serveur.')
|
||||
return v.access_token
|
||||
}
|
||||
|
||||
/** Déconnexion : la session est aussi fermée côté serveur. */
|
||||
export async function signOut(token: string): Promise<void> {
|
||||
await gotrue('/logout?scope=local', { token, body: {} }).catch(() => {})
|
||||
}
|
||||
|
||||
/** Fin de validité du jeton (ms). */
|
||||
export function expiresAt(token: string): number {
|
||||
try {
|
||||
const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')
|
||||
const { exp } = JSON.parse(atob(part.padEnd(part.length + ((4 - (part.length % 4)) % 4), '='))) as { exp?: number }
|
||||
return typeof exp === 'number' ? exp * 1000 : Date.now()
|
||||
} catch {
|
||||
return Date.now()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import '@fontsource-variable/epilogue/wght.css'
|
||||
import './styles.css'
|
||||
import App from './App'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,358 @@
|
||||
import { Search } from 'lucide-react'
|
||||
import { useCallback, useEffect, useState, type FormEvent, type ReactNode } from 'react'
|
||||
import { ApiError, call, type Card, type Comment, type JournalEntry, type Member, type Overview, type Review } from './api'
|
||||
|
||||
interface ScreenProps {
|
||||
token: string
|
||||
onAuthError: (e: unknown) => void
|
||||
}
|
||||
|
||||
const dateTime = new Intl.DateTimeFormat('fr-FR', { dateStyle: 'medium', timeStyle: 'short' })
|
||||
const date = new Intl.DateTimeFormat('fr-FR', { dateStyle: 'medium' })
|
||||
const fmt = (d?: string | null, withTime = true) => (d ? (withTime ? dateTime : date).format(new Date(d)) : '—')
|
||||
|
||||
/** Liste paginée (« Voir plus ») avec recherche facultative. */
|
||||
function usePaged<T>(token: string, action: string, onAuthError: (e: unknown) => void, q = '') {
|
||||
const [rows, setRows] = useState<T[]>()
|
||||
const [more, setMore] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const [tick, setTick] = useState(0)
|
||||
const load = useCallback(
|
||||
async (offset: number) => {
|
||||
setError(undefined)
|
||||
try {
|
||||
const page = await call<T[]>(token, action, { q, offset })
|
||||
setRows((prev) => (offset ? [...(prev ?? []), ...page] : page))
|
||||
setMore(page.length >= (action === 'members' || action === 'journal' ? 50 : 30))
|
||||
} catch (e) {
|
||||
onAuthError(e)
|
||||
setError(e instanceof ApiError ? e.message : 'Erreur inattendue.')
|
||||
}
|
||||
},
|
||||
[token, action, q, onAuthError],
|
||||
)
|
||||
useEffect(() => {
|
||||
void load(0)
|
||||
}, [load, tick])
|
||||
return { rows, more, error, loadMore: () => void load(rows?.length ?? 0), reload: () => setTick((n) => n + 1) }
|
||||
}
|
||||
|
||||
function Avatar({ card }: { card: Card }) {
|
||||
return card.avatar_url ? (
|
||||
<img src={card.avatar_url} alt="" className="size-9 shrink-0 rounded-full border border-line object-cover" />
|
||||
) : (
|
||||
<span className="grid size-9 shrink-0 place-items-center rounded-full border border-line bg-surface-2 text-sm font-bold text-ink-3">
|
||||
{(card.display_name || card.username || '?').charAt(0).toUpperCase()}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
function Who({ card, sub }: { card: Card; sub?: ReactNode }) {
|
||||
return (
|
||||
<div className="flex min-w-0 items-center gap-3">
|
||||
<Avatar card={card} />
|
||||
<div className="min-w-0">
|
||||
<p className="truncate font-semibold">
|
||||
{card.display_name || card.username} <span className="font-normal text-ink-3">@{card.username}</span>
|
||||
{card.suspended && <span className="badge ms-2 border-danger text-danger">suspendu</span>}
|
||||
</p>
|
||||
{sub && <p className="truncate text-xs text-ink-3">{sub}</p>}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function Status({ rows, error, empty }: { rows?: unknown[]; error?: string; empty: string }) {
|
||||
if (error) return <p className="py-6 text-sm text-danger">{error}</p>
|
||||
if (!rows) return <p className="py-6 text-sm text-ink-3">Chargement…</p>
|
||||
if (!rows.length) return <p className="py-6 text-sm text-ink-3">{empty}</p>
|
||||
return null
|
||||
}
|
||||
|
||||
function SearchBar({ placeholder, onSearch }: { placeholder: string; onSearch: (q: string) => void }) {
|
||||
const [value, setValue] = useState('')
|
||||
const submit = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
onSearch(value.trim())
|
||||
}
|
||||
return (
|
||||
<form onSubmit={submit} className="mb-4 flex gap-2">
|
||||
<input className="field" placeholder={placeholder} value={value} onChange={(e) => setValue(e.target.value.slice(0, 60))} enterKeyHint="search" />
|
||||
<button className="btn btn-ghost px-3" aria-label="Rechercher">
|
||||
<Search size={18} />
|
||||
</button>
|
||||
</form>
|
||||
)
|
||||
}
|
||||
|
||||
function MoreButton({ more, onMore }: { more: boolean; onMore: () => void }) {
|
||||
return more ? (
|
||||
<button onClick={onMore} className="btn btn-ghost mt-4 w-full">
|
||||
Voir plus
|
||||
</button>
|
||||
) : null
|
||||
}
|
||||
|
||||
/** Action sensible : motif obligatoire (inscrit au journal et dans l'e-mail d'alerte). */
|
||||
function Confirm({
|
||||
title,
|
||||
text,
|
||||
confirmLabel,
|
||||
onConfirm,
|
||||
onClose,
|
||||
}: {
|
||||
title: string
|
||||
text: ReactNode
|
||||
confirmLabel: string
|
||||
onConfirm: (reason: string) => Promise<void>
|
||||
onClose: () => void
|
||||
}) {
|
||||
const [reason, setReason] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (busy) return
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
try {
|
||||
await onConfirm(reason.trim())
|
||||
onClose()
|
||||
} catch (err) {
|
||||
setError(err instanceof ApiError ? err.message : 'Erreur inattendue.')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-end justify-center bg-scrim p-0 sm:items-center sm:p-4" onClick={onClose}>
|
||||
<form onSubmit={submit} onClick={(e) => e.stopPropagation()} className="w-full max-w-md border border-line-strong bg-surface p-5 pb-[max(1.25rem,env(safe-area-inset-bottom))]">
|
||||
<h2 className="text-lg font-bold">{title}</h2>
|
||||
<div className="mt-2 text-sm text-ink-2">{text}</div>
|
||||
<label className="mt-4 block text-sm font-medium">Motif (gardé dans le journal)</label>
|
||||
<textarea className="field mt-1.5 min-h-20" value={reason} onChange={(e) => setReason(e.target.value.slice(0, 500))} required minLength={3} autoFocus />
|
||||
{error && <p className="mt-2 text-sm text-danger">{error}</p>}
|
||||
<div className="mt-4 flex gap-2">
|
||||
<button type="button" onClick={onClose} className="btn btn-ghost flex-1">
|
||||
Annuler
|
||||
</button>
|
||||
<button className="btn btn-danger flex-1" disabled={busy || reason.trim().length < 3}>
|
||||
{busy ? '…' : confirmLabel}
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Tableau de bord ───
|
||||
|
||||
export function Dashboard({ token, onAuthError }: ScreenProps) {
|
||||
const [data, setData] = useState<Overview>()
|
||||
const [error, setError] = useState<string>()
|
||||
useEffect(() => {
|
||||
call<Overview>(token, 'overview')
|
||||
.then(setData)
|
||||
.catch((e) => {
|
||||
onAuthError(e)
|
||||
setError(e instanceof ApiError ? e.message : 'Erreur inattendue.')
|
||||
})
|
||||
}, [token, onAuthError])
|
||||
if (error) return <p className="text-sm text-danger">{error}</p>
|
||||
if (!data) return <p className="text-sm text-ink-3">Chargement…</p>
|
||||
const tiles: [string, number, string?][] = [
|
||||
['Membres', data.members, `+${data.members_week} cette semaine`],
|
||||
['Actifs (7 j)', data.active_week],
|
||||
['Fiches', data.items],
|
||||
['Avis', data.reviews],
|
||||
['Commentaires', data.comments],
|
||||
['Abonnements', data.follows],
|
||||
['Listes partagées', data.shared_lists],
|
||||
['Comptes privés', data.private],
|
||||
['Suspendus', data.suspended],
|
||||
]
|
||||
return (
|
||||
<>
|
||||
<div className="grid grid-cols-2 gap-3 sm:grid-cols-3">
|
||||
{tiles.map(([label, n, sub]) => (
|
||||
<div key={label} className="border border-line bg-surface p-4">
|
||||
<p className="text-xs text-ink-3">{label}</p>
|
||||
<p className="mt-1 text-2xl font-bold tabular-nums">{n.toLocaleString('fr-FR')}</p>
|
||||
{sub && <p className="mt-0.5 text-xs text-accent">{sub}</p>}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
<h2 className="mt-8 mb-3 font-bold">Dernières inscriptions</h2>
|
||||
<ul className="divide-y divide-line border-y border-line">
|
||||
{data.latest.map((c) => (
|
||||
<li key={c.id} className="py-3">
|
||||
<Who card={c} sub={`Inscrit le ${fmt(c.created_at)}`} />
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Membres ───
|
||||
|
||||
export function Members({ token, onAuthError, meId }: ScreenProps & { meId: string }) {
|
||||
const [q, setQ] = useState('')
|
||||
const { rows, more, error, loadMore, reload } = usePaged<Member>(token, 'members', onAuthError, q)
|
||||
const [target, setTarget] = useState<Member>()
|
||||
return (
|
||||
<>
|
||||
<SearchBar placeholder="Pseudo, nom ou e-mail" onSearch={setQ} />
|
||||
<Status rows={rows} error={error} empty="Aucun membre trouvé." />
|
||||
<ul className="divide-y divide-line border-y border-line">
|
||||
{rows?.map((m) => (
|
||||
<li key={m.id} className="flex flex-wrap items-center gap-3 py-3">
|
||||
<div className="min-w-0 flex-1">
|
||||
<Who card={m} sub={m.email} />
|
||||
<div className="mt-2 flex flex-wrap items-center gap-1.5 ps-12 text-xs text-ink-3">
|
||||
<span>
|
||||
Inscrit le {fmt(m.created_at, false)} · vu le {fmt(m.last_sign_in_at, false)} · {m.items} fiche{m.items > 1 ? 's' : ''}
|
||||
</span>
|
||||
{m.mfa && <span className="badge">2FA</span>}
|
||||
{m.is_admin && <span className="badge border-accent text-accent">admin</span>}
|
||||
</div>
|
||||
</div>
|
||||
{m.id !== meId && (
|
||||
<button onClick={() => setTarget(m)} className={`btn ${m.suspended ? 'btn-ghost' : 'btn-danger'} py-1.5`}>
|
||||
{m.suspended ? 'Réactiver' : 'Suspendre'}
|
||||
</button>
|
||||
)}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<MoreButton more={more} onMore={loadMore} />
|
||||
{target && (
|
||||
<Confirm
|
||||
title={target.suspended ? `Réactiver @${target.username} ?` : `Suspendre @${target.username} ?`}
|
||||
text={
|
||||
target.suspended
|
||||
? 'Son profil, ses avis et ses commentaires redeviennent visibles.'
|
||||
: 'Son profil, ses avis et ses commentaires deviennent invisibles pour les autres, et il ne peut plus s\'abonner ni réagir. Il garde sa bibliothèque.'
|
||||
}
|
||||
confirmLabel={target.suspended ? 'Réactiver' : 'Suspendre'}
|
||||
onConfirm={async (reason) => {
|
||||
await call(token, 'suspend', { user: target.id, value: !target.suspended, reason })
|
||||
reload()
|
||||
}}
|
||||
onClose={() => setTarget(undefined)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Avis ───
|
||||
|
||||
export function Reviews({ token, onAuthError }: ScreenProps) {
|
||||
const [q, setQ] = useState('')
|
||||
const { rows, more, error, loadMore, reload } = usePaged<Review>(token, 'reviews', onAuthError, q)
|
||||
const [target, setTarget] = useState<Review>()
|
||||
return (
|
||||
<>
|
||||
<SearchBar placeholder="Pseudo ou titre" onSearch={setQ} />
|
||||
<Status rows={rows} error={error} empty="Aucun avis." />
|
||||
<ul className="space-y-3">
|
||||
{rows?.map((r) => (
|
||||
<li key={r.user.id + r.item_id} className="border border-line bg-surface p-4">
|
||||
<Who card={r.user} sub={`${r.title} · ${fmt(r.updated_at)}`} />
|
||||
<p className="mt-3 text-sm text-ink-2">
|
||||
{typeof r.rating === 'number' && <span className="me-2 font-semibold text-accent">★ {(r.rating / 2).toLocaleString('fr-FR')}/5</span>}
|
||||
{r.spoiler && <span className="badge me-2">spoiler</span>}
|
||||
{r.comments > 0 && <span className="text-xs text-ink-3">{r.comments} commentaire{r.comments > 1 ? 's' : ''}</span>}
|
||||
</p>
|
||||
<p className="mt-2 whitespace-pre-line text-sm leading-relaxed">{r.notes}</p>
|
||||
<button onClick={() => setTarget(r)} className="btn btn-danger mt-3 py-1.5">
|
||||
Retirer l'avis
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<MoreButton more={more} onMore={loadMore} />
|
||||
{target && (
|
||||
<Confirm
|
||||
title={`Retirer l'avis de @${target.user.username} ?`}
|
||||
text={`Sur « ${target.title} ». La note et la fiche restent ; seul le texte est retiré (une copie est gardée dans le journal). Les commentaires sous l'avis sont supprimés.`}
|
||||
confirmLabel="Retirer"
|
||||
onConfirm={async (reason) => {
|
||||
await call(token, 'clear_review', { user: target.user.id, item: target.item_id, reason })
|
||||
reload()
|
||||
}}
|
||||
onClose={() => setTarget(undefined)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Commentaires ───
|
||||
|
||||
export function Comments({ token, onAuthError }: ScreenProps) {
|
||||
const { rows, more, error, loadMore, reload } = usePaged<Comment>(token, 'comments', onAuthError)
|
||||
const [target, setTarget] = useState<Comment>()
|
||||
return (
|
||||
<>
|
||||
<Status rows={rows} error={error} empty="Aucun commentaire." />
|
||||
<ul className="space-y-3">
|
||||
{rows?.map((c) => (
|
||||
<li key={c.id} className="border border-line bg-surface p-4">
|
||||
<Who card={c.user} sub={`Sur l'avis de @${c.author.username}${c.title ? ` (« ${c.title} »)` : ''} · ${fmt(c.created_at)}`} />
|
||||
<p className="mt-3 whitespace-pre-line text-sm leading-relaxed">{c.body}</p>
|
||||
<button onClick={() => setTarget(c)} className="btn btn-danger mt-3 py-1.5">
|
||||
Supprimer
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<MoreButton more={more} onMore={loadMore} />
|
||||
{target && (
|
||||
<Confirm
|
||||
title={`Supprimer le commentaire de @${target.user.username} ?`}
|
||||
text="Une copie du texte est gardée dans le journal."
|
||||
confirmLabel="Supprimer"
|
||||
onConfirm={async (reason) => {
|
||||
await call(token, 'delete_comment', { id: target.id, reason })
|
||||
reload()
|
||||
}}
|
||||
onClose={() => setTarget(undefined)}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
// ─── Journal ───
|
||||
|
||||
export function Journal({ token, onAuthError }: ScreenProps) {
|
||||
const { rows, more, error, loadMore } = usePaged<JournalEntry>(token, 'journal', onAuthError)
|
||||
return (
|
||||
<>
|
||||
<p className="mb-4 text-sm text-ink-3">Connexions et actions de la console. Rien ne peut y être modifié ni effacé.</p>
|
||||
<Status rows={rows} error={error} empty="Journal vide." />
|
||||
<ul className="divide-y divide-line border-y border-line">
|
||||
{rows?.map((j) => (
|
||||
<li key={j.id} className="py-3 text-sm">
|
||||
<p>
|
||||
<span className="font-semibold">{j.action}</span>
|
||||
{j.target && <span className="text-ink-2"> · {j.target}</span>}
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-ink-3">
|
||||
{fmt(j.at)}
|
||||
{j.admin && ` · par @${j.admin}`}
|
||||
</p>
|
||||
{Object.entries(j.details).map(([k, v]) => (
|
||||
<p key={k} className="mt-1 break-words text-xs text-ink-2">
|
||||
<span className="text-ink-3">{k} :</span> {String(v)}
|
||||
</p>
|
||||
))}
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<MoreButton more={more} onMore={loadMore} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
@import 'tailwindcss';
|
||||
|
||||
/* Mêmes couleurs que l'app (thème sombre), coins droits */
|
||||
@theme {
|
||||
--font-sans: 'Epilogue Variable', 'Epilogue', ui-sans-serif, system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
|
||||
--color-bg: #090909;
|
||||
--color-surface: #121212;
|
||||
--color-surface-2: #1b1b1b;
|
||||
--color-line: #2b2b2b;
|
||||
--color-line-strong: #424242;
|
||||
--color-ink: #f2f2f0;
|
||||
--color-ink-2: #c4c4c4;
|
||||
--color-ink-3: #989898;
|
||||
--color-accent: #53bfb6;
|
||||
--color-on-accent: #062b28;
|
||||
--color-danger: #f97066;
|
||||
--color-on-danger: #2b0a06;
|
||||
--color-scrim: rgb(0 0 0 / 0.7);
|
||||
--radius-sm: 0.125rem;
|
||||
--radius-md: 0.125rem;
|
||||
--radius-lg: 0.125rem;
|
||||
--radius-xl: 0.125rem;
|
||||
}
|
||||
|
||||
@layer base {
|
||||
html {
|
||||
background: var(--color-bg);
|
||||
color: var(--color-ink);
|
||||
color-scheme: dark;
|
||||
}
|
||||
body {
|
||||
font-family: var(--font-sans);
|
||||
-webkit-font-smoothing: antialiased;
|
||||
-webkit-tap-highlight-color: transparent;
|
||||
}
|
||||
button,
|
||||
a {
|
||||
touch-action: manipulation;
|
||||
}
|
||||
}
|
||||
|
||||
@layer components {
|
||||
.field {
|
||||
@apply w-full rounded-md border border-line-strong bg-surface px-3 py-2.5 text-ink outline-none placeholder:text-ink-3 focus:border-accent;
|
||||
}
|
||||
.btn {
|
||||
@apply inline-flex items-center justify-center gap-2 rounded-md px-4 py-2.5 text-sm font-semibold transition-colors disabled:opacity-50;
|
||||
}
|
||||
.btn-primary {
|
||||
@apply bg-accent text-on-accent active:opacity-80;
|
||||
}
|
||||
.btn-ghost {
|
||||
@apply border border-line-strong text-ink active:bg-surface-2;
|
||||
}
|
||||
.btn-danger {
|
||||
@apply border border-danger text-danger active:bg-danger active:text-on-danger;
|
||||
}
|
||||
.badge {
|
||||
@apply inline-flex items-center rounded-sm border border-line-strong px-1.5 py-0.5 text-[11px] font-medium text-ink-2;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user