diff --git a/app/main.py b/app/main.py index 2d90feb..d40d5fe 100644 --- a/app/main.py +++ b/app/main.py @@ -1,8 +1,11 @@ +import base64 +import re from contextlib import asynccontextmanager +from urllib.parse import quote from typing import Optional, List, Dict, Any from pathlib import Path from fastapi import FastAPI, APIRouter, Depends, HTTPException, Query, Request -from fastapi.responses import FileResponse +from fastapi.responses import FileResponse, Response from fastapi.staticfiles import StaticFiles from pydantic import BaseModel, Field @@ -198,6 +201,20 @@ def get_mails_periode(jours: int = 7): # --- Lecture d'un mail (texte seul, lecture seule) --- MAX_CORPS_LECTURE = 200_000 +MAX_PIECE = 25 * 1024 * 1024 +# Extensions exécutables ou actives : jamais servies (le mail est un contenu non fiable). +EXT_REFUSEES = {"exe", "msi", "bat", "cmd", "com", "scr", "pif", "vbs", "vbe", "js", "jse", "wsf", "wsh", "ps1", "psm1", + "jar", "lnk", "hta", "cpl", "reg", "dll", "sys", "iso", "img", "html", "htm", "xhtml", "svg", + "docm", "xlsm", "pptm", "dotm", "xlam", "appx", "apk", "sh", "py", "app", "dmg", "chm"} + + +def _extension(nom: str) -> str: + return nom.rsplit(".", 1)[-1].lower().strip() if "." in nom else "" + + +def _nom_sur(nom: str) -> str: + nom = re.sub(r"[\\/\x00-\x1f\x7f\"]", "_", nom.replace("\\", "/").split("/")[-1]).strip(" .") + return (nom or "piece-jointe")[:150] def _entete(en_tetes: Dict[str, Any], nom: str) -> str: @@ -227,6 +244,7 @@ def lire_mail(id: str = Query(..., min_length=1, max_length=400)): "nom": str(p.get("filename") or p.get("nom") or "(sans nom)"), "type": str(p.get("content_type") or p.get("type") or ""), "taille": int(p.get("size") or p.get("taille") or 0), + "bloquee": _extension(str(p.get("filename") or p.get("nom") or "")) in EXT_REFUSEES, }) return { "message_id": d.get("message_id") or id, @@ -238,6 +256,34 @@ def lire_mail(id: str = Query(..., min_length=1, max_length=400)): } +@api.get("/mail/piece") +def telecharger_piece(id: str = Query(..., min_length=1, max_length=400), nom: str = Query(..., min_length=1, max_length=260)): + """Télécharge une pièce jointe : toujours en téléchargement (jamais affichée), extensions actives refusées, + plafond de taille, aucune écriture, aucun contenu dans les journaux.""" + if _extension(nom) in EXT_REFUSEES: + raise HTTPException(status_code=403, detail="Type de fichier bloqué par sécurité.") + try: + res = mirror_client.get_attachment(id, nom) + except Exception: + raise HTTPException(status_code=502, detail="Pièce jointe indisponible : miroir injoignable.") + d = res.get("donnees") if isinstance(res, dict) else None + b64 = d.get("contenu_base64") if isinstance(d, dict) else None + if not b64: + raise HTTPException(status_code=404, detail="Pièce jointe introuvable.") + if len(b64) * 3 // 4 > MAX_PIECE or int(d.get("taille") or 0) > MAX_PIECE: + raise HTTPException(status_code=413, detail="Pièce jointe trop volumineuse (25 Mo maximum).") + try: + brut = base64.b64decode(b64) + except Exception: + raise HTTPException(status_code=502, detail="Pièce jointe illisible.") + propre = _nom_sur(nom) + ascii_nom = propre.encode("ascii", "replace").decode().replace("?", "_") + return Response(content=brut, media_type="application/octet-stream", headers={ + "Content-Disposition": f"attachment; filename=\"{ascii_nom}\"; filename*=UTF-8''{quote(propre)}", + "Cache-Control": "no-store", "X-Content-Type-Options": "nosniff", + }) + + # --- Classements --- @api.get("/classements") def get_classements( diff --git a/app/mirror_client.py b/app/mirror_client.py index 2480873..54fb407 100644 --- a/app/mirror_client.py +++ b/app/mirror_client.py @@ -283,6 +283,11 @@ class MirrorClient: pass # le miroir reste lisible sur les 100 derniers même si la recherche échoue return out + def get_attachment(self, message_id: str, filename: str) -> Dict[str, Any]: + """Pièce jointe d'un mail (mirror_mail_attachment), jamais mise en cache (contenu volumineux).""" + res = self.call_tool("mirror_mail_attachment", {"message_id": message_id, "filename": filename}, use_cache=False) + return res if isinstance(res, dict) else {"raw": res} + def get_mails_for_day(self, date_str: str, max_items: int = 50) -> List[Dict[str, Any]]: """Mails d'un jour donné (AAAA-MM-JJ).""" if not date_str: diff --git a/app/static/app.css b/app/static/app.css index 6024f08..bfeacba 100644 --- a/app/static/app.css +++ b/app/static/app.css @@ -264,3 +264,10 @@ h1, h2, h3, p { margin: 0; } .lect-meta { grid-template-columns: minmax(0, 1fr); gap: 0; } .lect-meta dt { margin-top: var(--ny-e2); font-size: 13px; line-height: 18px; } } + +/* Pièces jointes : téléchargement */ +.lect-pj li .btn-icone { flex: none; } +.lect-pj .info.bloquee { color: var(--ny-erreur, var(--ny-encre-2)); font-weight: 600; } +.lect-sig { margin-top: var(--ny-e4); } +.lect-sig ul { list-style: none; margin: var(--ny-e2) 0 0; padding: 0; display: grid; gap: var(--ny-e2); } +.lect-sig li { display: flex; align-items: center; gap: var(--ny-e3); min-height: var(--ny-cible); padding: 6px var(--ny-e3); color: var(--ny-encre-2); } diff --git a/app/static/app.js b/app/static/app.js index 93ccd36..2e12190 100644 --- a/app/static/app.js +++ b/app/static/app.js @@ -14,7 +14,7 @@ suivi: 'M12 6v6l4 2|M22 12a10 10 0 1 1-20 0 10 10 0 0 1 20 0', pj: 'm21.44 11.05-9.19 9.19a6 6 0 0 1-8.49-8.49l8.57-8.57A4 4 0 1 1 18 8.84l-8.59 8.57a2 2 0 0 1-2.83-2.83l8.49-8.48', groupes: 'M3 7h7v7H3z|M14 7h7v7h-7z|M3 17h18', - fermer: 'M18 6 6 18|m6 6 12 12', gauche: 'm15 18-6-6 6-6', droite: 'm9 18 6-6-6-6', bas: 'm6 9 6 6 6-6', fleche: 'M5 12h14|m12 5 7 7-7 7' + telecharger: 'M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4|m7 10 5 5 5-5|M12 15V3', fermer: 'M18 6 6 18|m6 6 12 12', gauche: 'm15 18-6-6 6-6', droite: 'm9 18 6-6-6-6', bas: 'm6 9 6 6 6-6', fleche: 'M5 12h14|m12 5 7 7-7 7' }; var NAV = [ ['tri', 'Tri du jour', true], ['categories', 'Catégories', true], ['groupes', 'Groupes', true], ['regles', 'Règles', true], @@ -378,6 +378,28 @@ if (!/^\d{4}-\d{2}-\d{2}$/.test(iso)) return String(v || ''); return nomJour(iso).toLowerCase() + ' ' + fr(iso) + ' à ' + heureTunis(v); } + function estSignature(p) { + return /^image\//.test(p.type || '') && Number(p.taille) < 20480 && !p.bloquee; + } + function telechargerPiece(id, p, bt) { + bt.disabled = true; annoncer('Téléchargement de ' + p.nom + ' en cours'); + fetch(API + '/mail/piece?id=' + encodeURIComponent(id) + '&nom=' + encodeURIComponent(p.nom), { credentials: 'same-origin', redirect: 'manual' }) + .then(function (rep) { + if (rep.type === 'opaqueredirect') { sessionExpiree(); throw new Error('session'); } + if (rep.status === 403) throw new Error('Ce type de fichier est bloqué par sécurité.'); + if (rep.status === 413) throw new Error('Pièce jointe trop volumineuse (25 Mo maximum).'); + if (!rep.ok) throw new Error('Pièce jointe indisponible pour le moment.'); + return rep.blob(); + }) + .then(function (blob) { + var url = URL.createObjectURL(blob), a = document.createElement('a'); + a.href = url; a.download = p.nom; document.body.appendChild(a); a.click(); a.remove(); + setTimeout(function () { URL.revokeObjectURL(url); }, 4000); + annoncer(p.nom + ' téléchargé'); + }) + .catch(function (e) { if (e.message !== 'session') annoncer(e.message); }) + .then(function () { bt.disabled = false; }); + } function afficherMail(cont, m, r, c) { var badges = h('div', { class: 'lect-badges' }, h('span', { class: 'lect-cat' }, pastille(couleur(m.cat, c && c.id)), m.cat)); (m.etiquettes || []).forEach(function (t) { badges.appendChild(h('span', { class: 'etq', text: t })); }); @@ -398,14 +420,27 @@ } if (r.tronque) cont.appendChild(h('p', { class: 'lect-note', text: 'Le texte est très long : seul le début est affiché.' })); var pj = r.pieces_jointes || []; - if (pj.length) { + var signature = pj.filter(estSignature), utiles = pj.filter(function (p) { return !estSignature(p); }); + function extDe(p) { var e = String(p.nom || '').indexOf('.') > -1 ? String(p.nom).split('.').pop().toUpperCase() : ''; return e && e.length <= 5 ? e + ' · ' : ''; } + if (utiles.length) { var ul = h('ul'); - pj.forEach(function (p) { - var ext = String(p.nom || '').indexOf('.') > -1 ? String(p.nom).split('.').pop().toUpperCase() : ''; + utiles.forEach(function (p) { + var action; + if (p.bloquee) action = h('span', { class: 'info bloquee', text: 'Bloquée par sécurité' }); + else { + var bt = h('button', { type: 'button', class: 'btn-icone', 'aria-label': 'Télécharger ' + p.nom, title: 'Télécharger' }, icone('telecharger')); + bt.addEventListener('click', function () { telechargerPiece(r.message_id || m.id, p, bt); }); + action = bt; + } ul.appendChild(h('li', null, icone('pj', 18), h('span', { class: 'nom coupe', title: p.nom, text: p.nom }), - h('span', { class: 'info', text: (ext && ext.length <= 5 ? ext + ' · ' : '') + tailleLisible(p.taille) }))); + h('span', { class: 'info', text: extDe(p) + tailleLisible(p.taille) }), action)); }); - cont.appendChild(h('section', { class: 'lect-pj', 'aria-labelledby': 'lect-pj-t' }, h('h3', { id: 'lect-pj-t', text: 'Pièces jointes (' + pj.length + ')' }), ul)); + cont.appendChild(h('section', { class: 'lect-pj', 'aria-labelledby': 'lect-pj-t' }, h('h3', { id: 'lect-pj-t', text: 'Pièces jointes (' + utiles.length + ')' }), ul)); + } + if (signature.length) { + var us = h('ul'); + signature.forEach(function (p) { us.appendChild(h('li', null, icone('pj', 18), h('span', { class: 'nom coupe', title: p.nom, text: p.nom }), h('span', { class: 'info', text: tailleLisible(p.taille) }))); }); + cont.appendChild(h('details', { class: 'lect-histo lect-sig' }, h('summary', null, 'Images intégrées au message (' + signature.length + ')'), us)); } cont.appendChild(h('p', { class: 'lect-note', text: 'Lecture seule : le mail n\'est pas modifié dans votre messagerie.' })); } diff --git a/app/static/index.html b/app/static/index.html index c94540b..43b5c2a 100644 --- a/app/static/index.html +++ b/app/static/index.html @@ -10,7 +10,7 @@ - +