diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml
index cf8930b..2d1583b 100644
--- a/.gitea/workflows/deploy.yml
+++ b/.gitea/workflows/deploy.yml
@@ -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 }}
diff --git a/.gitignore b/.gitignore
index c85b641..f865532 100644
--- a/.gitignore
+++ b/.gitignore
@@ -11,3 +11,4 @@ supabase/.branches
_to_delete
.env.deploy
tsconfig.tsbuildinfo
+dist-admin
diff --git a/CLAUDE.md b/CLAUDE.md
index b87b1bd..5d0d1f0 100644
--- a/CLAUDE.md
+++ b/CLAUDE.md
@@ -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é.
diff --git a/admin/index.html b/admin/index.html
new file mode 100644
index 0000000..ba23ce0
--- /dev/null
+++ b/admin/index.html
@@ -0,0 +1,15 @@
+
+
+
+
+
+
+
+
+ Console Bobinoo
+
+
+
+
+
+
diff --git a/admin/src/App.tsx b/admin/src/App.tsx
new file mode 100644
index 0000000..e271cc2
--- /dev/null
+++ b/admin/src/App.tsx
@@ -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()
+
+ 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 (setNotice(undefined), setSession({ token, me }))} />
+ return
+}
+
+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()
+ const codeRef = useRef(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(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 (
+
+
+
+ Console
+
+
Bobinoo
+
Accès réservé. Chaque connexion est inscrite au journal et signalée par e-mail.
Connexions et actions de la console. Rien ne peut y être modifié ni effacé.
+
+
+ {rows?.map((j) => (
+
+
+ {j.action}
+ {j.target && · {j.target}}
+
+
+ {fmt(j.at)}
+ {j.admin && ` · par @${j.admin}`}
+
+ {Object.entries(j.details).map(([k, v]) => (
+
+ {k} : {String(v)}
+
+ ))}
+
+ ))}
+
+
+ >
+ )
+}
diff --git a/admin/src/styles.css b/admin/src/styles.css
new file mode 100644
index 0000000..6082de3
--- /dev/null
+++ b/admin/src/styles.css
@@ -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;
+ }
+}
diff --git a/deploy/nginx/admin.conf b/deploy/nginx/admin.conf
new file mode 100644
index 0000000..172ec61
--- /dev/null
+++ b/deploy/nginx/admin.conf
@@ -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 "";
+ # 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;
+ }
+}
diff --git a/deploy/nginx/site.conf b/deploy/nginx/site.conf
index 835cbd9..00b4871 100644
--- a/deploy/nginx/site.conf
+++ b/deploy/nginx/site.conf
@@ -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;
diff --git a/deploy/release.sh b/deploy/release.sh
index 70d29cc..dcfdff4 100755
--- a/deploy/release.sh
+++ b/deploy/release.sh
@@ -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"
diff --git a/docs/admin.md b/docs/admin.md
new file mode 100644
index 0000000..a1738ab
--- /dev/null
+++ b/docs/admin.md
@@ -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..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.
diff --git a/docs/database.md b/docs/database.md
index cd5a9f8..d328780 100644
--- a/docs/database.md
+++ b/docs/database.md
@@ -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 |
diff --git a/package.json b/package.json
index ee1eb3a..c5151d8 100644
--- a/package.json
+++ b/package.json
@@ -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",
diff --git a/supabase/config.toml b/supabase/config.toml
index c63a173..d701410 100644
--- a/supabase/config.toml
+++ b/supabase/config.toml
@@ -13,3 +13,6 @@ verify_jwt = false
[functions.ratings]
verify_jwt = false
+
+[functions.admin]
+verify_jwt = false
diff --git a/supabase/functions/admin/index.ts b/supabase/functions/admin/index.ts
new file mode 100644
index 0000000..bf6a223
--- /dev/null
+++ b/supabase/functions/admin/index.ts
@@ -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) => (globalThis as { EdgeRuntime?: { waitUntil?: (p: Promise) => 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 {
+ 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()
+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) {
+ 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
+ try {
+ body = JSON.parse(text) as Record
+ } 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' })
+ }
+})
diff --git a/supabase/migrations/20261130150000_admin_console.sql b/supabase/migrations/20261130150000_admin_console.sql
new file mode 100644
index 0000000..aa99236
--- /dev/null
+++ b/supabase/migrations/20261130150000_admin_console.sql
@@ -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;
diff --git a/tsconfig.json b/tsconfig.json
index 4c4f1f6..ad15b74 100644
--- a/tsconfig.json
+++ b/tsconfig.json
@@ -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"]
}
diff --git a/vite.admin.config.ts b/vite.admin.config.ts
new file mode 100644
index 0000000..2b927b2
--- /dev/null
+++ b/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 },
+ }
+})