diff --git a/.gitea/workflows/backup.yml b/.gitea/workflows/backup.yml
new file mode 100644
index 0000000..fe85738
--- /dev/null
+++ b/.gitea/workflows/backup.yml
@@ -0,0 +1,32 @@
+# Sauvegarde automatique de la base Supabase : chaque nuit, pg_dump -> chiffrement -> VPS, avec rotation
+# (7 quotidiennes, 4 hebdomadaires, 6 mensuelles). Voir deploy/BACKUP.md.
+# Secrets à créer dans Gitea (Dépôt -> Paramètres -> Actions -> Secrets) — JAMAIS dans le dépôt :
+# SUPABASE_DB_URL chaîne « Session pooler » (IPv4) de Supabase, avec le mot de passe de la base
+# BACKUP_PASSPHRASE phrase de chiffrement (16 caractères min.), conservée aussi hors du VPS
+# Variable optionnelle : BACKUP_DIR (défaut /srv/backups/azuucine)
+name: backup
+on:
+ schedule:
+ - cron: '17 2 * * *' # tous les jours à 02:17 UTC
+ workflow_dispatch:
+
+jobs:
+ backup:
+ runs-on: azuucine
+ timeout-minutes: 30
+ steps:
+ - name: Récupérer le script
+ # Le jeton n'est visible que de cette étape
+ env:
+ GIT_TOKEN: ${{ github.token }}
+ REPO_URL: ${{ github.server_url }}/${{ github.repository }}.git
+ run: |
+ rm -rf src
+ AUTH=$(printf 'x-access-token:%s' "$GIT_TOKEN" | base64 -w0)
+ git -c http.extraheader="AUTHORIZATION: basic $AUTH" clone --depth 1 --branch main "$REPO_URL" src
+ - name: Sauvegarder (dump, contrôle, chiffrement, rotation)
+ env:
+ SUPABASE_DB_URL: ${{ secrets.SUPABASE_DB_URL }}
+ BACKUP_PASSPHRASE: ${{ secrets.BACKUP_PASSPHRASE }}
+ BACKUP_DIR: ${{ vars.BACKUP_DIR }}
+ run: bash src/deploy/backup.sh
diff --git a/deploy/BACKUP.md b/deploy/BACKUP.md
new file mode 100644
index 0000000..ebc8845
--- /dev/null
+++ b/deploy/BACKUP.md
@@ -0,0 +1,114 @@
+# Sauvegardes automatiques de la base (Supabase → VPS)
+
+Chaque nuit à 02:17 UTC, le workflow `.gitea/workflows/backup.yml` lance `deploy/backup.sh` sur le
+runner `azuucine` (le VPS) :
+
+1. `pg_dump` de toute la base (format custom compressé : tables, données, fonctions, policies RLS,
+ comptes `auth.users`), via la connexion **Session pooler IPv4** de Supabase ;
+2. **contrôles** : taille minimale, dump lisible par `pg_restore`, présence des tables `items`,
+ `profiles`, `follows`, `settings` et `auth.users` — sinon le job **échoue** (croix rouge dans Gitea) ;
+3. **chiffrement** gpg symétrique AES-256 avec `BACKUP_PASSPHRASE`, puis vérification que le fichier
+ se déchiffre bien ;
+4. rangement dans `/srv/backups/azuucine/` (dossier en `700`) et **rotation** :
+ 7 quotidiennes, 4 hebdomadaires, 6 mensuelles (liens physiques : une même sauvegarde n'occupe
+ la place qu'une fois).
+
+Les secrets ne sont jamais dans le dépôt ni affichés dans les logs ; le mot de passe de la base passe
+par `PGPASSWORD` (pas sur la ligne de commande).
+
+Pour restaurer : **`deploy/restore.md`**.
+
+## Mise en place (une seule fois)
+
+### 1. Chaîne de connexion Supabase
+
+Supabase → projet `qfgnxonqwldcfdjqhhjz` → **Connect** → **Session pooler** (IPv4, port 5432) :
+
+```
+postgresql://postgres.qfgnxonqwldcfdjqhhjz:[YOUR-PASSWORD]@aws-0-.pooler.supabase.com:5432/postgres
+```
+
+Remplacer `[YOUR-PASSWORD]` par le mot de passe de la base (Project Settings → Database → Reset
+database password si tu ne l'as plus ; **les caractères spéciaux doivent être encodés en %XX**,
+ex. `@` → `%40`, ou choisir un mot de passe sans caractères spéciaux, long).
+
+> Pourquoi le *Session pooler* : la connexion directe `db..supabase.co` est en IPv6 seulement ;
+> le pooler « session » est IPv4 et accepte `pg_dump` (le pooler « transaction », port 6543, non).
+
+### 2. Phrase de chiffrement
+
+Générer une phrase longue et la ranger **dans ton gestionnaire de mots de passe** (si le VPS meurt,
+c'est la seule façon de relire les sauvegardes copiées ailleurs) :
+
+```bash
+openssl rand -base64 32
+```
+
+### 3. Secrets Gitea
+
+Dépôt `romain/azuucine` → **Paramètres → Actions → Secrets** :
+
+| Nom | Valeur |
+| --- | --- |
+| `SUPABASE_DB_URL` | la chaîne de l'étape 1 |
+| `BACKUP_PASSPHRASE` | la phrase de l'étape 2 |
+
+Optionnel, **Variables** : `BACKUP_DIR` (défaut `/srv/backups/azuucine`).
+
+### 4. Préparer le VPS (en root, une fois)
+
+Le runner tourne avec l'utilisateur `deploy` (sans sudo). Il lui faut un client Postgres **de la même
+version majeure que Supabase ou plus récent** (Supabase → Project Settings → Infrastructure ; 15 ou 17),
+`gpg`, et le dossier des sauvegardes :
+
+```bash
+# Client Postgres officiel (dépôt PGDG), ex. version 17
+apt-get install -y gnupg postgresql-common
+/usr/share/postgresql-common/pgdg/apt.postgresql.org.sh -y
+apt-get install -y postgresql-client-17
+
+# Dossier dédié, hors de /srv/azuucine (qui est monté dans le conteneur web)
+install -d -m 700 -o deploy -g deploy /srv/backups/azuucine
+```
+
+Alternative sans installer le client : si l'utilisateur `deploy` peut lancer Docker, le script utilise
+automatiquement l'image `postgres:17-alpine` quand le `pg_dump` local manque ou est trop ancien.
+
+### 5. Premier lancement
+
+Gitea → **Actions → backup → Run workflow**. Le log doit finir par :
+
+```
+sauvegarde OK : azuucine-AAAAMMJJ-HHMMSS.dump.gpg (… octets chiffrés, … tables de données)
+ daily : 1
+ weekly : 1
+ monthly : 1
+```
+
+Puis **tester une restauration** dans une base jetable (`deploy/restore.md`, cas a). Une sauvegarde
+jamais testée n'est pas une sauvegarde.
+
+## Surveillance
+
+- Un échec rend le job rouge dans Gitea : active les **notifications par e-mail des Actions** dans
+ ton profil Gitea (Paramètres → Notifications) pour être prévenu.
+- `/srv/backups/azuucine/.last-success` contient la date de la dernière sauvegarde réussie.
+- Le job ne touche pas aux sauvegardes existantes s'il échoue.
+
+## Recommandé : une copie hors du VPS
+
+Les sauvegardes sur le VPS protègent contre une erreur côté Supabase (fausse manip, projet supprimé),
+pas contre la perte du VPS. Les fichiers étant chiffrés, on peut les copier n'importe où sans risque,
+par exemple chaque semaine depuis un autre ordinateur :
+
+```bash
+rsync -a deploy@:/srv/backups/azuucine/weekly/ ~/Sauvegardes/azuucine/
+```
+
+## Lancer une sauvegarde à la main (sur le VPS)
+
+```bash
+export SUPABASE_DB_URL='postgresql://…' # ou lu depuis un fichier en 600
+read -rs BACKUP_PASSPHRASE && export BACKUP_PASSPHRASE
+bash deploy/backup.sh
+```
diff --git a/deploy/backup.sh b/deploy/backup.sh
new file mode 100755
index 0000000..1179762
--- /dev/null
+++ b/deploy/backup.sh
@@ -0,0 +1,129 @@
+#!/usr/bin/env bash
+# Sauvegarde chiffrée de la base Supabase d'AzuuCine, avec rotation.
+# Lancé chaque nuit par .gitea/workflows/backup.yml (runner "azuucine", sur le VPS).
+#
+# Variables (secrets Gitea, JAMAIS dans le dépôt) :
+# SUPABASE_DB_URL postgresql://postgres.:@aws-0-.pooler.supabase.com:5432/postgres
+# (Supabase -> Connect -> « Session pooler », IPv4)
+# BACKUP_PASSPHRASE phrase de chiffrement (gpg symétrique AES-256) — à garder AUSSI hors du VPS
+# Optionnelles :
+# BACKUP_DIR dossier des sauvegardes (défaut : /srv/backups/azuucine)
+# PG_IMAGE image Docker du client Postgres si pg_dump local trop ancien (défaut : postgres:17-alpine)
+# KEEP_DAILY / KEEP_WEEKLY / KEEP_MONTHLY (défaut : 7 / 4 / 6)
+# MIN_DUMP_BYTES taille minimale d'un dump valide (défaut : 20000)
+#
+# Restauration : voir deploy/restore.md. Procédure complète : deploy/BACKUP.md.
+set -Eeuo pipefail
+umask 077
+
+fail() { echo "ÉCHEC SAUVEGARDE : $*" >&2; exit 1; }
+trap 'fail "erreur inattendue (ligne $LINENO)"' ERR
+
+: "${SUPABASE_DB_URL:?SUPABASE_DB_URL manquante (secret Gitea)}"
+: "${BACKUP_PASSPHRASE:?BACKUP_PASSPHRASE manquante (secret Gitea)}"
+[ "${#BACKUP_PASSPHRASE}" -ge 16 ] || fail "BACKUP_PASSPHRASE trop courte (16 caractères minimum)"
+BACKUP_DIR=${BACKUP_DIR:-/srv/backups/azuucine}
+PG_IMAGE=${PG_IMAGE:-postgres:17-alpine}
+KEEP_DAILY=${KEEP_DAILY:-7}
+KEEP_WEEKLY=${KEEP_WEEKLY:-4}
+KEEP_MONTHLY=${KEEP_MONTHLY:-6}
+MIN_DUMP_BYTES=${MIN_DUMP_BYTES:-20000}
+command -v gpg >/dev/null || fail "gpg absent (apt install gnupg)"
+
+# ── Connexion : le mot de passe passe par PGPASSWORD, jamais sur la ligne de commande (visible dans ps) ──
+re='^(postgres(ql)?://)([^:/@]+):([^@]*)@(.+)$'
+[[ "$SUPABASE_DB_URL" =~ $re ]] || fail "SUPABASE_DB_URL mal formée (attendu postgresql://user:motdepasse@hôte:port/base)"
+DB_URL="${BASH_REMATCH[1]}${BASH_REMATCH[3]}@${BASH_REMATCH[5]}"
+pw=${BASH_REMATCH[4]}
+PGPASSWORD=$(printf '%b' "${pw//%/\\x}") # décodage des %XX éventuels
+export PGPASSWORD
+export PGSSLMODE=${PGSSLMODE:-require}
+export PGCONNECT_TIMEOUT=20
+unset pw
+
+mkdir -p "$BACKUP_DIR"/{daily,weekly,monthly}
+chmod 700 "$BACKUP_DIR" "$BACKUP_DIR"/{daily,weekly,monthly}
+WORK=$(mktemp -d "$BACKUP_DIR/.work.XXXXXX")
+cleanup() { rm -rf "$WORK"; }
+trap cleanup EXIT
+
+# ── Client Postgres : pg_dump local s'il est assez récent (>= version du serveur), sinon Docker ──
+pg() { # pg — exécute un outil client Postgres
+ if [ "${USE_DOCKER:-0}" = 1 ]; then
+ docker run --rm -i --network host --user "$(id -u):$(id -g)" \
+ -e PGPASSWORD -e PGSSLMODE -e PGCONNECT_TIMEOUT -v "$WORK:$WORK" -w "$WORK" "$PG_IMAGE" "$@"
+ else
+ "$@"
+ fi
+}
+server_major() { pg psql -X -At -d "$DB_URL" -c 'show server_version_num' | cut -c1-2; }
+
+USE_DOCKER=0
+if command -v pg_dump >/dev/null && command -v psql >/dev/null; then
+ local_major=$(pg_dump --version | grep -oE '[0-9]+' | head -1)
+ srv=$(server_major) || fail "connexion à la base impossible (URL, mot de passe, réseau IPv4 ?)"
+ if [ "$local_major" -lt "$srv" ]; then
+ command -v docker >/dev/null || fail "pg_dump $local_major < serveur $srv et Docker absent : installe postgresql-client-$srv"
+ USE_DOCKER=1
+ fi
+else
+ command -v docker >/dev/null || fail "ni pg_dump ni Docker : installe postgresql-client (même version que Supabase) ou Docker"
+ USE_DOCKER=1
+ srv=$(server_major) || fail "connexion à la base impossible (URL, mot de passe, réseau IPv4 ?)"
+fi
+echo "serveur Postgres $srv · client $([ "$USE_DOCKER" = 1 ] && echo "Docker $PG_IMAGE" || echo "local $local_major")"
+
+# ── Dump (format « custom » : compressé, restauration sélective possible avec pg_restore) ──
+STAMP=$(date -u +%Y%m%d-%H%M%S)
+DUMP="$WORK/azuucine-$STAMP.dump"
+pg pg_dump -d "$DB_URL" --format=custom --compress=9 --no-owner --no-privileges \
+ --exclude-table-data='auth.audit_log_entries' --file "$DUMP" \
+ || fail "pg_dump a échoué"
+
+# ── Contrôles : le dump doit exister, avoir une taille plausible et contenir les tables de l'app ──
+[ -s "$DUMP" ] || fail "dump vide"
+size=$(stat -c %s "$DUMP")
+[ "$size" -ge "$MIN_DUMP_BYTES" ] || fail "dump trop petit ($size octets < $MIN_DUMP_BYTES) : base vide ou dump incomplet ?"
+pg pg_restore --list "$DUMP" > "$WORK/toc.txt" || fail "dump illisible par pg_restore"
+for tbl in items profiles follows settings; do
+ grep -qE "TABLE DATA public $tbl " "$WORK/toc.txt" || fail "table public.$tbl absente du dump"
+done
+grep -qE "TABLE DATA auth users " "$WORK/toc.txt" || fail "table auth.users absente du dump"
+entries=$(grep -c 'TABLE DATA' "$WORK/toc.txt")
+
+# ── Chiffrement (gpg symétrique AES-256 ; la phrase passe par un descripteur, pas par la ligne de commande) ──
+ENC="$DUMP.gpg"
+gpg --batch --yes --quiet --pinentry-mode loopback --passphrase-fd 3 \
+ --symmetric --cipher-algo AES256 --s2k-digest-algo SHA512 --s2k-count 65011712 --compress-algo none \
+ --output "$ENC" "$DUMP" 3<<<"$BACKUP_PASSPHRASE" || fail "chiffrement impossible"
+# Vérification : le fichier chiffré se déchiffre et redonne exactement le dump
+gpg --batch --quiet --pinentry-mode loopback --passphrase-fd 3 --decrypt "$ENC" 3<<<"$BACKUP_PASSPHRASE" \
+ | cmp -s - "$DUMP" || fail "vérification du déchiffrement échouée"
+sha256sum "$ENC" | sed "s# .*/# #" > "$ENC.sha256"
+rm -f "$DUMP"
+
+# ── Rangement + rotation (7 quotidiennes, 4 hebdomadaires, 6 mensuelles ; liens physiques = pas de doublon disque) ──
+name=$(basename "$ENC")
+mv "$ENC" "$ENC.sha256" "$BACKUP_DIR/daily/"
+newest() { { ls -1 "$1"/*.gpg 2>/dev/null || true; } | sort | tail -1; }
+age_days() { echo $(( ( $(date -u +%s) - $(stat -c %Y "$1") ) / 86400 )); }
+w=$(newest "$BACKUP_DIR/weekly")
+if [ -z "$w" ] || [ "$(age_days "$w")" -ge 7 ]; then
+ ln -f "$BACKUP_DIR/daily/$name" "$BACKUP_DIR/weekly/$name"
+ ln -f "$BACKUP_DIR/daily/$name.sha256" "$BACKUP_DIR/weekly/$name.sha256"
+fi
+m=$(newest "$BACKUP_DIR/monthly")
+if [ -z "$m" ] || [ "$(basename "$m" | cut -c10-15)" != "$(date -u +%Y%m)" ]; then
+ ln -f "$BACKUP_DIR/daily/$name" "$BACKUP_DIR/monthly/$name"
+ ln -f "$BACKUP_DIR/daily/$name.sha256" "$BACKUP_DIR/monthly/$name.sha256"
+fi
+prune() { # prune
+ { ls -1 "$1"/*.gpg 2>/dev/null || true; } | sort -r | tail -n +$(( $2 + 1 )) | while read -r f; do rm -f "$f" "$f.sha256"; done
+}
+prune "$BACKUP_DIR/daily" "$KEEP_DAILY"
+prune "$BACKUP_DIR/weekly" "$KEEP_WEEKLY"
+prune "$BACKUP_DIR/monthly" "$KEEP_MONTHLY"
+
+date -u +%FT%TZ > "$BACKUP_DIR/.last-success"
+echo "sauvegarde OK : $name ($(stat -c %s "$BACKUP_DIR/daily/$name") octets chiffrés, $entries tables de données)"
+for d in daily weekly monthly; do echo " $d : $({ ls -1 "$BACKUP_DIR/$d"/*.gpg 2>/dev/null || true; } | wc -l)"; done
diff --git a/deploy/restore.md b/deploy/restore.md
new file mode 100644
index 0000000..be8af67
--- /dev/null
+++ b/deploy/restore.md
@@ -0,0 +1,97 @@
+# Restaurer une sauvegarde de la base AzuuCine
+
+Les sauvegardes sont produites chaque nuit par `deploy/backup.sh` (workflow `.gitea/workflows/backup.yml`)
+dans `/srv/backups/azuucine/{daily,weekly,monthly}/` sur le VPS :
+
+```
+azuucine-AAAAMMJJ-HHMMSS.dump.gpg dump pg_dump (format custom, compressé) chiffré AES-256 (gpg symétrique)
+azuucine-AAAAMMJJ-HHMMSS.dump.gpg.sha256 empreinte du fichier chiffré
+```
+
+Il faut la **phrase de chiffrement** (`BACKUP_PASSPHRASE`, gardée dans ton gestionnaire de mots de passe) :
+sans elle, la sauvegarde est illisible — c'est voulu.
+
+> ⚠️ Toujours **tester d'abord sur un projet Supabase de test** (ou une base Postgres locale), jamais
+> directement sur la production. Une restauration remplace des données : fais d'abord une sauvegarde
+> de l'état actuel (`bash deploy/backup.sh` à la main, voir BACKUP.md).
+
+## 1. Récupérer et déchiffrer
+
+```bash
+cd /srv/backups/azuucine/daily # ou weekly / monthly
+ls -1 # choisir le fichier
+F=azuucine-20261009-021703.dump.gpg
+sha256sum -c "$F.sha256" # doit afficher : OK
+
+# Déchiffrer (la phrase est demandée ; rien n'est écrit dans l'historique du shell)
+umask 077
+gpg --decrypt --output /tmp/azuucine.dump "$F"
+
+# Contenu du dump (liste des tables, fonctions, policies…)
+pg_restore --list /tmp/azuucine.dump | less
+```
+
+Le client Postgres doit être **de la même version majeure que Supabase, ou plus récent**
+(`pg_restore --version`). Sinon, via Docker :
+`docker run --rm -it --network host -v /tmp:/tmp postgres:17-alpine pg_restore --list /tmp/azuucine.dump`
+
+## 2. Cas courants
+
+La connexion se fait avec la chaîne **Session pooler** (Supabase → Connect), mot de passe dans `PGPASSWORD` :
+
+```bash
+export PGPASSWORD='…' # mot de passe de la base (pas dans l'URL)
+export PGSSLMODE=require
+DB='postgresql://postgres.@aws-0-.pooler.supabase.com:5432/postgres'
+```
+
+### a) Récupérer les données d'un seul compte ou d'une seule table (le plus fréquent)
+
+Restaurer le dump dans une **base locale** jetable, puis copier ce qu'il faut :
+
+```bash
+createdb azuu_restore
+pg_restore --no-owner --no-privileges -d azuu_restore --schema=public /tmp/azuucine.dump
+psql -d azuu_restore -c "select id, data->>'title' from public.items where user_id = ''"
+```
+
+(Les erreurs « role … does not exist » / « schema auth does not exist » sur une base locale sont normales :
+les tables `public` gardent leurs données.) Puis réinjecter les lignes voulues dans Supabase avec
+`\copy … to/from` ou un `insert … on conflict do update` ciblé.
+
+### b) Restaurer tout le schéma `public` (après une fausse manip)
+
+```bash
+# 1. sauvegarde de l'état actuel
+bash deploy/backup.sh
+# 2. restauration des tables de l'app (les comptes auth.users existent toujours)
+pg_restore --no-owner --no-privileges --clean --if-exists --schema=public -d "$DB" /tmp/azuucine.dump
+```
+
+`--clean` supprime puis recrée les objets du schéma `public` (tables, fonctions, policies RLS).
+Relancer ensuite les migrations récentes si le dump est antérieur à l'une d'elles
+(`supabase/migrations/*.sql`, toutes idempotentes) dans **SQL Editor → Run**.
+
+### c) Projet Supabase perdu (reconstruction complète dans un nouveau projet)
+
+1. Créer un nouveau projet Supabase (même région), noter sa chaîne Session pooler.
+2. Restaurer d'abord les comptes, puis l'app :
+ ```bash
+ pg_restore --no-owner --no-privileges --data-only --schema=auth --table=users --table=identities -d "$DB" /tmp/azuucine.dump
+ pg_restore --no-owner --no-privileges --schema=public -d "$DB" /tmp/azuucine.dump
+ pg_restore --no-owner --no-privileges --data-only --schema=storage --table=objects -d "$DB" /tmp/azuucine.dump
+ ```
+ (Les fichiers du bucket `profile-media` ne sont **pas** dans le dump : seules leurs références le sont.
+ Les photos de profil devront être re-téléversées, ou copiées depuis l'ancien projet s'il est accessible.)
+3. Rejouer les réglages hors base : bucket `profile-media` (public), edge functions `tmdb` et
+ `delete-account` + leurs secrets (clé TMDB), fournisseurs d'auth (Google), URL du site.
+4. Mettre à jour `VITE_SUPABASE_URL` / `VITE_SUPABASE_ANON_KEY` dans Gitea et redéployer.
+5. Remettre Romain admin : `insert into public.admins (user_id) values ('') on conflict do nothing;`
+
+## 3. Nettoyer
+
+```bash
+shred -u /tmp/azuucine.dump 2>/dev/null || rm -f /tmp/azuucine.dump
+dropdb azuu_restore 2>/dev/null || true
+unset PGPASSWORD
+```
diff --git a/src/components/ErrorBoundary.tsx b/src/components/ErrorBoundary.tsx
new file mode 100644
index 0000000..fb145fa
--- /dev/null
+++ b/src/components/ErrorBoundary.tsx
@@ -0,0 +1,45 @@
+import { Component, type ErrorInfo, type ReactNode } from 'react'
+import { t } from '../i18n'
+import { reportError } from '../lib/errorReporter'
+
+/**
+ * Filet de sécurité global : si l'affichage plante, on montre un écran propre
+ * (« Oups… ») au lieu d'une page blanche, et l'erreur est remontée (sans donnée perso).
+ */
+export default class ErrorBoundary extends Component<{ children: ReactNode }, { failed: boolean }> {
+ state = { failed: false }
+
+ static getDerivedStateFromError() {
+ return { failed: true }
+ }
+
+ componentDidCatch(error: unknown, info: ErrorInfo) {
+ reportError(error, 'render', info.componentStack ?? '')
+ }
+
+ render() {
+ if (!this.state.failed) return this.props.children
+ return this.setState({ failed: false })} />
+ }
+}
+
+function CrashScreen({ onRetry }: { onRetry: () => void }) {
+ return (
+
+
+ )
+}
diff --git a/src/vite-env.d.ts b/src/vite-env.d.ts
index 172bfbf..b0739f7 100644
--- a/src/vite-env.d.ts
+++ b/src/vite-env.d.ts
@@ -5,8 +5,13 @@ interface ImportMetaEnv {
readonly VITE_SUPABASE_URL?: string
/** Clé publique « anon » / « publishable » de Supabase (publique par nature, protégée par les règles RLS) */
readonly VITE_SUPABASE_ANON_KEY?: string
+ /** « 1 » : remonter aussi les erreurs en mode dev (tests) */
+ readonly VITE_REPORT_ERRORS?: string
}
interface ImportMeta {
readonly env: ImportMetaEnv
}
+
+/** Version de l'app (package.json), injectée par vite.config.ts */
+declare const __APP_VERSION__: string
diff --git a/supabase/migrations/20261009160000_moderation.sql b/supabase/migrations/20261009160000_moderation.sql
new file mode 100644
index 0000000..50a5a76
--- /dev/null
+++ b/supabase/migrations/20261009160000_moderation.sql
@@ -0,0 +1,428 @@
+-- ════════════════════════════════════════════════════════════════════════════
+-- AzuuCine — Modération (9 octobre 2026)
+-- 1. Signalements (avis, profils ; commentaires et listes partagées prêts à brancher).
+-- 2. Tableau de modération (admin) : file des signalements regroupés par cible, actions.
+-- 3. Comptes suspendus : journal des suspensions + garde-fou sur la colonne « suspended ».
+-- 4. Blocage d'un membre : il ne peut plus te suivre ni réagir à tes avis ; ses avis
+-- sont masqués côté app.
+--
+-- À coller dans Supabase → SQL Editor → Run. Idempotent (réexécutable sans risque).
+-- Dépend de : 20261002 (profiles, follows, can_view), 20261005 (admins, is_admin,
+-- suspended, admin_clear_review), 20261007 (review_reactions).
+-- ════════════════════════════════════════════════════════════════════════════
+
+-- ═════════════════════════════ Journal de modération ═════════════════════════════
+-- Qui a fait quoi (suspensions, suppressions, signalements classés). Lisible seulement
+-- via les fonctions admin (aucun accès direct).
+create table if not exists public.moderation_log (
+ id bigint generated always as identity primary key,
+ admin_id uuid references auth.users (id) on delete set null,
+ action text not null check (char_length(action) <= 40),
+ target_type text check (target_type is null or char_length(target_type) <= 20),
+ target_id text check (target_id is null or char_length(target_id) <= 200),
+ target_user_id uuid references auth.users (id) on delete cascade,
+ created_at timestamptz not null default now()
+);
+create index if not exists moderation_log_target_idx on public.moderation_log (target_user_id, created_at desc);
+alter table public.moderation_log enable row level security;
+alter table public.moderation_log force row level security;
+revoke all on public.moderation_log from anon, authenticated;
+
+-- ── « suspended » : seuls un admin (ou le SQL Editor / service_role) peuvent la changer ──
+-- Défense en profondeur : même si une permission de colonne venait à manquer, un membre ne
+-- peut pas lever sa propre suspension en modifiant son profil.
+create or replace function public.azuu_suspended_guard()
+returns trigger language plpgsql security definer set search_path = '' as $$
+begin
+ if new.suspended is distinct from old.suspended
+ and auth.uid() is not null and not public.is_admin() then
+ raise exception 'forbidden';
+ end if;
+ return new;
+end;
+$$;
+drop trigger if exists profiles_suspended_guard on public.profiles;
+create trigger profiles_suspended_guard before update of suspended on public.profiles
+ for each row execute function public.azuu_suspended_guard();
+
+-- Chaque suspension / réactivation est journalisée (quel que soit le chemin : admin_set_suspended,
+-- admin_report_action, SQL Editor…).
+create or replace function public.azuu_suspended_log()
+returns trigger language plpgsql security definer set search_path = '' as $$
+begin
+ if new.suspended is distinct from old.suspended then
+ insert into public.moderation_log (admin_id, action, target_type, target_id, target_user_id)
+ values (auth.uid(), case when new.suspended then 'suspend' else 'unsuspend' end, 'profile', new.id::text, new.id);
+ end if;
+ return null;
+end;
+$$;
+drop trigger if exists profiles_suspended_log on public.profiles;
+create trigger profiles_suspended_log after update of suspended on public.profiles
+ for each row execute function public.azuu_suspended_log();
+
+-- ═════════════════════════════ Signalements ═════════════════════════════
+create table if not exists public.reports (
+ id bigint generated always as identity primary key,
+ reporter_id uuid not null references auth.users (id) on delete cascade,
+ target_type text not null check (target_type in ('review', 'profile', 'comment', 'list')),
+ target_id text not null check (target_id ~ '^[A-Za-z0-9_:.-]{1,200}$'),
+ target_user_id uuid not null references auth.users (id) on delete cascade, -- auteur du contenu
+ reason text not null check (reason in ('spoiler', 'harassment', 'hate', 'sexual', 'spam', 'impersonation', 'other')),
+ details text check (details is null or char_length(details) <= 500),
+ -- Copie du contenu au moment du signalement (preuve si l'auteur le modifie ou l'efface)
+ snapshot jsonb check (snapshot is null or (jsonb_typeof(snapshot) = 'object' and octet_length(snapshot::text) <= 6000)),
+ status text not null default 'open' check (status in ('open', 'resolved', 'dismissed')),
+ resolved_by uuid references auth.users (id) on delete set null,
+ resolved_at timestamptz,
+ created_at timestamptz not null default now(),
+ -- Pas deux fois la même cible par la même personne
+ unique (reporter_id, target_type, target_id, target_user_id)
+);
+create index if not exists reports_target_idx on public.reports (target_type, target_id, target_user_id);
+create index if not exists reports_status_idx on public.reports (status, created_at);
+create index if not exists reports_reporter_idx on public.reports (reporter_id, created_at desc);
+alter table public.reports enable row level security;
+alter table public.reports force row level security;
+-- Aucun accès direct : insertion via report_content(), lecture/màj via les fonctions admin.
+revoke all on public.reports from anon, authenticated;
+
+-- Signaler un contenu. Renvoie { ok: true, duplicate: bool }.
+create or replace function public.report_content(
+ p_type text, p_target_id text, p_target_user uuid, p_reason text, p_details text default null
+)
+returns jsonb language plpgsql security definer set search_path = '' as $$
+declare
+ me uuid := auth.uid();
+ d text;
+ snap jsonb;
+ n integer;
+begin
+ if me is null then raise exception 'auth'; end if;
+ if p_type is null or p_type not in ('review', 'profile', 'comment', 'list') then raise exception 'bad type'; end if;
+ if p_reason is null or p_reason not in ('spoiler', 'harassment', 'hate', 'sexual', 'spam', 'impersonation', 'other') then
+ raise exception 'bad reason';
+ end if;
+ if p_target_id is null or p_target_id !~ '^[A-Za-z0-9_:.-]{1,200}$' then raise exception 'bad target'; end if;
+ if p_target_user is null then raise exception 'bad target'; end if;
+ if p_target_user = me then raise exception 'cannot report yourself'; end if;
+ -- Un compte suspendu ne signale pas
+ if exists (select 1 from public.profiles p where p.id = me and p.suspended) then raise exception 'forbidden'; end if;
+
+ -- Précision facultative : sans caractères de contrôle, 500 caractères max
+ d := nullif(trim(regexp_replace(coalesce(p_details, ''), '[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]', '', 'g')), '');
+ if d is not null and char_length(d) > 500 then raise exception 'details too long'; end if;
+
+ -- La cible doit exister ET être visible de la personne qui signale
+ if p_type = 'review' then
+ select jsonb_build_object('title', left(i.data->>'title', 200), 'notes', left(i.data->>'notes', 3000),
+ 'rating', i.data->'rating', 'externalId', left(i.data->>'externalId', 60))
+ into snap
+ from public.items i
+ where i.user_id = p_target_user and i.id = p_target_id and not i.deleted
+ and coalesce(i.data->>'notes', '') <> '';
+ if snap is null or not public.can_view(p_target_user) then raise exception 'not found'; end if;
+ elsif p_type = 'profile' then
+ if p_target_id <> p_target_user::text then raise exception 'bad target'; end if;
+ select jsonb_build_object('username', p.username, 'display_name', p.display_name, 'bio', p.bio,
+ 'avatar_url', p.avatar_url, 'banner_url', p.banner_url)
+ into snap
+ from public.profiles p where p.id = p_target_user;
+ if snap is null then raise exception 'not found'; end if;
+ else
+ -- 'comment' / 'list' : tables ajoutées par d'autres migrations. On vérifie au minimum que
+ -- l'auteur existe et que son contenu m'est visible ; la copie du contenu sera ajoutée à la fusion.
+ if not exists (select 1 from public.profiles p where p.id = p_target_user) or not public.can_view(p_target_user) then
+ raise exception 'not found';
+ end if;
+ end if;
+
+ -- Anti-abus : 20 signalements par 24 h, 5 par minute
+ select count(*) into n from public.reports r where r.reporter_id = me and r.created_at > now() - interval '1 day';
+ if n >= 20 then raise exception 'rate limited'; end if;
+ select count(*) into n from public.reports r where r.reporter_id = me and r.created_at > now() - interval '1 minute';
+ if n >= 5 then raise exception 'rate limited'; end if;
+
+ insert into public.reports (reporter_id, target_type, target_id, target_user_id, reason, details, snapshot)
+ values (me, p_type, p_target_id, p_target_user, p_reason, d, snap)
+ on conflict (reporter_id, target_type, target_id, target_user_id) do nothing;
+ return jsonb_build_object('ok', true, 'duplicate', not found);
+end;
+$$;
+
+-- ═════════════════════════════ Blocage ═════════════════════════════
+create table if not exists public.blocks (
+ blocker_id uuid not null references auth.users (id) on delete cascade,
+ blocked_id uuid not null references auth.users (id) on delete cascade,
+ created_at timestamptz not null default now(),
+ primary key (blocker_id, blocked_id),
+ check (blocker_id <> blocked_id)
+);
+create index if not exists blocks_blocked_idx on public.blocks (blocked_id);
+alter table public.blocks enable row level security;
+alter table public.blocks force row level security;
+revoke all on public.blocks from anon, authenticated;
+
+-- Bloquer : retire aussi les abonnements dans les deux sens.
+create or replace function public.block_user(p_user uuid)
+returns jsonb language plpgsql security definer set search_path = '' as $$
+declare me uuid := auth.uid();
+begin
+ if me is null then raise exception 'auth'; end if;
+ if p_user is null or p_user = me then raise exception 'bad target'; end if;
+ if not exists (select 1 from public.profiles p where p.id = p_user) then raise exception 'not found'; end if;
+ if (select count(*) from public.blocks b where b.blocker_id = me) >= 1000 then raise exception 'too many blocks'; end if;
+ insert into public.blocks (blocker_id, blocked_id) values (me, p_user) on conflict do nothing;
+ delete from public.follows f
+ where (f.follower_id = me and f.following_id = p_user) or (f.follower_id = p_user and f.following_id = me);
+ return jsonb_build_object('ok', true);
+end;
+$$;
+
+create or replace function public.unblock_user(p_user uuid)
+returns jsonb language plpgsql security definer set search_path = '' as $$
+begin
+ if auth.uid() is null then raise exception 'auth'; end if;
+ delete from public.blocks b where b.blocker_id = auth.uid() and b.blocked_id = p_user;
+ return jsonb_build_object('ok', true);
+end;
+$$;
+
+-- Mes blocages (pour masquer les contenus côté app)
+create or replace function public.my_blocks()
+returns jsonb language sql stable security definer set search_path = '' as $$
+ select coalesce(jsonb_agg(jsonb_build_object(
+ 'id', b.blocked_id, 'username', p.username, 'display_name', p.display_name,
+ 'avatar_url', p.avatar_url, 'created_at', b.created_at) order by b.created_at desc), '[]'::jsonb)
+ from public.blocks b
+ left join public.profiles p on p.id = b.blocked_id
+ where b.blocker_id = auth.uid()
+$$;
+
+-- Un compte bloqué ne peut plus s'abonner (ni dans l'autre sens).
+-- Nom choisi pour passer APRÈS « follows_guard » (ordre alphabétique) qui fixe follower_id.
+create or replace function public.azuu_follow_block_guard()
+returns trigger language plpgsql security definer set search_path = '' as $$
+begin
+ if exists (select 1 from public.blocks b
+ where (b.blocker_id = new.following_id and b.blocked_id = new.follower_id)
+ or (b.blocker_id = new.follower_id and b.blocked_id = new.following_id)) then
+ raise exception 'blocked';
+ end if;
+ return new;
+end;
+$$;
+drop trigger if exists follows_zblock_guard on public.follows;
+create trigger follows_zblock_guard before insert on public.follows
+ for each row execute function public.azuu_follow_block_guard();
+
+-- … ni réagir à mes avis (pas de notification non plus, donc).
+create or replace function public.azuu_reaction_block_guard()
+returns trigger language plpgsql security definer set search_path = '' as $$
+begin
+ if exists (select 1 from public.blocks b where b.blocker_id = new.author_id and b.blocked_id = new.user_id) then
+ raise exception 'blocked';
+ end if;
+ return new;
+end;
+$$;
+do $$ begin
+ if to_regclass('public.review_reactions') is not null then
+ execute 'drop trigger if exists review_reactions_block_guard on public.review_reactions';
+ execute 'create trigger review_reactions_block_guard before insert or update on public.review_reactions
+ for each row execute function public.azuu_reaction_block_guard()';
+ end if;
+end $$;
+
+-- ═════════════════════════════ Administration ═════════════════════════════
+
+-- Petite carte « compte » pour l'admin
+create or replace function public.azuu_admin_card(p_user uuid)
+returns jsonb language sql stable security definer set search_path = '' as $$
+ select case when p.id is null then null else jsonb_build_object(
+ 'id', p.id, 'username', p.username, 'display_name', p.display_name,
+ 'avatar_url', p.avatar_url, 'suspended', p.suspended,
+ 'is_admin', exists (select 1 from public.admins a where a.user_id = p.id)) end
+ from (select 1) x left join public.profiles p on p.id = p_user
+$$;
+
+-- File des signalements, regroupés par cible.
+-- p_status = 'open' : cibles ayant au moins un signalement ouvert (les plus signalées d'abord, puis les plus anciennes)
+-- = 'closed' : cibles entièrement traitées (les plus récentes d'abord)
+create or replace function public.admin_reports(p_status text default 'open', p_offset integer default 0)
+returns jsonb language plpgsql stable security definer set search_path = '' as $$
+declare
+ res jsonb;
+ open_q boolean := coalesce(p_status, 'open') = 'open';
+begin
+ if not public.is_admin() then raise exception 'forbidden'; end if;
+ with g as (
+ select r.target_type, r.target_id, r.target_user_id,
+ count(*)::int as total,
+ (count(*) filter (where r.status = 'open'))::int as open_count,
+ min(r.created_at) as first_at,
+ max(r.created_at) as last_at,
+ (array_agg(r.status order by r.resolved_at desc nulls last, r.created_at desc))[1] as last_status
+ from public.reports r
+ group by r.target_type, r.target_id, r.target_user_id
+ ),
+ page as (
+ select g.* from g
+ where (open_q and g.open_count > 0) or (not open_q and g.open_count = 0)
+ order by case when open_q then g.total end desc nulls last,
+ case when open_q then g.first_at end asc nulls last,
+ g.last_at desc
+ offset greatest(coalesce(p_offset, 0), 0) limit 30
+ )
+ select coalesce(jsonb_agg(jsonb_build_object(
+ 'target_type', pg.target_type,
+ 'target_id', pg.target_id,
+ 'target_user', public.azuu_admin_card(pg.target_user_id),
+ 'total', pg.total,
+ 'open_count', pg.open_count,
+ 'first_at', pg.first_at,
+ 'last_at', pg.last_at,
+ 'status', case when pg.open_count > 0 then 'open' else pg.last_status end,
+ -- motif -> nombre
+ 'reasons', (select jsonb_object_agg(x.reason, x.c) from (
+ select r.reason, count(*)::int c from public.reports r
+ where r.target_type = pg.target_type and r.target_id = pg.target_id and r.target_user_id = pg.target_user_id
+ group by r.reason) x),
+ -- 10 derniers signalements (avec précision)
+ 'reports', (select coalesce(jsonb_agg(y.e order by y.created_at desc), '[]'::jsonb) from (
+ select jsonb_build_object('reason', r.reason, 'details', r.details, 'created_at', r.created_at, 'status', r.status,
+ 'reporter', public.azuu_admin_card(r.reporter_id)) e, r.created_at
+ from public.reports r
+ where r.target_type = pg.target_type and r.target_id = pg.target_id and r.target_user_id = pg.target_user_id
+ order by r.created_at desc limit 10) y),
+ -- Contenu au moment du (dernier) signalement
+ 'snapshot', (select r.snapshot from public.reports r
+ where r.target_type = pg.target_type and r.target_id = pg.target_id and r.target_user_id = pg.target_user_id
+ and r.snapshot is not null order by r.created_at desc limit 1),
+ -- Contenu actuel (null s'il a été effacé)
+ 'current', case pg.target_type
+ when 'review' then (select jsonb_build_object('title', left(i.data->>'title', 200), 'notes', left(i.data->>'notes', 3000),
+ 'rating', i.data->'rating')
+ from public.items i where i.user_id = pg.target_user_id and i.id = pg.target_id
+ and not i.deleted and coalesce(i.data->>'notes', '') <> '')
+ when 'profile' then (select jsonb_build_object('username', p.username, 'display_name', p.display_name, 'bio', p.bio,
+ 'avatar_url', p.avatar_url, 'banner_url', p.banner_url)
+ from public.profiles p where p.id = pg.target_user_id)
+ else null end,
+ -- Antécédents : nombre de contenus différents de ce compte déjà signalés
+ 'user_reported_targets', (select count(distinct (r.target_type, r.target_id))::int from public.reports r
+ where r.target_user_id = pg.target_user_id)
+ ) order by case when open_q then pg.total end desc nulls last,
+ case when open_q then pg.first_at end asc nulls last,
+ pg.last_at desc), '[]'::jsonb)
+ into res
+ from page pg;
+ return res;
+end;
+$$;
+
+-- Action sur une cible signalée.
+-- p_action : 'delete' (efface le contenu + résout), 'suspend' (suspend l'auteur + résout),
+-- 'unsuspend', 'dismiss' (classe sans suite), 'resolve' (marque résolu)
+create or replace function public.admin_report_action(p_type text, p_target_id text, p_target_user uuid, p_action text)
+returns jsonb language plpgsql security definer set search_path = '' as $$
+declare
+ me uuid := auth.uid();
+ n integer := 0;
+begin
+ if not public.is_admin() then raise exception 'forbidden'; end if;
+ if p_type is null or p_type not in ('review', 'profile', 'comment', 'list') then raise exception 'bad type'; end if;
+ if p_action is null or p_action not in ('delete', 'suspend', 'unsuspend', 'dismiss', 'resolve') then raise exception 'bad action'; end if;
+ if p_target_user is null then raise exception 'bad target'; end if;
+
+ if p_action = 'delete' then
+ if p_type = 'review' then
+ -- Même chemin que l'onglet « Avis » (renvoyé à l'appareil du membre à la synchro)
+ perform public.admin_clear_review(p_target_user, p_target_id);
+ elsif p_type = 'profile' then
+ if p_target_id <> p_target_user::text then raise exception 'bad target'; end if;
+ -- Remet le profil à zéro : bio, photo et bannière effacées, nom affiché = pseudo
+ update public.profiles p set bio = '', avatar_url = null, banner_url = null, display_name = p.username
+ where p.id = p_target_user;
+ else
+ -- 'comment' / 'list' : à brancher quand ces tables existent (fusion des fonctionnalités)
+ raise exception 'unsupported target';
+ end if;
+ elsif p_action in ('suspend', 'unsuspend') then
+ if p_target_user = me then raise exception 'cannot suspend yourself'; end if;
+ if p_action = 'suspend' and exists (select 1 from public.admins a where a.user_id = p_target_user) then
+ raise exception 'cannot suspend an admin';
+ end if;
+ update public.profiles set suspended = (p_action = 'suspend') where id = p_target_user;
+ end if;
+
+ if p_action in ('delete', 'suspend', 'resolve', 'dismiss') then
+ update public.reports r
+ set status = case when p_action = 'dismiss' then 'dismissed' else 'resolved' end,
+ resolved_by = me, resolved_at = now()
+ where r.target_type = p_type and r.target_id = p_target_id and r.target_user_id = p_target_user and r.status = 'open';
+ get diagnostics n = row_count;
+ end if;
+
+ -- (suspensions déjà journalisées par le déclencheur)
+ if p_action not in ('suspend', 'unsuspend') then
+ insert into public.moderation_log (admin_id, action, target_type, target_id, target_user_id)
+ values (me, 'report_' || p_action, p_type, p_target_id, p_target_user);
+ end if;
+ return jsonb_build_object('ok', true, 'reports', n);
+end;
+$$;
+
+-- Comptes suspendus (les plus récemment suspendus d'abord)
+create or replace function public.admin_suspended_users(p_offset integer default 0)
+returns jsonb language plpgsql stable security definer set search_path = '' as $$
+declare res jsonb;
+begin
+ if not public.is_admin() then raise exception 'forbidden'; end if;
+ select coalesce(jsonb_agg(x.e order by x.since desc nulls last, x.username), '[]'::jsonb) into res
+ from (
+ select p.username,
+ l.created_at as since,
+ jsonb_build_object(
+ 'id', p.id, 'username', p.username, 'display_name', p.display_name, 'avatar_url', p.avatar_url,
+ 'suspended_at', l.created_at,
+ 'suspended_by', case when l.admin_id is null then null else
+ (select a.username from public.profiles a where a.id = l.admin_id) end,
+ 'reports', (select count(*)::int from public.reports r where r.target_user_id = p.id),
+ 'created_at', p.created_at) e
+ from public.profiles p
+ left join lateral (
+ select ml.created_at, ml.admin_id from public.moderation_log ml
+ where ml.target_user_id = p.id and ml.action = 'suspend'
+ order by ml.created_at desc limit 1
+ ) l on true
+ where p.suspended
+ order by l.created_at desc nulls last, p.username
+ offset greatest(coalesce(p_offset, 0), 0) limit 50
+ ) x;
+ return res;
+end;
+$$;
+
+-- ═════════════════════════════ Droits ═════════════════════════════
+revoke all on function public.azuu_suspended_guard() from public, anon, authenticated;
+revoke all on function public.azuu_suspended_log() from public, anon, authenticated;
+revoke all on function public.azuu_follow_block_guard() from public, anon, authenticated;
+revoke all on function public.azuu_reaction_block_guard() from public, anon, authenticated;
+revoke all on function public.azuu_admin_card(uuid) from public, anon, authenticated;
+
+revoke all on function public.report_content(text, text, uuid, text, text) from public, anon;
+revoke all on function public.block_user(uuid) from public, anon;
+revoke all on function public.unblock_user(uuid) from public, anon;
+revoke all on function public.my_blocks() from public, anon;
+revoke all on function public.admin_reports(text, integer) from public, anon;
+revoke all on function public.admin_report_action(text, text, uuid, text) from public, anon;
+revoke all on function public.admin_suspended_users(integer) from public, anon;
+
+grant execute on function public.report_content(text, text, uuid, text, text) to authenticated;
+grant execute on function public.block_user(uuid) to authenticated;
+grant execute on function public.unblock_user(uuid) to authenticated;
+grant execute on function public.my_blocks() to authenticated;
+grant execute on function public.admin_reports(text, integer) to authenticated;
+grant execute on function public.admin_report_action(text, text, uuid, text) to authenticated;
+grant execute on function public.admin_suspended_users(integer) to authenticated;
diff --git a/supabase/migrations/20261009160100_bugs_errors.sql b/supabase/migrations/20261009160100_bugs_errors.sql
new file mode 100644
index 0000000..9e192a0
--- /dev/null
+++ b/supabase/migrations/20261009160100_bugs_errors.sql
@@ -0,0 +1,268 @@
+-- ════════════════════════════════════════════════════════════════════════════
+-- AzuuCine — « Signaler un bug » + remontée d'erreurs (9 octobre 2026)
+-- 1. bug_reports : formulaire des Réglages (comptes connectés, 5 par jour).
+-- 2. client_errors : erreurs JavaScript de l'app, regroupées par empreinte, sans donnée perso
+-- (équivalent Sentry minimal, sans service tiers). Écriture ouverte à anon
+-- mais bornée (taille, débit par empreinte et par heure, taille de la table).
+-- 3. admin_alerts : compteurs pour le badge de l'administration.
+--
+-- À coller dans Supabase → SQL Editor → Run, APRÈS 20261009160000_moderation.sql.
+-- Idempotent (réexécutable sans risque).
+-- ════════════════════════════════════════════════════════════════════════════
+
+-- ═════════════════════════════ Nettoyage des textes ═════════════════════════════
+-- Retire ce qui pourrait identifier quelqu'un : e-mails, jetons (JWT, clés), UUID,
+-- paramètres d'URL (?…, #…), longues suites de chiffres.
+create or replace function public.azuu_scrub(p text, p_max integer)
+returns text language sql immutable set search_path = '' as $$
+ select left(
+ regexp_replace(
+ regexp_replace(
+ regexp_replace(
+ regexp_replace(
+ regexp_replace(
+ regexp_replace(
+ regexp_replace(coalesce(p, ''), '[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]', '', 'g'),
+ '[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}', '[email]', 'g'),
+ 'eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+(\.[A-Za-z0-9_-]*)?', '[token]', 'g'),
+ '(sb_(publishable|secret)_|sk_|pk_)[A-Za-z0-9_-]+', '[key]', 'g'),
+ '[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}', '[id]', 'g'),
+ '(https?://[^\s?#''"()]+)[?#][^\s''"()]*', '\1', 'g'),
+ '[A-Za-z0-9_-]{40,}', '[token]', 'g'),
+ greatest(p_max, 0))
+$$;
+revoke all on function public.azuu_scrub(text, integer) from public, anon, authenticated;
+
+-- ═════════════════════════════ Signaler un bug ═════════════════════════════
+create table if not exists public.bug_reports (
+ id bigint generated always as identity primary key,
+ user_id uuid not null references auth.users (id) on delete cascade,
+ description text not null check (char_length(description) between 10 and 2000),
+ -- Infos techniques (version, navigateur, langue, thème, écran, page) — liste blanche de clés
+ context jsonb not null default '{}'::jsonb check (jsonb_typeof(context) = 'object' and octet_length(context::text) <= 2000),
+ status text not null default 'new' check (status in ('new', 'in_progress', 'fixed')),
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now()
+);
+create index if not exists bug_reports_status_idx on public.bug_reports (status, created_at desc);
+create index if not exists bug_reports_user_idx on public.bug_reports (user_id, created_at desc);
+alter table public.bug_reports enable row level security;
+alter table public.bug_reports force row level security;
+revoke all on public.bug_reports from anon, authenticated;
+
+create or replace function public.submit_bug_report(p_description text, p_context jsonb default '{}'::jsonb)
+returns jsonb language plpgsql security definer set search_path = '' as $$
+declare
+ me uuid := auth.uid();
+ d text;
+ ctx jsonb := '{}'::jsonb;
+ k text;
+ new_id bigint;
+begin
+ if me is null then raise exception 'auth'; end if;
+ d := trim(regexp_replace(coalesce(p_description, ''), '[\x00-\x08\x0B\x0C\x0E-\x1F\x7F]', '', 'g'));
+ if char_length(d) < 10 then raise exception 'too short'; end if;
+ if char_length(d) > 2000 then raise exception 'too long'; end if;
+ if (select count(*) from public.bug_reports b where b.user_id = me and b.created_at > now() - interval '1 day') >= 5 then
+ raise exception 'rate limited';
+ end if;
+ -- Seules ces clés sont gardées, en texte court nettoyé
+ if jsonb_typeof(p_context) = 'object' then
+ foreach k in array array['version', 'browser', 'os', 'lang', 'theme', 'screen', 'viewport', 'route', 'online', 'standalone'] loop
+ if p_context ? k and jsonb_typeof(p_context->k) in ('string', 'number', 'boolean') then
+ ctx := ctx || jsonb_build_object(k, public.azuu_scrub(p_context->>k, 80));
+ end if;
+ end loop;
+ end if;
+ insert into public.bug_reports (user_id, description, context) values (me, d, ctx) returning id into new_id;
+ return jsonb_build_object('ok', true, 'id', new_id);
+end;
+$$;
+
+create or replace function public.admin_bug_reports(p_status text default null, p_offset integer default 0)
+returns jsonb language plpgsql stable security definer set search_path = '' as $$
+declare res jsonb;
+begin
+ if not public.is_admin() then raise exception 'forbidden'; end if;
+ select coalesce(jsonb_agg(x.e order by x.rank, x.created_at desc), '[]'::jsonb) into res
+ from (
+ select b.created_at,
+ case b.status when 'new' then 0 when 'in_progress' then 1 else 2 end as rank,
+ jsonb_build_object('id', b.id, 'description', b.description, 'context', b.context, 'status', b.status,
+ 'created_at', b.created_at, 'updated_at', b.updated_at,
+ 'reporter', public.azuu_admin_card(b.user_id)) e
+ from public.bug_reports b
+ where p_status is null or b.status = p_status
+ order by case b.status when 'new' then 0 when 'in_progress' then 1 else 2 end, b.created_at desc
+ offset greatest(coalesce(p_offset, 0), 0) limit 30
+ ) x;
+ return res;
+end;
+$$;
+
+create or replace function public.admin_set_bug_status(p_id bigint, p_status text)
+returns jsonb language plpgsql security definer set search_path = '' as $$
+begin
+ if not public.is_admin() then raise exception 'forbidden'; end if;
+ if p_status is null or p_status not in ('new', 'in_progress', 'fixed') then raise exception 'bad status'; end if;
+ update public.bug_reports set status = p_status, updated_at = now() where id = p_id;
+ return jsonb_build_object('ok', found);
+end;
+$$;
+
+-- ═════════════════════════════ Remontée d'erreurs ═════════════════════════════
+create table if not exists public.client_errors (
+ fingerprint text primary key check (fingerprint ~ '^[0-9a-f]{32}$'),
+ source text not null default 'error' check (source in ('error', 'rejection', 'render')),
+ message text not null check (char_length(message) between 1 and 500),
+ stack text check (stack is null or char_length(stack) <= 4000),
+ url text check (url is null or char_length(url) <= 300),
+ app_version text check (app_version is null or char_length(app_version) <= 40),
+ user_agent text check (user_agent is null or char_length(user_agent) <= 300),
+ count integer not null default 1,
+ -- Débit : nombre d'occurrences dans l'heure en cours (au-delà de 100, on ne compte plus)
+ hour_start timestamptz not null default date_trunc('hour', now()),
+ hour_count integer not null default 1,
+ status text not null default 'new' check (status in ('new', 'seen', 'fixed')),
+ first_seen timestamptz not null default now(),
+ last_seen timestamptz not null default now()
+);
+create index if not exists client_errors_last_idx on public.client_errors (last_seen desc);
+create index if not exists client_errors_first_idx on public.client_errors (first_seen desc);
+alter table public.client_errors enable row level security;
+alter table public.client_errors force row level security;
+revoke all on public.client_errors from anon, authenticated;
+
+-- Appelée par l'app (avec ou sans compte). Ne renvoie rien d'utile à un attaquant.
+create or replace function public.log_client_error(
+ p_message text, p_stack text default null, p_url text default null,
+ p_version text default null, p_ua text default null, p_source text default 'error'
+)
+returns void language plpgsql security definer set search_path = '' as $$
+declare
+ msg text;
+ st text;
+ u text;
+ v text;
+ ua text;
+ src text;
+ first_line text;
+ fp text;
+begin
+ -- Corps trop gros : on ignore sans rien analyser
+ if p_message is null or octet_length(p_message) > 4000 or octet_length(coalesce(p_stack, '')) > 20000
+ or octet_length(coalesce(p_url, '')) > 2000 or octet_length(coalesce(p_ua, '')) > 1000 then
+ return;
+ end if;
+ msg := nullif(trim(public.azuu_scrub(p_message, 500)), '');
+ if msg is null then return; end if;
+ st := nullif(trim(public.azuu_scrub(p_stack, 4000)), '');
+ -- Adresse : origine + chemin seulement (ni paramètres ni ancre)
+ u := nullif(left(regexp_replace(coalesce(p_url, ''), '[?#].*$', ''), 300), '');
+ if u is not null and u !~ '^https?://[^\s]+$' then u := null; end if;
+ if u is not null then u := public.azuu_scrub(u, 300); end if;
+ v := case when coalesce(p_version, '') ~ '^[0-9A-Za-z._+-]{1,40}$' then p_version end;
+ ua := nullif(public.azuu_scrub(p_ua, 300), '');
+ src := case when p_source in ('error', 'rejection', 'render') then p_source else 'error' end;
+
+ -- Empreinte calculée ici (pas par le client) : message sans nombres + 1re ligne de pile sans n° de ligne
+ first_line := coalesce((regexp_match(coalesce(st, ''), '([^\n]*\S[^\n]*)'))[1], '');
+ -- La 1re ligne de pile répète souvent le message (Chrome : « TypeError: … ») : on prend la 1re ligne « at … »
+ first_line := coalesce((regexp_match(coalesce(st, ''), '\n\s*(at [^\n]+|[^\n]*@[^\n]+)'))[1], first_line);
+ fp := md5(src || '|' || regexp_replace(lower(msg), '[0-9]+', '0', 'g') || '|'
+ || regexp_replace(regexp_replace(first_line, ':[0-9]+(:[0-9]+)?', '', 'g'), '-[A-Za-z0-9_-]{8}\.js', '.js', 'g'));
+
+ if not exists (select 1 from public.client_errors e where e.fingerprint = fp) then
+ -- Nouvelles empreintes : 30 par heure maximum (inondation d'erreurs inventées)
+ if (select count(*) from public.client_errors e where e.first_seen > now() - interval '1 hour') >= 30 then
+ return;
+ end if;
+ -- Table bornée : au-delà de 2000 empreintes, on oublie les plus anciennes
+ delete from public.client_errors e where e.fingerprint in (
+ select e2.fingerprint from public.client_errors e2 order by e2.last_seen desc offset 1999
+ );
+ end if;
+
+ insert into public.client_errors as e (fingerprint, source, message, stack, url, app_version, user_agent)
+ values (fp, src, msg, st, u, v, ua)
+ on conflict (fingerprint) do update set
+ count = e.count + case when e.hour_start < date_trunc('hour', now()) or e.hour_count < 100 then 1 else 0 end,
+ hour_count = case when e.hour_start < date_trunc('hour', now()) then 1 else least(e.hour_count + 1, 100) end,
+ hour_start = date_trunc('hour', now()),
+ last_seen = now(),
+ url = coalesce(excluded.url, e.url),
+ app_version = coalesce(excluded.app_version, e.app_version),
+ user_agent = coalesce(excluded.user_agent, e.user_agent),
+ -- Une erreur marquée « corrigée » qui revient redevient « nouvelle » (régression)
+ status = case when e.status = 'fixed' then 'new' else e.status end;
+end;
+$$;
+
+create or replace function public.admin_client_errors(p_status text default null, p_offset integer default 0)
+returns jsonb language plpgsql stable security definer set search_path = '' as $$
+declare res jsonb;
+begin
+ if not public.is_admin() then raise exception 'forbidden'; end if;
+ select coalesce(jsonb_agg(to_jsonb(x) - 'hour_start' - 'hour_count' order by x.last_seen desc), '[]'::jsonb) into res
+ from (
+ select * from public.client_errors e
+ where p_status is null or e.status = p_status
+ order by e.last_seen desc
+ offset greatest(coalesce(p_offset, 0), 0) limit 50
+ ) x;
+ return res;
+end;
+$$;
+
+-- p_fingerprint null + 'seen' : tout marquer comme vu (à l'ouverture de l'onglet)
+create or replace function public.admin_set_error_status(p_fingerprint text, p_status text)
+returns jsonb language plpgsql security definer set search_path = '' as $$
+declare n integer;
+begin
+ if not public.is_admin() then raise exception 'forbidden'; end if;
+ if p_status is null or p_status not in ('new', 'seen', 'fixed', 'delete') then raise exception 'bad status'; end if;
+ if p_fingerprint is null then
+ if p_status <> 'seen' then raise exception 'bad status'; end if;
+ update public.client_errors set status = 'seen' where status = 'new';
+ elsif p_status = 'delete' then
+ delete from public.client_errors where fingerprint = p_fingerprint;
+ else
+ update public.client_errors set status = p_status where fingerprint = p_fingerprint;
+ end if;
+ get diagnostics n = row_count;
+ return jsonb_build_object('ok', true, 'count', n);
+end;
+$$;
+
+-- Compteurs du badge « Administration »
+create or replace function public.admin_alerts()
+returns jsonb language plpgsql stable security definer set search_path = '' as $$
+begin
+ if not public.is_admin() then raise exception 'forbidden'; end if;
+ return jsonb_build_object(
+ 'reports', (select count(*)::int from (select 1 from public.reports r where r.status = 'open'
+ group by r.target_type, r.target_id, r.target_user_id) t),
+ 'bugs', (select count(*)::int from public.bug_reports b where b.status = 'new'),
+ 'errors', (select count(*)::int from public.client_errors e where e.status = 'new'),
+ 'suspended', (select count(*)::int from public.profiles p where p.suspended)
+ );
+end;
+$$;
+
+-- ═════════════════════════════ Droits ═════════════════════════════
+revoke all on function public.submit_bug_report(text, jsonb) from public, anon;
+revoke all on function public.admin_bug_reports(text, integer) from public, anon;
+revoke all on function public.admin_set_bug_status(bigint, text) from public, anon;
+revoke all on function public.log_client_error(text, text, text, text, text, text) from public;
+revoke all on function public.admin_client_errors(text, integer) from public, anon;
+revoke all on function public.admin_set_error_status(text, text) from public, anon;
+revoke all on function public.admin_alerts() from public, anon;
+
+grant execute on function public.submit_bug_report(text, jsonb) to authenticated;
+grant execute on function public.admin_bug_reports(text, integer) to authenticated;
+grant execute on function public.admin_set_bug_status(bigint, text) to authenticated;
+-- Seule fonction ouverte aux visiteurs non connectés (l'écran de connexion peut planter aussi)
+grant execute on function public.log_client_error(text, text, text, text, text, text) to anon, authenticated;
+grant execute on function public.admin_client_errors(text, integer) to authenticated;
+grant execute on function public.admin_set_error_status(text, text) to authenticated;
+grant execute on function public.admin_alerts() to authenticated;
diff --git a/vite.config.ts b/vite.config.ts
index 10bb443..641e32d 100644
--- a/vite.config.ts
+++ b/vite.config.ts
@@ -82,6 +82,8 @@ export default defineConfig(({ mode }) => {
const supabaseUrl = /^https:\/\/[a-z0-9-]+\.supabase\.(co|in)$/i.test(origin) ? origin : ''
return {
base: '/',
+ // Version de l'app (package.json, fournie par « npm run … »), affichée dans « Signaler un bug » et jointe aux erreurs remontées
+ define: { __APP_VERSION__: JSON.stringify(full.npm_package_version || 'dev') },
// Le serveur de dev n'écoute que sur ce PC (voir « npm run dev:mobile » pour tester sur le téléphone)
server: { host: 'localhost', strictPort: false },
preview: { host: 'localhost' },