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
@@ -35,7 +35,7 @@ jobs:
|
||||
env:
|
||||
VITE_SUPABASE_URL: ${{ vars.VITE_SUPABASE_URL }}
|
||||
VITE_SUPABASE_ANON_KEY: ${{ secrets.VITE_SUPABASE_ANON_KEY }}
|
||||
run: cd src && npm run build
|
||||
run: cd src && npm run build && npm run build:admin
|
||||
- name: Publier (atomique, 3 versions conservées)
|
||||
env:
|
||||
SHA: ${{ github.sha }}
|
||||
|
||||
@@ -11,3 +11,4 @@ supabase/.branches
|
||||
_to_delete
|
||||
.env.deploy
|
||||
tsconfig.tsbuildinfo
|
||||
dist-admin
|
||||
@@ -65,7 +65,7 @@ npm run build # build de prod
|
||||
- **Appels aux données publiques** (proxy TMDB, notes Trakt) : `publicFetch` dans `cloud/api.ts`, sans aucun en-tête → pas de pré-requête CORS (un aller-retour au lieu de deux). Limite côté serveur par adresse IP (tmdb 1000, ratings 400 / 10 min). Les données perso restent sur `cloudFetch` (jeton).
|
||||
|
||||
## État (au 28 nov. 2026)
|
||||
- **Toutes les migrations de `supabase/migrations/` sont appliquées en ligne**, jusqu'à `20261130120000_remove_admin.sql` incluse (pg_net supprimée, index des notifications revus, réserve des notes Trakt ; notifications aux abonnés en une requête, quota vérifié une fois par envoi (trigger `*_quota_stmt`), fiche renvoyée à l'identique non réécrite).
|
||||
- **Toutes les migrations de `supabase/migrations/` sont appliquées en ligne**, jusqu'à `20261130150000_admin_console.sql` incluse (pg_net supprimée, index des notifications revus, réserve des notes Trakt ; notifications aux abonnés en une requête, quota vérifié une fois par envoi (trigger `*_quota_stmt`), fiche renvoyée à l'identique non réécrite).
|
||||
- **29 nov. 2026** : 123 avis du compte de Romain contenaient « Réalisation : … » (ancien import, `legacyImport.ts`, corrigé). Lignes retirées en base (la copie de sauvegarde a été supprimée le même jour, correction validée).
|
||||
- **Affiches** : une fiche garde l'**adresse** de l'affiche (TMDB w342 / AniList), jamais l'image copiée en base64 (≈ 50 Ko par fiche, renvoyés à chaque modification et chez les amis). Seule une image choisie dans la galerie (EditDetails, 360 px) est intégrée. Le 29 nov. 2026, 109 affiches intégrées (342 px, copies automatiques) ont été remplacées par leur adresse TMDB : base des fiches 5,95 Mo → 267 Ko.
|
||||
- **Cache (service worker, `vite.config.ts`)** : pré-téléchargement ~1 Mo (app + français). Les 17 autres langues (`assets/locale-*`) et les variantes de police sont mises en cache à la demande (`app-files`). Caches d'exécution : `posters` (petites images TMDB/AniList, 1500), `backdrops` (grandes images, 80) — réponses opaques acceptées (`posters-v2` / `backdrops-v2`, d'un essai abandonné, sont supprimés au lancement par `main.tsx`), `catalog` (fiches TMDB avec `append_to_response`, saisons, personnes, notes Trakt : StaleWhileRevalidate 14 j ; jamais `/tv/123` seul, recherche, sorties ni données perso). React est dans son propre fichier (`react-*.js`), gardé d'une version à l'autre.
|
||||
@@ -79,7 +79,7 @@ npm run build # build de prod
|
||||
- **Compression** : `deploy/nginx/site.conf` active gzip (JS, CSS, JSON, SVG), avec `gzip_http_version 1.0` car le proxy en façade parle HTTP/1.0. Sans ça les fichiers partaient bruts. Mesure Lighthouse mobile (1re visite, 29 nov. 2026) : score 67 → 97, premier affichage 3,9 → 1,8 s, poids 789 → 248 Ko.
|
||||
- **Anciennes icônes installées depuis kino.rdacet.fr / azuucine.rdacet.fr** : ces adresses n'existent plus, l'app installée tourne sur sa copie (plus de mises à jour) et les fonctions serveur la refusent (CORS) → « Impossible de joindre le serveur ». Solution : supprimer l'icône et réinstaller depuis https://bobinoo.org. La date de la version est affichée en bas des Réglages.
|
||||
- **Notifications** (dans l'app, pas de push) : abonnements (`new_follower`, `follow_request`, `unfollow`, `follow_accepted`, trigger `follows_notify`), réaction / commentaire sur mon avis (`reaction`, `review_comment`, triggers sur `review_reactions` / `review_comments`), activité des comptes suivis (`friend_review`, `friend_started`, `friend_added`, trigger `items_notify` → `azuu_notify_followers`, rafales regroupées sur 3 h). Pas de notification pour les listes perso (privées). RPC `get_notifications` (avec le titre lié) / `unread_notifications` / `mark_notifications_read`. La fonction Edge `send-push` répond 410 : à supprimer depuis le tableau de bord Supabase.
|
||||
- **Pas d'administration** (retirée le 30 nov. 2026) : pas d'écran admin, pas de signalements, bugs ou erreurs stockés en base. « Signaler » (avis, commentaire, profil, liste) et « Signaler un bug » ouvrent un e-mail pré-rempli vers contact@bobinoo.org (`mailto` dans `components/moderation/BugReport.tsx`). Modération à la main dans Supabase (voir `docs/database.md`). Après une mise à jour, une ancienne version ouverte qui ne trouve plus un fichier se recharge d'elle-même (`ErrorBoundary`).
|
||||
- **Administration = console séparée** (`docs/admin.md`) : site `admin/` (build `npm run build:admin` → `dist-admin/`), jamais dans l'app publique. Servi par nginx sur `127.0.0.1:8081` (`deploy/nginx/admin.conf`), publié uniquement sur le réseau Tailscale. Appels → fonction Edge `admin` (secret `X-Admin-Gate` ajouté par nginx + jeton aal2 obligatoire + `admin.admins`) → schéma `admin` (non exposé par l'API) par connexion directe. Journal `admin.journal` en ajout seulement. Dans l'app : « Signaler » et « Signaler un bug » ouvrent un e-mail vers contact@bobinoo.org (`components/moderation/BugReport.tsx`). Après une mise à jour, une ancienne version qui ne trouve plus un fichier se recharge d'elle-même (`ErrorBoundary`).
|
||||
- **E-mails du compte** (inscription, mot de passe oublié, changement d'adresse) : envoyés par `contact@bobinoo.org` (OVH Zimbra Starter, SMTP `ssl0.ovh.net:465`, DKIM actif), modèles dans `docs/emails/`. Testé le 30 nov. 2026 : reçu en boîte de réception, lien de confirmation OK. Limite Supabase : 30 e-mails / heure. `contact@bobinoo.org` est aussi l'adresse de contact des pages légales, de « Signaler un bug » et du Play Store.
|
||||
- **Retirés (27-28 nov. 2026)** : défis, couleur d'accent au choix, apparences Nuit/Étoilé, notation sur 10 (les notes restent stockées sur 10 en interne, affichées sur 5 étoiles).
|
||||
- **Double authentification (TOTP)** : optionnelle, Réglages → Mon compte (`src/components/TwoFactor.tsx`, fonctions dans `src/lib/cloud/auth.ts`). À la connexion, `Root.tsx` demande le code (`MfaScreen`) si le compte a un facteur vérifié. Côté serveur, `azuu_mfa_ok()` : règles RLS restrictives « mfa required » (items, lists, settings, follows, profiles, activity), `is_admin()` et `azuu_me_active()` ; les fonctions Edge (`_shared/auth.ts`) refusent un jeton « aal1 » d'un compte protégé.
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="robots" content="noindex, nofollow" />
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<title>Console Bobinoo</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
# Console d'administration (docs/admin.md). Incluse par site.conf, livrée avec chaque release.
|
||||
# Écoute UNIQUEMENT sur la boucle locale du conteneur : Internet ne peut pas la joindre. Tailscale la publie
|
||||
# en HTTPS sur le réseau privé (« tailscale serve --bg --https=443 http://127.0.0.1:8081 »).
|
||||
server {
|
||||
listen 127.0.0.1:8081;
|
||||
server_name _;
|
||||
server_tokens off;
|
||||
|
||||
root /srv/azuucine/current/admin;
|
||||
index index.html;
|
||||
include /etc/nginx/mime.types;
|
||||
|
||||
add_header Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self' data: https://qfgnxonqwldcfdjqhhjz.supabase.co; connect-src 'self' https://qfgnxonqwldcfdjqhhjz.supabase.co; base-uri 'none'; form-action 'self'; frame-ancestors 'none'" always;
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header Referrer-Policy "no-referrer" always;
|
||||
add_header X-Robots-Tag "noindex, nofollow" always;
|
||||
add_header Cache-Control "no-store" always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always;
|
||||
|
||||
# Relais vers la fonction serveur « admin » : nginx ajoute le secret partagé (en-tête X-Admin-Gate).
|
||||
# Le secret est dans /etc/nginx/bobinoo-admin-gate.conf, créé une fois sur le VPS, JAMAIS dans le dépôt :
|
||||
# proxy_set_header X-Admin-Gate "<secret de 64 caractères>";
|
||||
# Fichier absent : la fonction répond 404 (la console affiche « pas reliée au serveur »), le site n'est pas touché.
|
||||
location = /api/admin {
|
||||
limit_except POST { deny all; }
|
||||
client_max_body_size 16k;
|
||||
resolver 1.1.1.1 9.9.9.9 valid=300s ipv6=off;
|
||||
resolver_timeout 5s;
|
||||
set $supabase qfgnxonqwldcfdjqhhjz.supabase.co;
|
||||
proxy_pass https://$supabase/functions/v1/admin;
|
||||
proxy_ssl_server_name on;
|
||||
proxy_ssl_name $supabase;
|
||||
proxy_set_header Host $supabase;
|
||||
proxy_set_header Cookie "";
|
||||
proxy_set_header X-Forwarded-For "";
|
||||
include /etc/nginx/bobinoo-admin-gate*.conf;
|
||||
proxy_read_timeout 30s;
|
||||
}
|
||||
|
||||
location /assets/ {
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri /index.html;
|
||||
}
|
||||
}
|
||||
@@ -44,3 +44,6 @@ server {
|
||||
try_files $uri $uri/ =404;
|
||||
}
|
||||
}
|
||||
|
||||
# Console d'administration : boucle locale seulement (voir admin.conf et docs/admin.md)
|
||||
include /srv/azuucine/current/nginx/admin.conf;
|
||||
@@ -14,6 +14,9 @@ mkdir -p "$REL"
|
||||
cp -a "$SRC" "$REL/dist"
|
||||
node "$HERE/headers-to-nginx.mjs" "$REL/dist/_headers" "$REL/nginx"
|
||||
cp "$HERE/nginx/site.conf" "$REL/nginx/site.conf" # config nginx du site, versionnée dans le dépôt
|
||||
# Console d'administration (docs/admin.md) : servie seulement sur la boucle locale, publiée par Tailscale
|
||||
cp "$HERE/nginx/admin.conf" "$REL/nginx/admin.conf"
|
||||
if [ -f "$SRC/../dist-admin/index.html" ]; then cp -a "$SRC/../dist-admin" "$REL/admin"; else mkdir -p "$REL/admin"; fi
|
||||
|
||||
# bascule atomique : lien relatif temporaire puis rename
|
||||
ln -s "releases/$(basename "$REL")" "$ROOT/current.tmp"
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
# Console d'administration Bobinoo
|
||||
|
||||
Un site à part, **jamais dans l'app publique**, joignable seulement depuis tes appareils.
|
||||
|
||||
## Les verrous, dans l'ordre
|
||||
|
||||
1. **Réseau privé (Tailscale)** : la console n'écoute que sur la boucle locale du conteneur web du VPS (`127.0.0.1:8081`).
|
||||
`tailscale serve` la publie en HTTPS sur ton réseau Tailscale. Depuis Internet, elle n'existe pas.
|
||||
2. **Secret du VPS** : nginx ajoute l'en-tête `X-Admin-Gate` (fichier `/etc/nginx/bobinoo-admin-gate.conf`, hors dépôt)
|
||||
en relayant les appels vers la fonction Edge `admin`. Le même secret est dans Supabase (`ADMIN_GATE_SECRET`).
|
||||
Sans lui, la fonction répond 404, comme si elle n'existait pas.
|
||||
3. **Compte + code** : mot de passe puis code de double authentification, obligatoire (jeton « aal2 »).
|
||||
4. **Liste des admins** : la table `admin.admins`, dans le schéma `admin`. Ce schéma n'est pas exposé par l'API Supabase :
|
||||
ni l'app ni un membre ne peuvent le lire. Seule la fonction Edge y accède, par connexion directe à la base.
|
||||
5. **Journal** : la table `admin.journal` enregistre chaque connexion, chaque refus et chaque action, avec le motif.
|
||||
Le texte retiré y est aussi copié. On peut y ajouter, jamais modifier ni effacer.
|
||||
Un e-mail d'alerte part vers contact@bobinoo.org si `SMTP_PASSWORD` est configuré.
|
||||
|
||||
Session : en mémoire seulement. Recharger la page ou fermer l'onglet déconnecte. Le jeton expire au bout d'une heure, et la
|
||||
console se déconnecte après 15 minutes sans activité.
|
||||
|
||||
## Ce que fait la console
|
||||
|
||||
| Onglet | Contenu |
|
||||
|---|---|
|
||||
| Tableau de bord | Chiffres (membres, actifs, fiches, avis…), dernières inscriptions |
|
||||
| Membres | Recherche par pseudo, nom ou e-mail ; suspendre / réactiver (motif obligatoire) |
|
||||
| Avis | Recherche par pseudo ou titre ; retirer un avis (le texte va au journal) |
|
||||
| Commentaires | Derniers commentaires ; supprimer |
|
||||
| Journal | Connexions et actions |
|
||||
|
||||
## Fichiers
|
||||
|
||||
- `admin/` : le site (React). Construit par `npm run build:admin` dans `dist-admin/`.
|
||||
- `vite.admin.config.ts` : sa configuration de build.
|
||||
- `supabase/functions/admin/` : la fonction Edge, seule porte vers le schéma `admin`.
|
||||
- `supabase/migrations/20261130150000_admin_console.sql` : le schéma `admin` (tables, fonctions, journal verrouillé).
|
||||
- `deploy/nginx/admin.conf` : le serveur de la console (boucle locale, CSP stricte, relais avec secret).
|
||||
Il est inclus par `site.conf`.
|
||||
- `deploy/release.sh` : copie `dist-admin/` dans chaque release (`/srv/azuucine/current/admin`).
|
||||
|
||||
## Installation (une fois)
|
||||
|
||||
1. **Double authentification** sur ton compte : dans l'app, Réglages → Mon compte.
|
||||
2. **Tailscale dans le conteneur web** (`azuucine-web`, celui de nginx), en root :
|
||||
```bash
|
||||
curl -fsSL https://tailscale.com/install.sh | sh
|
||||
# Conteneur LXC sans /dev/net/tun : mode « userspace » (suffisant pour tailscale serve)
|
||||
[ -c /dev/net/tun ] || { sed -i 's|^FLAGS=.*|FLAGS="--tun=userspace-networking"|' /etc/default/tailscaled; systemctl restart tailscaled; }
|
||||
tailscale up --hostname=bobinoo-admin # ouvre le lien affiché et valide avec ton compte Tailscale
|
||||
tailscale serve --bg --https=443 http://127.0.0.1:8081
|
||||
```
|
||||
Dans la console Tailscale (login.tailscale.com → DNS) : activer **MagicDNS** et **HTTPS Certificates**.
|
||||
Adresse de la console : `https://bobinoo-admin.<ton-réseau>.ts.net`.
|
||||
3. **Secret** (dans le même conteneur) :
|
||||
```bash
|
||||
S=$(openssl rand -hex 32)
|
||||
printf 'proxy_set_header X-Admin-Gate "%s";\n' "$S" > /etc/nginx/bobinoo-admin-gate.conf
|
||||
chmod 600 /etc/nginx/bobinoo-admin-gate.conf
|
||||
nginx -t && systemctl reload nginx
|
||||
echo "$S" # à copier UNE fois dans Supabase, puis effacer de l'écran
|
||||
```
|
||||
Dans Supabase → Edge Functions → Secrets : `ADMIN_GATE_SECRET` = ce secret.
|
||||
4. **Alertes par e-mail** (facultatif) : secret Supabase `SMTP_PASSWORD` = mot de passe de contact@bobinoo.org.
|
||||
5. **Tes appareils** : installe l'app Tailscale sur le téléphone et sur l'ordinateur, avec le même compte.
|
||||
|
||||
Vérification depuis le conteneur : `curl -s -X POST http://127.0.0.1:8081/api/admin`
|
||||
- `{"error":"session"}` : tout est relié.
|
||||
- `Not found` : secret absent ou différent entre nginx et Supabase.
|
||||
- `502` : nginx n'arrive pas à joindre Supabase (DNS du conteneur).
|
||||
|
||||
## Gérer
|
||||
|
||||
- **Ajouter un admin**, dans Supabase → SQL Editor :
|
||||
`insert into admin.admins (user_id) select id from public.profiles where username = 'pseudo';`
|
||||
- **Retirer un admin** : `delete from admin.admins where user_id = (select id from public.profiles where username = 'pseudo');`
|
||||
- **Changer le secret** : refaire l'étape 3 (nginx + Supabase).
|
||||
- **Téléphone perdu** :
|
||||
1. Retire l'appareil dans la console Tailscale.
|
||||
2. Change ton mot de passe.
|
||||
3. La double authentification protège le reste.
|
||||
- **Tout couper d'un coup** : supprimer le secret `ADMIN_GATE_SECRET` dans Supabase. La fonction répond alors 404 à tout le monde.
|
||||
+4
-3
@@ -47,10 +47,11 @@ Triggers sur `items` / `lists` / `settings` :
|
||||
| `shared_lists`, `shared_list_members`, `shared_list_items` | Listes partagées entre amis |
|
||||
|
||||
### Modération
|
||||
Pas d'écran d'administration (retiré le 30 nov. 2026).
|
||||
- **Console d'administration séparée** : voir `docs/admin.md`. Elle utilise le schéma `admin` (`admin.admins`, `admin.journal`),
|
||||
qui n'est pas exposé par l'API Supabase.
|
||||
- **Signalements et bugs** : ils arrivent par e-mail à contact@bobinoo.org. Dans l'app, « Signaler » et « Signaler un bug » ouvrent un e-mail pré-rempli.
|
||||
- **Suspendre un compte** : dans Supabase, Table Editor → `profiles`, cocher `suspended`. Le compte devient alors invisible pour les autres.
|
||||
- **Retirer un avis** : vider `data->notes` de la fiche dans `items`.
|
||||
- **Suspendre un compte** : depuis la console (Membres), ou à la main dans Supabase (Table Editor → `profiles` → `suspended`). Le compte devient alors invisible pour les autres.
|
||||
- **Retirer un avis** : depuis la console (Avis).
|
||||
|
||||
### Réserve partagée
|
||||
| Table | Contenu |
|
||||
|
||||
+2
-1
@@ -10,7 +10,8 @@
|
||||
"build": "vite build",
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"audit": "npm audit --omit=dev"
|
||||
"audit": "npm audit --omit=dev",
|
||||
"build:admin": "vite build --config vite.admin.config.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource-variable/epilogue": "5.3.0",
|
||||
|
||||
@@ -13,3 +13,6 @@ verify_jwt = false
|
||||
|
||||
[functions.ratings]
|
||||
verify_jwt = false
|
||||
|
||||
[functions.admin]
|
||||
verify_jwt = false
|
||||
@@ -0,0 +1,204 @@
|
||||
// Console d'administration (docs/admin.md) : seule porte d'entrée vers le schéma « admin » de la base.
|
||||
//
|
||||
// Une requête n'est traitée que si les trois verrous passent, dans cet ordre :
|
||||
// 1. le secret du VPS (en-tête X-Admin-Gate, ajouté par nginx sur le serveur de la console, joignable
|
||||
// seulement par le VPN Tailscale). Sans lui : 404, comme si la fonction n'existait pas ;
|
||||
// 2. un compte connecté AVEC son code de double authentification (jeton « aal2 ») ;
|
||||
// 3. ce compte est dans admin.admins.
|
||||
// Chaque connexion, refus et action est inscrit dans admin.journal (ajout seulement). Les actions
|
||||
// sensibles envoient en plus un e-mail d'alerte à contact@bobinoo.org (si SMTP_PASSWORD est configuré).
|
||||
|
||||
import postgres from 'npm:postgres@3.4.5'
|
||||
|
||||
const GATE = Deno.env.get('ADMIN_GATE_SECRET') ?? ''
|
||||
const SUPABASE_URL = Deno.env.get('SUPABASE_URL') ?? ''
|
||||
const ANON_KEY = Deno.env.get('SUPABASE_ANON_KEY') ?? ''
|
||||
const DB_URL = Deno.env.get('SUPABASE_DB_URL') ?? ''
|
||||
const SMTP_USER = Deno.env.get('SMTP_USER') ?? 'contact@bobinoo.org'
|
||||
const SMTP_PASSWORD = Deno.env.get('SMTP_PASSWORD') ?? ''
|
||||
const ALERT_TO = Deno.env.get('ADMIN_ALERT_TO') ?? 'contact@bobinoo.org'
|
||||
|
||||
const sql = DB_URL ? postgres(DB_URL, { prepare: false, max: 2, idle_timeout: 20, connect_timeout: 10 }) : null
|
||||
|
||||
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
|
||||
const ITEM_ID = /^[A-Za-z0-9_-]{1,64}$/
|
||||
|
||||
/** Laisse une tâche finir après la réponse (e-mail d'alerte). */
|
||||
const inBackground = (p: Promise<unknown>) => (globalThis as { EdgeRuntime?: { waitUntil?: (p: Promise<unknown>) => void } }).EdgeRuntime?.waitUntil?.(p)
|
||||
|
||||
const enc = new TextEncoder()
|
||||
/** Comparaison en temps constant (empreintes SHA-256 : même longueur quelle que soit l'entrée). */
|
||||
async function sameSecret(a: string, b: string): Promise<boolean> {
|
||||
const [x, y] = await Promise.all([crypto.subtle.digest('SHA-256', enc.encode(a)), crypto.subtle.digest('SHA-256', enc.encode(b))])
|
||||
const u = new Uint8Array(x)
|
||||
const v = new Uint8Array(y)
|
||||
let diff = 0
|
||||
for (let i = 0; i < u.length; i++) diff |= u[i] ^ v[i]
|
||||
return diff === 0
|
||||
}
|
||||
|
||||
const notFound = () => new Response('Not found', { status: 404 })
|
||||
const json = (status: number, body: unknown) =>
|
||||
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' } })
|
||||
|
||||
function tokenClaims(token: string): { aal?: string } {
|
||||
try {
|
||||
const part = token.split('.')[1].replace(/-/g, '+').replace(/_/g, '/')
|
||||
return JSON.parse(atob(part.padEnd(part.length + ((4 - (part.length % 4)) % 4), '='))) as { aal?: string }
|
||||
} catch {
|
||||
return {}
|
||||
}
|
||||
}
|
||||
|
||||
/** Compte du jeton, vérifié par Supabase Auth, avec son niveau (aal2 = code de double authentification validé). */
|
||||
async function verifiedUser(req: Request): Promise<{ id: string; email: string; aal2: boolean; totp: boolean } | null> {
|
||||
const auth = req.headers.get('Authorization') ?? ''
|
||||
const token = auth.startsWith('Bearer ') ? auth.slice(7).trim() : ''
|
||||
if (!token || token.length > 4096) return null
|
||||
const res = await fetch(`${SUPABASE_URL}/auth/v1/user`, { headers: { apikey: ANON_KEY, Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(8000) })
|
||||
if (!res.ok) {
|
||||
await res.body?.cancel()
|
||||
return null
|
||||
}
|
||||
const u = (await res.json()) as { id?: string; email?: string; factors?: { status?: string; factor_type?: string }[] }
|
||||
if (typeof u.id !== 'string' || !UUID.test(u.id)) return null
|
||||
const totp = Array.isArray(u.factors) && u.factors.some((f) => f?.status === 'verified' && f?.factor_type === 'totp')
|
||||
return { id: u.id, email: u.email ?? '', aal2: tokenClaims(token).aal === 'aal2', totp }
|
||||
}
|
||||
|
||||
// Limite par compte : 120 requêtes par minute (par instance)
|
||||
const hits = new Map<string, number[]>()
|
||||
function limited(key: string): boolean {
|
||||
const now = Date.now()
|
||||
const list = (hits.get(key) ?? []).filter((t) => now - t < 60_000)
|
||||
list.push(now)
|
||||
hits.set(key, list)
|
||||
if (hits.size > 1000) hits.clear()
|
||||
return list.length > 120
|
||||
}
|
||||
|
||||
async function log(adminId: string | null, action: string, targetUser: string | null, target: string | null, details: Record<string, unknown>) {
|
||||
await sql!`select admin.log(${adminId}::uuid, ${action}::text, ${targetUser}::uuid, ${target}::text, ${JSON.stringify(details)}::jsonb)`
|
||||
}
|
||||
|
||||
/** E-mail d'alerte (action sensible ou connexion). Sans mot de passe SMTP configuré : rien. */
|
||||
function alert(subject: string, lines: string[]) {
|
||||
if (!SMTP_PASSWORD) return
|
||||
inBackground(
|
||||
(async () => {
|
||||
// Chargé seulement pour envoyer : un souci d'envoi ne peut pas bloquer la console
|
||||
const { default: nodemailer } = await import('npm:nodemailer@6.9.16')
|
||||
const transport = nodemailer.createTransport({ host: 'ssl0.ovh.net', port: 465, secure: true, auth: { user: SMTP_USER, pass: SMTP_PASSWORD } })
|
||||
await transport.sendMail({
|
||||
from: `Bobinoo (console) <${SMTP_USER}>`,
|
||||
to: ALERT_TO,
|
||||
subject: `[Console Bobinoo] ${subject}`,
|
||||
text: [...lines, '', `Le ${new Date().toLocaleString('fr-FR', { timeZone: 'Europe/Paris' })} (heure de Paris).`, "Si ce n'est pas toi : change ton mot de passe et retire ce compte de admin.admins dans Supabase."].join('\n'),
|
||||
})
|
||||
})().catch((e) => console.error('alerte e-mail non envoyée', (e as Error)?.message)),
|
||||
)
|
||||
}
|
||||
|
||||
const str = (v: unknown, max: number) => (typeof v === 'string' ? v.trim().slice(0, max) : '')
|
||||
const int = (v: unknown) => (typeof v === 'number' && Number.isInteger(v) && v >= 0 && v <= 100_000 ? v : 0)
|
||||
const reasonOf = (v: unknown) => {
|
||||
const r = str(v, 500)
|
||||
if (r.length < 3) throw new Error('motif requis (3 caractères minimum)')
|
||||
return r
|
||||
}
|
||||
|
||||
Deno.serve(async (req) => {
|
||||
// 1. Secret du VPS : sans lui, la fonction n'existe pas
|
||||
if (GATE.length < 32 || !sql) return notFound()
|
||||
if (!(await sameSecret(req.headers.get('X-Admin-Gate') ?? '', GATE))) return notFound()
|
||||
if (req.method !== 'POST') return notFound()
|
||||
|
||||
// 2. Compte + code de double authentification
|
||||
const user = await verifiedUser(req).catch(() => null)
|
||||
if (!user) return json(401, { error: 'session' })
|
||||
if (limited(user.id)) return json(429, { error: 'trop de requêtes' })
|
||||
if (!user.totp || !user.aal2) return json(403, { error: 'mfa' })
|
||||
|
||||
// 3. Liste des admins
|
||||
const [{ ok: isAdmin }] = await sql`select admin.is_admin(${user.id}::uuid) as ok`
|
||||
if (!isAdmin) {
|
||||
await log(user.id, 'accès refusé', user.id, user.email, {})
|
||||
alert('Accès refusé', [`Un compte qui n'est pas admin a tenté d'utiliser la console : ${user.email}.`])
|
||||
return json(403, { error: 'interdit' })
|
||||
}
|
||||
|
||||
const text = await req.text()
|
||||
if (text.length > 10_000) return json(413, { error: 'trop long' })
|
||||
let body: Record<string, unknown>
|
||||
try {
|
||||
body = JSON.parse(text) as Record<string, unknown>
|
||||
} catch {
|
||||
return json(400, { error: 'json' })
|
||||
}
|
||||
const action = str(body.action, 30)
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'hello': {
|
||||
const ua = str(req.headers.get('User-Agent'), 200)
|
||||
await log(user.id, 'connexion', user.id, user.email, { appareil: ua })
|
||||
alert('Connexion à la console', [`Connexion de ${user.email}.`, `Appareil : ${ua}`])
|
||||
const [{ r }] = await sql`select admin.card(${user.id}::uuid) as r`
|
||||
return json(200, r)
|
||||
}
|
||||
case 'overview': {
|
||||
const [{ r }] = await sql`select admin.overview() as r`
|
||||
return json(200, r)
|
||||
}
|
||||
case 'members': {
|
||||
const [{ r }] = await sql`select admin.members(${str(body.q, 60)}::text, ${int(body.offset)}::int) as r`
|
||||
return json(200, r)
|
||||
}
|
||||
case 'suspend': {
|
||||
const target = str(body.user, 36)
|
||||
if (!UUID.test(target) || typeof body.value !== 'boolean') return json(400, { error: 'paramètres' })
|
||||
const reason = reasonOf(body.reason)
|
||||
const [{ r }] = await sql`select admin.set_suspended(${user.id}::uuid, ${target}::uuid, ${body.value}::boolean, ${reason}::text) as r`
|
||||
if (r?.ok) alert(body.value ? 'Compte suspendu' : 'Compte réactivé', [`Par ${user.email}.`, `Compte : ${target}`, `Motif : ${reason}`])
|
||||
return json(200, r)
|
||||
}
|
||||
case 'reviews': {
|
||||
const [{ r }] = await sql`select admin.reviews(${str(body.q, 60)}::text, ${int(body.offset)}::int) as r`
|
||||
return json(200, r)
|
||||
}
|
||||
case 'clear_review': {
|
||||
const target = str(body.user, 36)
|
||||
const item = str(body.item, 64)
|
||||
if (!UUID.test(target) || !ITEM_ID.test(item)) return json(400, { error: 'paramètres' })
|
||||
const reason = reasonOf(body.reason)
|
||||
const [{ r }] = await sql`select admin.clear_review(${user.id}::uuid, ${target}::uuid, ${item}::text, ${reason}::text) as r`
|
||||
if (r?.ok) alert('Avis retiré', [`Par ${user.email}.`, `Compte : ${target}, fiche ${item}`, `Motif : ${reason}`])
|
||||
return json(200, r)
|
||||
}
|
||||
case 'comments': {
|
||||
const [{ r }] = await sql`select admin.comments(${int(body.offset)}::int) as r`
|
||||
return json(200, r)
|
||||
}
|
||||
case 'delete_comment': {
|
||||
const id = typeof body.id === 'number' && Number.isInteger(body.id) && body.id > 0 ? body.id : 0
|
||||
if (!id) return json(400, { error: 'paramètres' })
|
||||
const reason = reasonOf(body.reason)
|
||||
const [{ r }] = await sql`select admin.delete_comment(${user.id}::uuid, ${id}::bigint, ${reason}::text) as r`
|
||||
if (r?.ok) alert('Commentaire supprimé', [`Par ${user.email}.`, `Commentaire n° ${id}`, `Motif : ${reason}`])
|
||||
return json(200, r)
|
||||
}
|
||||
case 'journal': {
|
||||
const [{ r }] = await sql`select admin.journal_list(${int(body.offset)}::int) as r`
|
||||
return json(200, r)
|
||||
}
|
||||
default:
|
||||
return json(400, { error: 'action inconnue' })
|
||||
}
|
||||
} catch (e) {
|
||||
const msg = (e as Error)?.message ?? 'erreur'
|
||||
// Messages volontaires (motif manquant, action sur son propre compte) renvoyés tels quels, le reste masqué
|
||||
if (/motif requis|impossible sur son propre compte/.test(msg)) return json(400, { error: msg.replace(/^.*?(motif requis.*|impossible sur son propre compte).*$/, '$1') })
|
||||
console.error('admin', action, msg)
|
||||
return json(500, { error: 'erreur serveur' })
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,219 @@
|
||||
-- Console d'administration séparée (30/11/2026). Voir docs/admin.md.
|
||||
-- Tout vit dans le schéma « admin », qui n'est PAS exposé par l'API (PostgREST ne sert que public et graphql_public) :
|
||||
-- ni l'app, ni un visiteur, ni un membre connecté ne peuvent l'appeler. Seule la fonction Edge « admin »
|
||||
-- y accède, par une connexion directe à la base, après avoir vérifié le secret du VPS, le compte et son code (aal2).
|
||||
-- Idempotent.
|
||||
|
||||
create schema if not exists admin;
|
||||
revoke all on schema admin from public, anon, authenticated, service_role;
|
||||
comment on schema admin is 'Console d''administration (docs/admin.md). Non exposé par l''API : seule la fonction Edge « admin » y accède, par connexion directe.';
|
||||
|
||||
-- ─── Qui est admin ───
|
||||
create table if not exists admin.admins (
|
||||
user_id uuid primary key references auth.users (id) on delete cascade,
|
||||
added_at timestamptz not null default now()
|
||||
);
|
||||
comment on table admin.admins is 'Comptes autorisés dans la console (double authentification obligatoire en plus).';
|
||||
|
||||
-- ─── Journal : on peut y ajouter, jamais modifier ni effacer ───
|
||||
create table if not exists admin.journal (
|
||||
id bigint generated always as identity primary key,
|
||||
at timestamptz not null default now(),
|
||||
admin_id uuid,
|
||||
action text not null check (char_length(action) <= 40),
|
||||
target_user uuid,
|
||||
target text check (char_length(target) <= 200),
|
||||
details jsonb not null default '{}'::jsonb
|
||||
);
|
||||
create index if not exists journal_at_idx on admin.journal (at desc);
|
||||
comment on table admin.journal is 'Journal de la console : connexions et actions. Ajout seulement (modification et suppression refusées).';
|
||||
|
||||
create or replace function admin.journal_locked()
|
||||
returns trigger language plpgsql set search_path = '' as $$
|
||||
begin
|
||||
raise exception 'journal en ajout seulement';
|
||||
end;
|
||||
$$;
|
||||
drop trigger if exists journal_locked on admin.journal;
|
||||
create trigger journal_locked before update or delete on admin.journal
|
||||
for each row execute function admin.journal_locked();
|
||||
drop trigger if exists journal_no_truncate on admin.journal;
|
||||
create trigger journal_no_truncate before truncate on admin.journal
|
||||
for each statement execute function admin.journal_locked();
|
||||
comment on function admin.journal_locked() is 'Trigger : refuse toute modification ou suppression du journal.';
|
||||
|
||||
create or replace function admin.log(p_admin uuid, p_action text, p_target_user uuid, p_target text, p_details jsonb)
|
||||
returns void language sql set search_path = '' as $$
|
||||
insert into admin.journal (admin_id, action, target_user, target, details)
|
||||
values (p_admin, left(p_action, 40), p_target_user, left(p_target, 200), coalesce(p_details, '{}'::jsonb));
|
||||
$$;
|
||||
comment on function admin.log(uuid, text, uuid, text, jsonb) is 'Ajoute une ligne au journal.';
|
||||
|
||||
create or replace function admin.is_admin(p_user uuid)
|
||||
returns boolean language sql stable set search_path = '' as $$
|
||||
select exists (select 1 from admin.admins where user_id = p_user);
|
||||
$$;
|
||||
comment on function admin.is_admin(uuid) is 'Ce compte est-il dans la liste des admins ?';
|
||||
|
||||
-- Carte d'un membre (réutilisée par les listes)
|
||||
create or replace function admin.card(p_user uuid)
|
||||
returns jsonb language sql stable set search_path = '' as $$
|
||||
select jsonb_build_object('id', p.id, 'username', p.username, 'display_name', p.display_name, 'avatar_url', p.avatar_url, 'suspended', p.suspended)
|
||||
from public.profiles p where p.id = p_user;
|
||||
$$;
|
||||
comment on function admin.card(uuid) is 'Pseudo, nom, photo et état d''un membre.';
|
||||
|
||||
-- ─── Tableau de bord ───
|
||||
create or replace function admin.overview()
|
||||
returns jsonb language sql stable set search_path = '' as $$
|
||||
select jsonb_build_object(
|
||||
'members', (select count(*) from auth.users),
|
||||
'members_week', (select count(*) from auth.users where created_at > now() - interval '7 days'),
|
||||
'active_week', (select count(*) from auth.users where last_sign_in_at > now() - interval '7 days'),
|
||||
'suspended', (select count(*) from public.profiles where suspended),
|
||||
'private', (select count(*) from public.profiles where is_private),
|
||||
'items', (select count(*) from public.items where not deleted),
|
||||
'reviews', (select count(*) from public.items where not deleted and coalesce(data->>'notes', '') <> ''),
|
||||
'comments', (select count(*) from public.review_comments),
|
||||
'follows', (select count(*) from public.follows where status = 'accepted'),
|
||||
'shared_lists', (select count(*) from public.shared_lists),
|
||||
'latest', coalesce((
|
||||
select jsonb_agg(admin.card(u.id) || jsonb_build_object('created_at', u.created_at) order by u.created_at desc)
|
||||
from (select id, created_at from auth.users order by created_at desc limit 5) u
|
||||
), '[]'::jsonb)
|
||||
);
|
||||
$$;
|
||||
comment on function admin.overview() is 'Chiffres généraux et dernières inscriptions.';
|
||||
|
||||
-- ─── Membres ───
|
||||
create or replace function admin.members(p_q text, p_offset integer)
|
||||
returns jsonb language sql stable set search_path = '' as $$
|
||||
select coalesce(jsonb_agg(m.row order by m.created_at desc), '[]'::jsonb) from (
|
||||
select u.created_at, admin.card(u.id) || jsonb_build_object(
|
||||
'email', u.email,
|
||||
'created_at', u.created_at,
|
||||
'last_sign_in_at', u.last_sign_in_at,
|
||||
'items', (select count(*) from public.items i where i.user_id = u.id and not i.deleted),
|
||||
'mfa', exists (select 1 from auth.mfa_factors f where f.user_id = u.id and f.status = 'verified'),
|
||||
'is_admin', admin.is_admin(u.id)
|
||||
) as row
|
||||
from auth.users u join public.profiles p on p.id = u.id
|
||||
where coalesce(p_q, '') = ''
|
||||
or p.username ilike '%' || replace(replace(replace(p_q, '\', '\\'), '%', '\%'), '_', '\_') || '%'
|
||||
or p.display_name ilike '%' || replace(replace(replace(p_q, '\', '\\'), '%', '\%'), '_', '\_') || '%'
|
||||
or u.email ilike '%' || replace(replace(replace(p_q, '\', '\\'), '%', '\%'), '_', '\_') || '%'
|
||||
order by u.created_at desc
|
||||
limit 50 offset greatest(coalesce(p_offset, 0), 0)
|
||||
) m;
|
||||
$$;
|
||||
comment on function admin.members(text, integer) is 'Membres (recherche par pseudo, nom ou e-mail), 50 par page.';
|
||||
|
||||
create or replace function admin.set_suspended(p_admin uuid, p_user uuid, p_value boolean, p_reason text)
|
||||
returns jsonb language plpgsql set search_path = '' as $$
|
||||
begin
|
||||
if p_user = p_admin then raise exception 'impossible sur son propre compte'; end if;
|
||||
update public.profiles set suspended = p_value where id = p_user and suspended is distinct from p_value;
|
||||
if not found then return jsonb_build_object('ok', false); end if;
|
||||
perform admin.log(p_admin, case when p_value then 'suspendre' else 'réactiver' end, p_user,
|
||||
(select username from public.profiles where id = p_user), jsonb_build_object('motif', left(p_reason, 500)));
|
||||
return jsonb_build_object('ok', true);
|
||||
end;
|
||||
$$;
|
||||
comment on function admin.set_suspended(uuid, uuid, boolean, text) is 'Suspendre ou réactiver un membre (inscrit au journal).';
|
||||
|
||||
-- ─── Avis ───
|
||||
create or replace function admin.reviews(p_q text, p_offset integer)
|
||||
returns jsonb language sql stable set search_path = '' as $$
|
||||
select coalesce(jsonb_agg(r.row order by r.updated_at desc), '[]'::jsonb) from (
|
||||
select i.updated_at, jsonb_build_object(
|
||||
'user', admin.card(i.user_id),
|
||||
'item_id', i.id,
|
||||
'title', i.data->>'title',
|
||||
'rating', i.data->'rating',
|
||||
'spoiler', coalesce(i.data->'spoiler' = 'true'::jsonb, false),
|
||||
'notes', left(i.data->>'notes', 2000),
|
||||
'updated_at', i.updated_at,
|
||||
'comments', (select count(*) from public.review_comments c where c.author_id = i.user_id and c.item_id = i.id)
|
||||
) as row
|
||||
from public.items i join public.profiles p on p.id = i.user_id
|
||||
where not i.deleted and coalesce(i.data->>'notes', '') <> ''
|
||||
and (coalesce(p_q, '') = '' or p.username ilike '%' || replace(replace(replace(p_q, '\', '\\'), '%', '\%'), '_', '\_') || '%'
|
||||
or i.data->>'title' ilike '%' || replace(replace(replace(p_q, '\', '\\'), '%', '\%'), '_', '\_') || '%')
|
||||
order by i.updated_at desc
|
||||
limit 30 offset greatest(coalesce(p_offset, 0), 0)
|
||||
) r;
|
||||
$$;
|
||||
comment on function admin.reviews(text, integer) is 'Avis (recherche par pseudo ou titre), les plus récents d''abord, 30 par page.';
|
||||
|
||||
create or replace function admin.clear_review(p_admin uuid, p_user uuid, p_item text, p_reason text)
|
||||
returns jsonb language plpgsql set search_path = '' as $$
|
||||
declare
|
||||
now_iso text := to_char(now() at time zone 'utc', 'YYYY-MM-DD"T"HH24:MI:SS.MS"Z"');
|
||||
v_title text;
|
||||
v_notes text;
|
||||
begin
|
||||
select data->>'title', data->>'notes' into v_title, v_notes from public.items
|
||||
where user_id = p_user and id = p_item and not deleted and coalesce(data->>'notes', '') <> '';
|
||||
if not found then return jsonb_build_object('ok', false); end if;
|
||||
-- Date de modification avancée : l'appareil du membre reçoit la fiche sans l'avis à sa prochaine synchro
|
||||
update public.items
|
||||
set data = jsonb_set(data - 'notes', '{updatedAt}', to_jsonb(now_iso)), updated_at = now()
|
||||
where user_id = p_user and id = p_item;
|
||||
perform admin.log(p_admin, 'retirer un avis', p_user, v_title,
|
||||
jsonb_build_object('motif', left(p_reason, 500), 'avis', left(v_notes, 1000)));
|
||||
return jsonb_build_object('ok', true);
|
||||
end;
|
||||
$$;
|
||||
comment on function admin.clear_review(uuid, uuid, text, text) is 'Retirer un avis (le texte retiré est gardé dans le journal).';
|
||||
|
||||
-- ─── Commentaires ───
|
||||
create or replace function admin.comments(p_offset integer)
|
||||
returns jsonb language sql stable set search_path = '' as $$
|
||||
select coalesce(jsonb_agg(c.row order by c.created_at desc), '[]'::jsonb) from (
|
||||
select rc.created_at, jsonb_build_object(
|
||||
'id', rc.id, 'body', rc.body, 'created_at', rc.created_at,
|
||||
'user', admin.card(rc.user_id), 'author', admin.card(rc.author_id),
|
||||
'title', (select i.data->>'title' from public.items i where i.user_id = rc.author_id and i.id = rc.item_id)
|
||||
) as row
|
||||
from public.review_comments rc
|
||||
order by rc.created_at desc
|
||||
limit 30 offset greatest(coalesce(p_offset, 0), 0)
|
||||
) c;
|
||||
$$;
|
||||
comment on function admin.comments(integer) is 'Derniers commentaires sur les avis, 30 par page.';
|
||||
|
||||
create or replace function admin.delete_comment(p_admin uuid, p_id bigint, p_reason text)
|
||||
returns jsonb language plpgsql set search_path = '' as $$
|
||||
declare r public.review_comments;
|
||||
begin
|
||||
delete from public.review_comments where id = p_id returning * into r;
|
||||
if r.id is null then return jsonb_build_object('ok', false); end if;
|
||||
perform admin.log(p_admin, 'supprimer un commentaire', r.user_id, (select username from public.profiles where id = r.user_id),
|
||||
jsonb_build_object('motif', left(p_reason, 500), 'commentaire', left(r.body, 1000)));
|
||||
return jsonb_build_object('ok', true);
|
||||
end;
|
||||
$$;
|
||||
comment on function admin.delete_comment(uuid, bigint, text) is 'Supprimer un commentaire (le texte est gardé dans le journal).';
|
||||
|
||||
-- ─── Journal ───
|
||||
create or replace function admin.journal_list(p_offset integer)
|
||||
returns jsonb language sql stable set search_path = '' as $$
|
||||
select coalesce(jsonb_agg(j.row order by j.id desc), '[]'::jsonb) from (
|
||||
select j.id, jsonb_build_object('id', j.id, 'at', j.at, 'action', j.action, 'target', j.target, 'details', j.details,
|
||||
'admin', (select username from public.profiles where id = j.admin_id)) as row
|
||||
from admin.journal j order by j.id desc
|
||||
limit 50 offset greatest(coalesce(p_offset, 0), 0)
|
||||
) j;
|
||||
$$;
|
||||
comment on function admin.journal_list(integer) is 'Journal de la console, le plus récent d''abord, 50 par page.';
|
||||
|
||||
-- Personne d'autre que le propriétaire (postgres, utilisé par la fonction Edge) n'y touche
|
||||
revoke all on all tables in schema admin from public, anon, authenticated, service_role;
|
||||
revoke all on all functions in schema admin from public, anon, authenticated, service_role;
|
||||
alter default privileges in schema admin revoke all on tables from public, anon, authenticated, service_role;
|
||||
alter default privileges in schema admin revoke all on functions from public, anon, authenticated, service_role;
|
||||
|
||||
-- Premier admin : le compte de Romain (rx0m_dct)
|
||||
insert into admin.admins (user_id)
|
||||
select id from public.profiles where username = 'rx0m_dct'
|
||||
on conflict do nothing;
|
||||
+1
-1
@@ -15,5 +15,5 @@
|
||||
"allowImportingTsExtensions": false,
|
||||
"types": ["vite/client", "vite-plugin-pwa/client"]
|
||||
},
|
||||
"include": ["src", "vite.config.ts"]
|
||||
"include": ["src", "vite.config.ts", "admin/src", "vite.admin.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { defineConfig, loadEnv } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
/**
|
||||
* Console d'administration (docs/admin.md) : site à part, construit dans dist-admin/, jamais dans l'app publique.
|
||||
* Servie par nginx sur la boucle locale du VPS et publiée seulement sur le réseau privé Tailscale.
|
||||
*/
|
||||
export default defineConfig(({ mode }) => {
|
||||
const env = loadEnv(mode, '.', 'VITE_')
|
||||
const full = loadEnv(mode, '.', '')
|
||||
if ((full.REQUIRE_SUPABASE || full.CI || full.GITEA_ACTIONS) && (!env.VITE_SUPABASE_URL || !env.VITE_SUPABASE_ANON_KEY)) {
|
||||
throw new Error('VITE_SUPABASE_URL / VITE_SUPABASE_ANON_KEY manquantes')
|
||||
}
|
||||
return {
|
||||
root: 'admin',
|
||||
envDir: '..',
|
||||
base: '/',
|
||||
plugins: [react(), tailwindcss()],
|
||||
build: { outDir: '../dist-admin', emptyOutDir: true, sourcemap: false },
|
||||
}
|
||||
})
|
||||
Reference in new issue
Block a user