SPB Git

Repository Public

inscriptions.py 15.4 KB 346 lines python

1# -----------------------------------------------------------------------------2# Fabri-Ka v2 — inscription d'une boutique (formulaire public, sans compte)3# Auteur : Simon-Pierre Boucher — contact@spboucher.ai4# inscriptions.py :5#   POST /api/inscriptions                 dépôt public → file de modération6#   GET  /api/inscriptions                 liste (X-Admin-Token)7#   POST /api/inscriptions/{id}/decision   approve | reject (X-Admin-Token)8#   GET  /api/inscriptions/form            champs, limites et taxonomie du formulaire9#10#   La file vit dans une base PROPRE à la v2 (var/inscriptions.db) : rien n'est11#   écrit dans la base ni dans le registre de la collecte. Une demande acceptée12#   reste dans cette file avec le statut `approved` ; l'intégration au registre13#   se fait hors ligne par scripts/inscriptions_admin.py, qui l'exporte pour le14#   veilleur. Rien n'est publié par cette API.15#16#   Ce qui est enregistré pour une demande : nom, spécialité, description,17#   adresse postale (facultative), site, courriel et/ou téléphone, jusqu'à six18#   liens de réseaux sociaux, l'horodatage, et une EMPREINTE de l'adresse IP19#   (SHA-256 salé, tronqué) servant seulement à limiter les abus. L'adresse IP20#   elle-même n'est jamais conservée, ni dans la base ni dans un journal.21# -----------------------------------------------------------------------------22from __future__ import annotations2324import hashlib25import hmac26import json27import os28import re29import sqlite330import threading31import time32from pathlib import Path33from urllib.parse import urlsplit3435from fastapi import APIRouter, HTTPException, Request36from pydantic import BaseModel, Field3738from . import categories as cats39from . import texte4041router = APIRouter(prefix="/api/inscriptions")4243ROOT = Path(__file__).resolve().parent.parent44VAR = Path(os.environ.get("FABRIKA_VAR") or ROOT / "var")45DB = VAR / "inscriptions.db"46ADMIN_TOKEN = os.environ.get("FABRIKA_ADMIN_TOKEN", "")4748MAX_PAR_IP_24H = 349MAX_PAR_IP_HEURE_REFUS = 20       # tentatives invalides tolérées par heure50MAX_GLOBAL_24H = 200              # au-delà : file fermée jusqu'au lendemain51MAX_EN_ATTENTE = 100052MAX_CORPS = 16 * 10245354_verrou = threading.Lock()55_refus: dict[str, list[float]] = {}565758def _con() -> sqlite3.Connection:59    VAR.mkdir(parents=True, exist_ok=True)60    con = sqlite3.connect(DB, timeout=30)61    con.row_factory = sqlite3.Row62    con.execute("PRAGMA journal_mode=WAL")63    con.execute("""CREATE TABLE IF NOT EXISTS inscriptions (64        id INTEGER PRIMARY KEY AUTOINCREMENT,65        ts REAL NOT NULL, ip_hash TEXT NOT NULL,66        name TEXT NOT NULL, category TEXT NOT NULL, description TEXT NOT NULL,67        address TEXT, website TEXT, domain TEXT, email TEXT, phone TEXT, socials TEXT,68        status TEXT NOT NULL DEFAULT 'pending',     -- pending | approved | rejected69        reviewed_at REAL, review_note TEXT, exported_at REAL)""")70    con.execute("CREATE INDEX IF NOT EXISTS i_ins_ip ON inscriptions(ip_hash, ts)")71    con.execute("CREATE INDEX IF NOT EXISTS i_ins_status ON inscriptions(status, ts)")72    con.execute("CREATE TABLE IF NOT EXISTS meta (k TEXT PRIMARY KEY, v TEXT)")73    return con747576def _sel(con) -> bytes:77    r = con.execute("SELECT v FROM meta WHERE k='sel'").fetchone()78    if r:79        return bytes.fromhex(r[0])80    s = os.urandom(24)81    con.execute("INSERT OR IGNORE INTO meta VALUES ('sel', ?)", (s.hex(),))82    con.commit()83    return bytes.fromhex(con.execute("SELECT v FROM meta WHERE k='sel'").fetchone()[0])848586def _ip(request: Request) -> str:87    """Adresse du client : derrière le tunnel, le premier X-Forwarded-For."""88    fwd = request.headers.get("x-forwarded-for", "")89    ip = fwd.split(",")[0].strip() if fwd else (request.client.host if request.client else "")90    return ip[:64] or "?"919293def _empreinte(con, ip: str) -> str:94    return hmac.new(_sel(con), ip.encode(), hashlib.sha256).hexdigest()[:24]959697_NOM = re.compile(r"^[\w\s'’&.,()+\-/!·]+$", re.UNICODE)98_URL_INTERDITE = re.compile(r"^(localhost|\d+\.\d+\.\d+\.\d+|\[.*\]|.*\.(local|internal|lan|test|invalid))$")99_SPAM = re.compile(r"(?i)\b(viagra|casino|crypto|bitcoin|forex|seo services?|backlinks?|escort|porn|"100                   r"loan|payday|betting|telegram|whatsapp \+)\b")101_RESEAUX = ("facebook.com", "instagram.com", "tiktok.com", "youtube.com", "linkedin.com",102            "pinterest.com", "pinterest.ca", "x.com", "twitter.com", "etsy.com")103104105class Demande(BaseModel):106    name: str = Field(min_length=2, max_length=120)107    category: str = Field(min_length=2, max_length=40)       # clé de la taxonomie108    description: str = Field(min_length=40, max_length=2000)109    website: str = Field(min_length=4, max_length=200)110    address: str = Field("", max_length=200)111    email: str = Field("", max_length=160)112    phone: str = Field("", max_length=40)113    socials: list[str] = Field(default_factory=list, max_length=6)114    consent: bool = False115    # pot de miel : champ invisible dans l'interface — un humain le laisse vide116    company_url: str = Field("", max_length=300)117118119def _site(v: str) -> tuple[str, str]:120    v = v.strip()121    if not re.match(r"^https?://", v, re.I):122        v = "https://" + v123    p = urlsplit(v)124    host = (p.hostname or "").lower()125    if p.scheme not in ("http", "https") or "." not in host or _URL_INTERDITE.match(host) \126            or p.username or p.port not in (None, 80, 443) or len(host) > 100 \127            or not re.fullmatch(r"[a-z0-9.\-]+", host):128        raise HTTPException(400, "Adresse du site invalide.")129    dom = host[4:] if host.startswith("www.") else host130    return f"https://{host}{p.path if p.path not in ('', '/') else ''}"[:200], dom131132133def _propre(s: str, n: int) -> str:134    s = re.sub(r"[\x00-\x08\x0b\x0c\x0e-\x1f\x7f]", "", s or "")135    s = re.sub(r"<[^>]{0,200}>", " ", s)136    return re.sub(r"[ \t]+", " ", s).strip()[:n]137138139def _note_refus(ip: str) -> None:140    now = time.time()141    with _verrou:142        l = [t for t in _refus.get(ip, []) if now - t < 3600]143        l.append(now)144        _refus[ip] = l145        if len(_refus) > 5000:146            for k in list(_refus)[:2500]:147                _refus.pop(k, None)148149150@router.get("/form")151def formulaire():152    """Ce que le formulaire doit présenter, et ce qui sera enregistré."""153    return {154        "fields": [155            {"name": "name", "label": "Nom de la boutique", "required": True, "max": 120},156            {"name": "category", "label": "Spécialité", "required": True,157             "options": [{"key": k, "label": v} for k, v in cats.LIBELLES.items()]},158            {"name": "description", "label": "Ce que vous fabriquez ou vendez", "required": True,159             "min": 40, "max": 2000},160            {"name": "website", "label": "Adresse de la boutique en ligne", "required": True, "max": 200},161            {"name": "address", "label": "Ville et code postal", "required": False, "max": 200},162            {"name": "email", "label": "Courriel", "required": "email ou phone", "max": 160},163            {"name": "phone", "label": "Téléphone", "required": "email ou phone", "max": 40},164            {"name": "socials", "label": "Réseaux sociaux", "required": False, "max_items": 6},165            {"name": "consent", "label": "J'atteste être autorisé à inscrire cette boutique et "166                                         "j'accepte que ces renseignements soient conservés pour "167                                         "traiter ma demande.", "required": True},168        ],169        "honeypot": "company_url",170        "limits": {"per_ip_24h": MAX_PAR_IP_24H},171        "stored": ["nom", "spécialité", "description", "ville et code postal", "site", "courriel",172                   "téléphone", "réseaux sociaux", "date", "empreinte irréversible de l'adresse IP "173                   "(anti-abus ; l'adresse elle-même n'est pas conservée)"],174        "moderation": "Chaque demande est lue par une personne avant toute publication. Une boutique "175                      "acceptée entre au répertoire à la collecte suivante.",176        "contact": "contact@spboucher.ai",177    }178179180@router.post("")181async def deposer(request: Request):182    brut = await request.body()183    if len(brut) > MAX_CORPS:184        raise HTTPException(413, "Demande trop volumineuse.")185    ip = _ip(request)186    with _verrou:187        recent = [t for t in _refus.get(ip, []) if time.time() - t < 3600]188    if len(recent) >= MAX_PAR_IP_HEURE_REFUS:189        raise HTTPException(429, "Trop de tentatives. Réessayez dans une heure.")190    try:191        d = Demande.model_validate_json(brut)192    except Exception as exc:  # noqa: BLE001193        _note_refus(ip)194        champs = sorted({str(e["loc"][0]) for e in getattr(exc, "errors", lambda: [])() if e.get("loc")})195        raise HTTPException(400, "Champs invalides ou manquants : " + (", ".join(champs) or "format JSON"))196    # pot de miel : on répond comme si tout allait bien, sans rien enregistrer197    if d.company_url.strip():198        return {"status": "pending", "id": 0,199                "message": "Merci. Votre demande sera lue avant toute publication."}200201    def refuse(msg: str):202        _note_refus(ip)203        raise HTTPException(400, msg)204205    nom = _propre(d.name, 120)206    if re.search(r"[<>{}\\]|https?://", d.name) or len(nom) < 2 or not _NOM.match(nom) or not re.search(r"[A-Za-zÀ-ÿ]{2}", nom):207        refuse("Nom de boutique invalide.")208    if d.category not in cats.CATEGORIES:209        refuse("Spécialité inconnue.")210    if not d.consent:211        refuse("Le consentement est requis.")212    desc = _propre(d.description, 2000)213    if len(desc) < 40:214        refuse("Description trop courte (40 caractères au moins).")215    if len(re.findall(r"https?://", desc)) > 2 or _SPAM.search(desc) or _SPAM.search(nom):216        refuse("Description refusée (liens ou contenu promotionnel).")217    try:218        site, dom = _site(d.website)219    except HTTPException:220        _note_refus(ip)221        raise222    mail = texte.courriel(d.email) if d.email.strip() else None223    tel = texte.telephone(d.phone) if d.phone.strip() else None224    if d.email.strip() and not mail:225        refuse("Courriel invalide.")226    if d.phone.strip() and not tel:227        refuse("Téléphone invalide (dix chiffres).")228    if not mail and not tel:229        refuse("Un courriel ou un téléphone est requis.")230    sociaux = []231    for u in d.socials[:6]:232        u = (u or "").strip()233        if not u:234            continue235        p = urlsplit(u if re.match(r"^https?://", u, re.I) else "https://" + u)236        h = (p.hostname or "").lower().replace("www.", "")237        if not any(h == r or h.endswith("." + r) for r in _RESEAUX) or len(u) > 200:238            refuse("Lien de réseau social non reconnu : " + u[:60])239        sociaux.append(f"https://{h}{p.path}"[:200])240    adresse = _propre(d.address, 200)241242    with _verrou:243        con = _con()244        try:245            h = _empreinte(con, ip)246            now = time.time()247            if con.execute("SELECT COUNT(*) FROM inscriptions WHERE ip_hash=? AND ts>?",248                           (h, now - 86400)).fetchone()[0] >= MAX_PAR_IP_24H:249                raise HTTPException(429, "Trop de demandes depuis cette connexion. Réessayez demain.")250            if con.execute("SELECT COUNT(*) FROM inscriptions WHERE ts>?",251                           (now - 86400,)).fetchone()[0] >= MAX_GLOBAL_24H \252                    or con.execute("SELECT COUNT(*) FROM inscriptions WHERE status='pending'"253                                   ).fetchone()[0] >= MAX_EN_ATTENTE:254                raise HTTPException(503, "La file d'inscription est pleine. Réessayez demain, ou "255                                         "écrivez à contact@spboucher.ai.")256            deja = con.execute("SELECT id, status FROM inscriptions WHERE domain=? AND status<>'rejected' "257                               "ORDER BY ts DESC LIMIT 1", (dom,)).fetchone()258            if deja:259                return {"status": deja["status"], "id": deja["id"], "duplicate": True,260                        "message": "Cette boutique a déjà été proposée."}261            cur = con.execute(262                "INSERT INTO inscriptions (ts, ip_hash, name, category, description, address, website, "263                "domain, email, phone, socials) VALUES (?,?,?,?,?,?,?,?,?,?,?)",264                (now, h, nom, d.category, desc, adresse, site, dom, mail or "",265                 tel["affichage"] if tel else "", json.dumps(sociaux, ensure_ascii=False)))266            con.commit()267            num = cur.lastrowid268        finally:269            con.close()270    # déjà au répertoire ? on le dit, la demande reste utile (mise à jour)271    connue = False272    try:273        from .public import catalogue274        cat = catalogue()275        connue = dom in cat.b_index or dom in cat.annuaire276    except Exception:  # noqa: BLE001277        pass278    return {"status": "pending", "id": num, "already_listed": connue,279            "message": "Merci. Votre demande sera lue par une personne avant toute publication."}280281282def _admin(request: Request) -> None:283    tok = request.headers.get("x-admin-token", "")284    if not ADMIN_TOKEN or len(ADMIN_TOKEN) < 16:285        raise HTTPException(503, "Administration désactivée (jeton non configuré).")286    if not hmac.compare_digest(tok.encode(), ADMIN_TOKEN.encode()):287        ip = _ip(request)288        _note_refus(ip)289        time.sleep(0.4)290        raise HTTPException(401, "Jeton d'administration requis (X-Admin-Token).")291292293def _ligne(r) -> dict:294    d = dict(r)295    d.pop("ip_hash", None)296    d["socials"] = json.loads(d.get("socials") or "[]")297    d["category_label"] = cats.LIBELLES.get(d.get("category"), d.get("category"))298    return d299300301@router.get("")302def lister(request: Request, status: str = "pending", limit: int = 200):303    _admin(request)304    if status not in ("pending", "approved", "rejected", "all"):305        raise HTTPException(400, "status : pending, approved, rejected ou all")306    con = _con()307    try:308        if status == "all":309            rows = con.execute("SELECT * FROM inscriptions ORDER BY ts DESC LIMIT ?",310                               (max(1, min(500, limit)),)).fetchall()311        else:312            rows = con.execute("SELECT * FROM inscriptions WHERE status=? ORDER BY ts DESC LIMIT ?",313                               (status, max(1, min(500, limit)))).fetchall()314        comptes = dict(con.execute("SELECT status, COUNT(*) FROM inscriptions GROUP BY status").fetchall())315    finally:316        con.close()317    return {"total": len(rows), "counts": comptes, "items": [_ligne(r) for r in rows]}318319320class Decision(BaseModel):321    action: str = Field(pattern="^(approve|reject)$")322    note: str = Field("", max_length=300)323324325@router.post("/{ins_id}/decision")326def decider(ins_id: int, body: Decision, request: Request):327    _admin(request)328    with _verrou:329        con = _con()330        try:331            r = con.execute("SELECT * FROM inscriptions WHERE id=?", (ins_id,)).fetchone()332            if not r:333                raise HTTPException(404, "Demande inconnue.")334            if r["status"] != "pending":335                raise HTTPException(409, f"Demande déjà traitée ({r['status']}).")336            statut = "approved" if body.action == "approve" else "rejected"337            con.execute("UPDATE inscriptions SET status=?, reviewed_at=?, review_note=? WHERE id=?",338                        (statut, time.time(), _propre(body.note, 300), ins_id))339            con.commit()340        finally:341            con.close()342    return {"status": statut, "id": ins_id,343            "next": ("La boutique sera ajoutée au registre de la collecte par "344                     "scripts/inscriptions_admin.py (aucune écriture depuis l'API)."345                     if statut == "approved" else None)}346
Files main
Menu

Theme