Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
05c75c74f7 | ||
|
|
81d9cae1f7 |
No files matched your search
@@ -35,7 +35,7 @@ jobs:
|
||||
env:
|
||||
VITE_SUPABASE_URL: ${{ vars.VITE_SUPABASE_URL }}
|
||||
VITE_SUPABASE_ANON_KEY: ${{ secrets.VITE_SUPABASE_ANON_KEY }}
|
||||
run: cd src && npm run build && npm run build:admin
|
||||
run: cd src && npm run build && npm run build:admin && npm run build:mail
|
||||
- name: Publier (atomique, 3 versions conservées)
|
||||
env:
|
||||
SHA: ${{ github.sha }}
|
||||
|
||||
@@ -12,3 +12,4 @@ _to_delete
|
||||
.env.deploy
|
||||
tsconfig.tsbuildinfo
|
||||
dist-admin
|
||||
dist-mail
|
||||
@@ -80,7 +80,7 @@ npm run build # build de prod
|
||||
- **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`. **Choix par type** (Réglages → Notifications, `NotificationSettings.tsx`) : `settings.notifOff` (synchronisé) ; le trigger `notifications_wanted` ne crée pas un type désactivé, et `get_notifications` / `unread_notifications` masquent ceux déjà reçus. La fonction Edge `send-push` répond 410 : à supprimer depuis le tableau de bord Supabase.
|
||||
- **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 https://admin.bobinoo.org (`deploy/nginx/admin.conf`, limite d'appels, CSP stricte). 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. Webmail : https://mail.bobinoo.org (redirection vers le webmail OVH, `deploy/nginx/mail.conf`). `contact@bobinoo.org` est aussi l'adresse de contact des pages légales, de « Signaler un bug » et du Play Store.
|
||||
- **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. Messagerie : https://mail.bobinoo.org, interface Bobinoo de la boîte (`docs/mail.md` : site `mail/`, fonction Edge `mail` en IMAP/SMTP, mêmes verrous que la console). `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é.
|
||||
- **Dépendances figées** : versions exactes dans `package.json` + `.npmrc` (`save-exact=true`), CI en `npm ci`.
|
||||
|
||||
+64
-4
@@ -1,9 +1,69 @@
|
||||
# Raccourci vers la boîte contact@bobinoo.org : https://mail.bobinoo.org ouvre le webmail OVH (Zimbra).
|
||||
# Incluse par site.conf. Le HTTPS est assuré par le proxy en façade du VPS (en-tête Host transmis), comme pour bobinoo.org.
|
||||
# Messagerie Bobinoo (docs/mail.md) : https://mail.bobinoo.org, interface de contact@bobinoo.org (boîte OVH Zimbra).
|
||||
# Incluse par site.conf, livrée avec chaque release. HTTPS assuré par le proxy en façade du VPS (en-tête Host transmis).
|
||||
# Mêmes protections que la console : compte Bobinoo admin + code de double authentification, secret entre ce serveur
|
||||
# et la fonction Edge « mail », nombre d'appels limité, journal.
|
||||
|
||||
limit_req_zone $server_name zone=bobinoo_mail:1m rate=120r/m;
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name mail.bobinoo.org webmail.bobinoo.org;
|
||||
server_name mail.bobinoo.org;
|
||||
server_tokens off;
|
||||
|
||||
root /srv/bobinoo/current/mail;
|
||||
index index.html;
|
||||
include /etc/nginx/mime.types;
|
||||
|
||||
# Styles en ligne autorisés : le contenu des e-mails en a besoin (il est affiché dans un cadre isolé, sans script).
|
||||
# Images https autorisées : bloquées par défaut par l'interface, chargées seulement sur « Afficher les images ».
|
||||
add_header Content-Security-Policy "default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; font-src 'self' data:; img-src 'self' data: blob: https:; connect-src 'self' https://qfgnxonqwldcfdjqhhjz.supabase.co; frame-src 'self'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'" always;
|
||||
add_header Strict-Transport-Security "max-age=63072000" 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;
|
||||
return 302 https://www.ovhcloud.com/fr/mail/;
|
||||
add_header Cache-Control "no-store" always;
|
||||
add_header Permissions-Policy "camera=(), microphone=(), geolocation=(), payment=()" always;
|
||||
|
||||
# Relais vers la fonction serveur « mail », avec le même secret que la console (/etc/nginx/bobinoo-admin-gate.conf)
|
||||
location = /api/mail {
|
||||
limit_except POST { deny all; }
|
||||
limit_req zone=bobinoo_mail burst=40 nodelay;
|
||||
limit_req_status 429;
|
||||
client_max_body_size 256k;
|
||||
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/mail;
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
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 60s;
|
||||
}
|
||||
|
||||
location = /robots.txt {
|
||||
default_type text/plain;
|
||||
return 200 "User-agent: *\nDisallow: /\n";
|
||||
}
|
||||
|
||||
location /assets/ {
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
location / {
|
||||
try_files $uri /index.html;
|
||||
}
|
||||
}
|
||||
|
||||
# Autre adresse : renvoie vers la messagerie
|
||||
server {
|
||||
listen 80;
|
||||
server_name webmail.bobinoo.org;
|
||||
server_tokens off;
|
||||
return 301 https://mail.bobinoo.org/;
|
||||
}
|
||||
@@ -48,5 +48,5 @@ server {
|
||||
# Console d'administration : https://admin.bobinoo.org (voir admin.conf et docs/admin.md)
|
||||
include /srv/bobinoo/current/nginx/admin.conf;
|
||||
|
||||
# Raccourci vers le webmail de contact@bobinoo.org : https://mail.bobinoo.org (voir mail.conf)
|
||||
# Messagerie de contact@bobinoo.org : https://mail.bobinoo.org (voir mail.conf et docs/mail.md)
|
||||
include /srv/bobinoo/current/nginx/mail.conf;
|
||||
+3
-1
@@ -16,7 +16,9 @@ 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) : https://admin.bobinoo.org
|
||||
cp "$HERE/nginx/admin.conf" "$REL/nginx/admin.conf"
|
||||
cp "$HERE/nginx/mail.conf" "$REL/nginx/mail.conf" # raccourci https://mail.bobinoo.org → webmail OVH
|
||||
# Messagerie (docs/mail.md) : https://mail.bobinoo.org
|
||||
cp "$HERE/nginx/mail.conf" "$REL/nginx/mail.conf"
|
||||
if [ -f "$SRC/../dist-mail/index.html" ]; then cp -a "$SRC/../dist-mail" "$REL/mail"; else mkdir -p "$REL/mail"; fi
|
||||
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
|
||||
|
||||
@@ -20,6 +20,6 @@ DMARC `_dmarc` TXT `v=DMARC1; p=none; rua=mailto:<adresse de la boîte>`.
|
||||
|
||||
## Lire la boîte
|
||||
|
||||
- **Navigateur** : https://mail.bobinoo.org, raccourci vers le webmail OVH (`deploy/nginx/mail.conf`).
|
||||
- **Navigateur** : https://mail.bobinoo.org, la messagerie Bobinoo (`docs/mail.md`).
|
||||
- **iPhone (app Mail)** : compte IMAP `imap.mail.ovh.net:993` (SSL), envoi `smtp.mail.ovh.net:465` (SSL), identifiant = l'adresse complète.
|
||||
- **Mot de passe changé** : le reporter aussi dans Supabase, dans Authentication → Emails → SMTP Settings et dans le secret Edge `SMTP_PASSWORD`.
|
||||
@@ -0,0 +1,55 @@
|
||||
# Messagerie Bobinoo
|
||||
|
||||
**https://mail.bobinoo.org** : l'interface de la boîte contact@bobinoo.org, aux couleurs de Bobinoo.
|
||||
La boîte reste chez OVH (Zimbra Starter) ; seule l'interface est la nôtre.
|
||||
|
||||
## Fonctionnement
|
||||
|
||||
- **Interface** : `mail/` (React), construite par `npm run build:mail` dans `dist-mail/`, servie par nginx
|
||||
(`deploy/nginx/mail.conf`).
|
||||
- **Serveur** : fonction Edge `mail` (`supabase/functions/mail/`).
|
||||
- Lecture en IMAP (`ssl0.ovh.net:993`, bibliothèque imapflow), envoi en SMTP (`ssl0.ovh.net:465`, nodemailer).
|
||||
- Chaque envoi est copié dans « Envoyés ».
|
||||
- Une réponse marque le message d'origine comme « répondu ».
|
||||
- **Mot de passe de la boîte** : secret Supabase `MAIL_PASSWORD` (sinon `SMTP_PASSWORD`). Il ne quitte jamais le serveur.
|
||||
|
||||
## Sécurité
|
||||
|
||||
Mêmes verrous que la console (`docs/admin.md`) :
|
||||
- compte Bobinoo **admin** + code de double authentification ;
|
||||
- secret `X-Admin-Gate` ajouté par nginx (même fichier `/etc/nginx/bobinoo-admin-gate.conf`) ;
|
||||
- nombre d'appels limité ;
|
||||
- connexions, envois et suppressions inscrits dans `admin.journal`.
|
||||
|
||||
Affichage des e-mails :
|
||||
- le HTML est nettoyé (DOMPurify : ni script, ni formulaire, ni cadre) puis affiché dans un cadre isolé, sans script ;
|
||||
- les **images distantes sont bloquées** par défaut, car elles servent à savoir qu'un message a été ouvert ;
|
||||
le bouton « Afficher les images » les charge ;
|
||||
- les liens s'ouvrent dans un nouvel onglet.
|
||||
|
||||
Session en mémoire seulement : 1 h maximum, déconnexion après 30 min sans activité.
|
||||
|
||||
## Ce qu'on peut faire
|
||||
|
||||
| Action | Détail |
|
||||
|---|---|
|
||||
| Dossiers | Réception, Envoyés, Brouillons, Indésirables, Corbeille, avec le nombre de non-lus |
|
||||
| Lire | Pièces jointes à télécharger (15 Mo maximum par fichier) |
|
||||
| Écrire, répondre, transférer | En texte simple ; les pièces jointes ne sont pas transférées |
|
||||
| Classer | Non lu, Indésirable, Corbeille, remettre en réception |
|
||||
| Supprimer définitivement | Depuis la Corbeille ou les Indésirables |
|
||||
| Rechercher | Expéditeur, destinataire, objet, texte |
|
||||
|
||||
La boîte vérifie les nouveaux messages chaque minute quand la page est ouverte.
|
||||
|
||||
## Installation (une fois)
|
||||
|
||||
1. **Secret Supabase** (Edge Functions → Secrets) : `MAIL_PASSWORD` = mot de passe de contact@bobinoo.org.
|
||||
Si `SMTP_PASSWORD` existe déjà avec ce mot de passe, il est utilisé.
|
||||
2. **DNS** : enregistrement A `mail` → 193.168.145.214.
|
||||
3. **Proxy en façade du VPS** : `mail.bobinoo.org` comme `admin.bobinoo.org` (en-tête Host transmis), avec certificat HTTPS.
|
||||
Le secret nginx de la console sert aussi ici.
|
||||
|
||||
**Mot de passe de la boîte changé** : le reporter dans Supabase, à deux endroits :
|
||||
- les secrets `MAIL_PASSWORD` / `SMTP_PASSWORD` ;
|
||||
- Authentication → Emails → SMTP Settings.
|
||||
@@ -0,0 +1,18 @@
|
||||
<!doctype html>
|
||||
<html lang="fr">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
|
||||
<meta name="robots" content="noindex, nofollow" />
|
||||
<meta name="referrer" content="no-referrer" />
|
||||
<meta name="color-scheme" content="dark" />
|
||||
<meta name="theme-color" content="#090909" />
|
||||
<meta name="apple-mobile-web-app-capable" content="yes" />
|
||||
<meta name="apple-mobile-web-app-title" content="Bobinoo Mail" />
|
||||
<title>Bobinoo Mail</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,375 @@
|
||||
import { Inbox, Loader2, LogOut, Paperclip, PenSquare, RefreshCw, Search, Send, ShieldAlert, Trash2, FileText } from 'lucide-react'
|
||||
import { useCallback, useEffect, useRef, useState, type FormEvent, type ReactNode } from 'react'
|
||||
import { AuthError, expiresAt, signIn, signOut, verifyCode } from '../../admin/src/auth'
|
||||
import { ApiError, call, FOLDER_LABEL, who, type Folder, type FolderId, type Message, type Summary } from './api'
|
||||
import Compose, { type Draft } from './Compose'
|
||||
import { fullDate, listDate } from './format'
|
||||
import Reader from './Reader'
|
||||
|
||||
/** Déconnexion automatique après 30 minutes sans activité. */
|
||||
const IDLE_MS = 30 * 60_000
|
||||
|
||||
const FOLDER_ICON: Record<FolderId, ReactNode> = {
|
||||
inbox: <Inbox size={17} />,
|
||||
sent: <Send size={17} />,
|
||||
drafts: <FileText size={17} />,
|
||||
junk: <ShieldAlert size={17} />,
|
||||
trash: <Trash2 size={17} />,
|
||||
}
|
||||
|
||||
function Logo() {
|
||||
return (
|
||||
<span className="text-lg font-bold tracking-tight">
|
||||
Bobin<span className="text-accent">oo</span> <span className="font-medium text-ink-2">Mail</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
// Jeton en mémoire seulement : recharger la page déconnecte
|
||||
const [session, setSession] = useState<{ token: string; mailbox: string }>()
|
||||
const [notice, setNotice] = useState<string>()
|
||||
|
||||
const logout = useCallback((why?: string) => {
|
||||
setSession((s) => {
|
||||
if (s) void signOut(s.token)
|
||||
return undefined
|
||||
})
|
||||
setNotice(why)
|
||||
}, [])
|
||||
|
||||
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 30 minutes sans activité.'), IDLE_MS)
|
||||
const touch = () => {
|
||||
window.clearTimeout(idle)
|
||||
idle = window.setTimeout(() => logout('Déconnecté après 30 minutes sans activité.'), IDLE_MS)
|
||||
}
|
||||
for (const ev of ['pointerdown', 'keydown'] as const) window.addEventListener(ev, touch)
|
||||
return () => {
|
||||
window.clearTimeout(end)
|
||||
window.clearTimeout(idle)
|
||||
for (const ev of ['pointerdown', 'keydown'] as const) window.removeEventListener(ev, touch)
|
||||
}
|
||||
}, [session, logout])
|
||||
|
||||
if (!session) return <Login notice={notice} onReady={(token, mailbox) => (setNotice(undefined), setSession({ token, mailbox }))} />
|
||||
return <Mailbox token={session.token} mailbox={session.mailbox} onLogout={logout} />
|
||||
}
|
||||
|
||||
function Login({ notice, onReady }: { notice?: string; onReady: (token: string, mailbox: string) => void }) {
|
||||
const [step, setStep] = useState<{ token: string; factorId: string }>()
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [code, setCode] = useState('')
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const codeRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (busy) return
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
try {
|
||||
if (!step) {
|
||||
const r = await signIn(email, password)
|
||||
setPassword('')
|
||||
if (!r.factorId) {
|
||||
await signOut(r.token)
|
||||
throw new AuthError("Ce compte n'a pas la double authentification. Active-la d'abord dans l'app Bobinoo (Réglages → Mon compte).")
|
||||
}
|
||||
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 r = await call<{ mailbox: string }>(token, 'hello')
|
||||
onReady(token, r.mailbox)
|
||||
}
|
||||
} catch (err) {
|
||||
setError(err instanceof AuthError || err instanceof ApiError ? err.message : 'Erreur inattendue.')
|
||||
if (step) setCode('')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className="mx-auto flex min-h-dvh max-w-sm flex-col justify-center px-5 py-10">
|
||||
<Logo />
|
||||
<h1 className="mt-3 text-2xl font-bold">contact@bobinoo.org</h1>
|
||||
<p className="mt-2 text-sm text-ink-3">Connecte-toi avec ton compte Bobinoo (administrateur), puis ton code de double authentification.</p>
|
||||
{notice && <p className="mt-5 border-s-2 border-accent ps-3 text-sm text-ink-2">{notice}</p>}
|
||||
<form onSubmit={submit} className="mt-7 space-y-3">
|
||||
{!step ? (
|
||||
<>
|
||||
<input className="field" type="email" autoComplete="username" placeholder="E-mail du compte Bobinoo" value={email} onChange={(e) => setEmail(e.target.value)} required />
|
||||
<input className="field" type="password" autoComplete="current-password" placeholder="Mot de passe" value={password} onChange={(e) => setPassword(e.target.value)} required />
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p className="text-sm text-ink-2">Code à 6 chiffres de ton application d'authentification :</p>
|
||||
<input
|
||||
ref={codeRef}
|
||||
className="field text-center text-2xl tracking-[0.4em]"
|
||||
inputMode="numeric"
|
||||
autoComplete="one-time-code"
|
||||
pattern="[0-9 ]{6,7}"
|
||||
maxLength={7}
|
||||
value={code}
|
||||
onChange={(e) => setCode(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</>
|
||||
)}
|
||||
{error && <p className="text-sm text-danger">{error}</p>}
|
||||
<button className="btn btn-primary w-full" disabled={busy}>
|
||||
{busy ? '…' : step ? 'Ouvrir la boîte' : 'Continuer'}
|
||||
</button>
|
||||
{step && (
|
||||
<button type="button" className="btn w-full text-ink-3" onClick={() => (void signOut(step.token), setStep(undefined), setCode(''))}>
|
||||
Annuler
|
||||
</button>
|
||||
)}
|
||||
</form>
|
||||
</main>
|
||||
)
|
||||
}
|
||||
|
||||
const quote = (text: string) =>
|
||||
text
|
||||
.slice(0, 20_000)
|
||||
.split('\n')
|
||||
.map((l) => `> ${l}`)
|
||||
.join('\n')
|
||||
|
||||
function Mailbox({ token, mailbox, onLogout }: { token: string; mailbox: string; onLogout: (why?: string) => void }) {
|
||||
const [folders, setFolders] = useState<Folder[]>([])
|
||||
const [folder, setFolder] = useState<FolderId>('inbox')
|
||||
const [list, setList] = useState<Summary[]>()
|
||||
const [total, setTotal] = useState(0)
|
||||
const [page, setPage] = useState(0)
|
||||
const [q, setQ] = useState('')
|
||||
const [query, setQuery] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const [selected, setSelected] = useState<number>()
|
||||
const [draft, setDraft] = useState<Draft>()
|
||||
const [toast, setToast] = useState<string>()
|
||||
|
||||
const onAuthError = useCallback(
|
||||
(e: unknown) => {
|
||||
if (e instanceof ApiError && (e.status === 401 || (e.status === 403 && /double|interdit|réservé/i.test(e.message)))) onLogout(e.message)
|
||||
},
|
||||
[onLogout],
|
||||
)
|
||||
|
||||
const loadFolders = useCallback(() => {
|
||||
call<Folder[]>(token, 'folders').then(setFolders, onAuthError)
|
||||
}, [token, onAuthError])
|
||||
|
||||
const loadList = useCallback(
|
||||
async (p = 0, quiet = false) => {
|
||||
if (!quiet) setLoading(true)
|
||||
setError(undefined)
|
||||
try {
|
||||
const r = await call<{ total: number; messages: Summary[] }>(token, 'list', { folder, page: p, q: query })
|
||||
setTotal(r.total)
|
||||
setPage(p)
|
||||
setList((prev) => (p ? [...(prev ?? []), ...r.messages] : r.messages))
|
||||
} catch (e) {
|
||||
onAuthError(e)
|
||||
setError(e instanceof ApiError ? e.message : 'Erreur inattendue.')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
},
|
||||
[token, folder, query, onAuthError],
|
||||
)
|
||||
|
||||
useEffect(() => {
|
||||
setList(undefined)
|
||||
setSelected(undefined)
|
||||
void loadList(0)
|
||||
}, [loadList])
|
||||
useEffect(loadFolders, [loadFolders])
|
||||
|
||||
// Nouveaux messages : vérifiés chaque minute quand la page est affichée (première page, hors recherche)
|
||||
useEffect(() => {
|
||||
const id = window.setInterval(() => {
|
||||
if (document.visibilityState !== 'visible' || query || page > 0) return
|
||||
loadFolders()
|
||||
void loadList(0, true)
|
||||
}, 60_000)
|
||||
return () => window.clearInterval(id)
|
||||
}, [loadFolders, loadList, query, page])
|
||||
|
||||
const unread = folders.find((f) => f.id === 'inbox')?.unseen ?? 0
|
||||
useEffect(() => {
|
||||
document.title = unread ? `(${unread}) Bobinoo Mail` : 'Bobinoo Mail'
|
||||
}, [unread])
|
||||
|
||||
const flash = (text: string) => {
|
||||
setToast(text)
|
||||
window.setTimeout(() => setToast(undefined), 2500)
|
||||
}
|
||||
|
||||
const reply = (m: Message) =>
|
||||
setDraft({
|
||||
to: (m.replyTo.length ? m.replyTo : [m.from]).map((a) => a.address).filter(Boolean).join(', '),
|
||||
cc: '',
|
||||
subject: /^re\s*:/i.test(m.subject) ? m.subject : `Re: ${m.subject}`,
|
||||
text: `\n\n\nLe ${fullDate(m.date)}, ${who(m.from)} a écrit :\n${quote(m.text)}`,
|
||||
inReplyTo: m.messageId ?? undefined,
|
||||
references: [...m.references, m.messageId ?? ''].filter(Boolean),
|
||||
answeredUid: m.uid,
|
||||
answeredFolder: folder,
|
||||
})
|
||||
|
||||
const forward = (m: Message) =>
|
||||
setDraft({
|
||||
to: '',
|
||||
cc: '',
|
||||
subject: /^(tr|fwd?)\s*:/i.test(m.subject) ? m.subject : `Tr: ${m.subject}`,
|
||||
text: `\n\n\n---------- Message transféré ----------\nDe : ${who(m.from)}${m.from.address ? ` <${m.from.address}>` : ''}\nDate : ${fullDate(m.date)}\nObjet : ${m.subject}\n\n${m.text.slice(0, 50_000)}${m.attachments.length ? '\n\n(Pièces jointes non transférées)' : ''}`,
|
||||
})
|
||||
|
||||
const search = (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
setQuery(q.trim())
|
||||
}
|
||||
|
||||
const listPane = (
|
||||
<section className={`min-w-0 ${selected ? 'hidden lg:block' : ''}`}>
|
||||
<form onSubmit={search} className="mb-3 flex gap-2">
|
||||
<input className="field py-2" placeholder={`Rechercher dans ${FOLDER_LABEL[folder].toLowerCase()}`} value={q} onChange={(e) => setQ(e.target.value.slice(0, 100))} enterKeyHint="search" />
|
||||
<button className="btn btn-ghost px-3" aria-label="Rechercher">
|
||||
<Search size={17} />
|
||||
</button>
|
||||
<button type="button" onClick={() => (loadFolders(), void loadList(0))} className="btn btn-ghost px-3" aria-label="Actualiser">
|
||||
{loading ? <Loader2 size={17} className="animate-spin" /> : <RefreshCw size={17} />}
|
||||
</button>
|
||||
</form>
|
||||
{query && (
|
||||
<p className="mb-2 text-xs text-ink-3">
|
||||
Résultats pour « {query} » ·{' '}
|
||||
<button onClick={() => (setQ(''), setQuery(''))} className="text-accent underline underline-offset-2">
|
||||
effacer
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
{error && <p className="py-4 text-sm text-danger">{error}</p>}
|
||||
{!list && !error && <p className="py-4 text-sm text-ink-3">Chargement…</p>}
|
||||
{list && !list.length && <p className="py-4 text-sm text-ink-3">{query ? 'Aucun message trouvé.' : 'Aucun message.'}</p>}
|
||||
<ul className="divide-y divide-line border-y border-line">
|
||||
{list?.map((m) => {
|
||||
const person = folder === 'sent' || folder === 'drafts' ? `À : ${m.to.map(who).join(', ') || '—'}` : who(m.from)
|
||||
return (
|
||||
<li key={m.uid}>
|
||||
<button
|
||||
onClick={() => setSelected(m.uid)}
|
||||
className={`flex w-full gap-3 px-1 py-3 text-start transition-colors active:bg-surface-2 ${selected === m.uid ? 'bg-surface-2' : ''}`}
|
||||
>
|
||||
<span className={`mt-1.5 size-2 shrink-0 rounded-full ${m.seen ? 'bg-transparent' : 'bg-accent'}`} aria-hidden />
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="flex items-baseline gap-2">
|
||||
<span className={`min-w-0 flex-1 truncate text-sm ${m.seen ? 'text-ink-2' : 'font-bold text-ink'}`}>{person}</span>
|
||||
<span className="shrink-0 text-xs text-ink-3">{listDate(m.date)}</span>
|
||||
</span>
|
||||
<span className={`mt-0.5 flex items-center gap-1.5 text-sm ${m.seen ? 'text-ink-3' : 'font-semibold text-ink'}`}>
|
||||
<span className="min-w-0 flex-1 truncate">{m.subject || '(sans objet)'}</span>
|
||||
{m.attachments && <Paperclip size={13} className="shrink-0 text-ink-3" />}
|
||||
</span>
|
||||
</span>
|
||||
</button>
|
||||
</li>
|
||||
)
|
||||
})}
|
||||
</ul>
|
||||
{list && !query && list.length < total && (
|
||||
<button onClick={() => void loadList(page + 1)} className="btn btn-ghost mt-4 w-full" disabled={loading}>
|
||||
Messages plus anciens
|
||||
</button>
|
||||
)}
|
||||
</section>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="mx-auto min-h-dvh max-w-7xl px-4 pb-16 sm:px-6">
|
||||
<header className="sticky top-0 z-20 -mx-4 border-b border-line bg-bg px-4 pt-[max(0.75rem,env(safe-area-inset-top))] sm:-mx-6 sm:px-6">
|
||||
<div className="flex items-center gap-3 pb-2">
|
||||
<Logo />
|
||||
<span className="ms-auto hidden truncate text-sm text-ink-3 sm:inline">{mailbox}</span>
|
||||
<button onClick={() => setDraft({ to: '', cc: '', subject: '', text: '' })} className="btn btn-primary ms-auto py-2 sm:ms-0">
|
||||
<PenSquare size={16} /> Écrire
|
||||
</button>
|
||||
<button onClick={() => onLogout('Déconnecté.')} className="grid size-9 place-items-center text-ink-2" aria-label="Se déconnecter">
|
||||
<LogOut size={18} />
|
||||
</button>
|
||||
</div>
|
||||
<nav className={`-mx-1 flex gap-1 overflow-x-auto pb-2 lg:hidden ${selected ? 'hidden' : ''}`}>
|
||||
{folders.map((f) => (
|
||||
<FolderButton key={f.id} f={f} active={f.id === folder} onClick={() => setFolder(f.id)} />
|
||||
))}
|
||||
</nav>
|
||||
</header>
|
||||
|
||||
<div className="pt-4 lg:grid lg:grid-cols-[12rem_minmax(0,26rem)_minmax(0,1fr)] lg:gap-6">
|
||||
<nav className="hidden flex-col gap-1 lg:flex">
|
||||
{folders.map((f) => (
|
||||
<FolderButton key={f.id} f={f} active={f.id === folder} onClick={() => setFolder(f.id)} />
|
||||
))}
|
||||
</nav>
|
||||
{listPane}
|
||||
{selected ? (
|
||||
<Reader
|
||||
key={`${folder}:${selected}`}
|
||||
token={token}
|
||||
folder={folder}
|
||||
uid={selected}
|
||||
onBack={() => setSelected(undefined)}
|
||||
onReply={reply}
|
||||
onForward={forward}
|
||||
onChanged={(removed) => {
|
||||
loadFolders()
|
||||
if (removed) {
|
||||
setList((l) => l?.filter((m) => m.uid !== selected))
|
||||
flash('Message déplacé')
|
||||
} else setList((l) => l?.map((m) => (m.uid === selected ? { ...m, seen: true } : m)))
|
||||
}}
|
||||
onAuthError={onAuthError}
|
||||
/>
|
||||
) : (
|
||||
<p className="hidden pt-10 text-center text-sm text-ink-3 lg:block">Choisis un message pour le lire.</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{draft && (
|
||||
<Compose
|
||||
token={token}
|
||||
initial={draft}
|
||||
onClose={() => setDraft(undefined)}
|
||||
onSent={() => {
|
||||
setDraft(undefined)
|
||||
flash('Message envoyé')
|
||||
loadFolders()
|
||||
if (folder === 'sent') void loadList(0, true)
|
||||
}}
|
||||
onAuthError={onAuthError}
|
||||
/>
|
||||
)}
|
||||
{toast && <p className="fixed inset-x-0 bottom-[max(1.5rem,env(safe-area-inset-bottom))] z-50 mx-auto w-fit bg-ink px-4 py-2 text-sm font-medium text-bg">{toast}</p>}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function FolderButton({ f, active, onClick }: { f: Folder; active: boolean; onClick: () => void }) {
|
||||
return (
|
||||
<button onClick={onClick} className={`flex shrink-0 items-center gap-2.5 rounded-md px-3 py-2 text-sm font-medium ${active ? 'bg-surface-2 text-ink' : 'text-ink-3'}`}>
|
||||
{FOLDER_ICON[f.id]}
|
||||
<span className="flex-1 text-start">{FOLDER_LABEL[f.id]}</span>
|
||||
{f.unseen > 0 && (f.id === 'inbox' || f.id === 'junk') && <span className="text-xs font-bold text-accent">{f.unseen}</span>}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,106 @@
|
||||
import { Loader2, Send, X } from 'lucide-react'
|
||||
import { useState, type FormEvent } from 'react'
|
||||
import { ApiError, call, type FolderId } from './api'
|
||||
|
||||
export interface Draft {
|
||||
to: string
|
||||
cc: string
|
||||
subject: string
|
||||
text: string
|
||||
inReplyTo?: string
|
||||
references?: string[]
|
||||
/** Message auquel on répond : marqué « répondu » après l'envoi */
|
||||
answeredUid?: number
|
||||
answeredFolder?: FolderId
|
||||
}
|
||||
|
||||
/** Nouveau message, réponse ou transfert (texte simple, envoyé depuis contact@bobinoo.org). */
|
||||
export default function Compose({
|
||||
token,
|
||||
initial,
|
||||
onClose,
|
||||
onSent,
|
||||
onAuthError,
|
||||
}: {
|
||||
token: string
|
||||
initial: Draft
|
||||
onClose: () => void
|
||||
onSent: () => void
|
||||
onAuthError: (e: unknown) => void
|
||||
}) {
|
||||
const [d, setD] = useState(initial)
|
||||
const [showCc, setShowCc] = useState(!!initial.cc)
|
||||
const [busy, setBusy] = useState(false)
|
||||
const [error, setError] = useState<string>()
|
||||
const set = (patch: Partial<Draft>) => setD((x) => ({ ...x, ...patch }))
|
||||
|
||||
const submit = async (e: FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (busy) return
|
||||
if (!d.subject.trim() && !confirm('Envoyer sans objet ?')) return
|
||||
setBusy(true)
|
||||
setError(undefined)
|
||||
try {
|
||||
await call(token, 'send', { ...d })
|
||||
onSent()
|
||||
} catch (err) {
|
||||
onAuthError(err)
|
||||
setError(err instanceof ApiError ? err.message : "L'envoi a échoué.")
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const close = () => {
|
||||
const touched = d.text !== initial.text || d.to !== initial.to || d.subject !== initial.subject
|
||||
if (!touched || confirm('Abandonner ce message ?')) onClose()
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed inset-0 z-50 flex items-stretch justify-center bg-scrim sm:items-center sm:p-6">
|
||||
<form onSubmit={submit} className="flex w-full max-w-2xl flex-col border-line-strong bg-surface sm:max-h-[90dvh] sm:border">
|
||||
<div className="flex items-center gap-2 border-b border-line px-4 pb-3 pt-[max(0.75rem,env(safe-area-inset-top))]">
|
||||
<button type="button" onClick={close} className="grid size-9 place-items-center text-ink-2" aria-label="Fermer">
|
||||
<X size={20} />
|
||||
</button>
|
||||
<span className="font-semibold">{initial.inReplyTo ? 'Réponse' : 'Nouveau message'}</span>
|
||||
<button className="btn btn-primary ms-auto py-2" disabled={busy}>
|
||||
{busy ? <Loader2 size={16} className="animate-spin" /> : <Send size={16} />} Envoyer
|
||||
</button>
|
||||
</div>
|
||||
<div className="divide-y divide-line border-b border-line text-sm">
|
||||
<label className="flex items-center gap-2 px-4">
|
||||
<span className="w-10 shrink-0 text-ink-3">À</span>
|
||||
<input className="min-w-0 flex-1 bg-transparent py-3 outline-none" value={d.to} onChange={(e) => set({ to: e.target.value })} type="text" inputMode="email" autoComplete="off" required />
|
||||
{!showCc && (
|
||||
<button type="button" onClick={() => setShowCc(true)} className="text-xs text-ink-3">
|
||||
Cc
|
||||
</button>
|
||||
)}
|
||||
</label>
|
||||
{showCc && (
|
||||
<label className="flex items-center gap-2 px-4">
|
||||
<span className="w-10 shrink-0 text-ink-3">Cc</span>
|
||||
<input className="min-w-0 flex-1 bg-transparent py-3 outline-none" value={d.cc} onChange={(e) => set({ cc: e.target.value })} type="text" inputMode="email" autoComplete="off" />
|
||||
</label>
|
||||
)}
|
||||
<label className="flex items-center gap-2 px-4">
|
||||
<span className="w-10 shrink-0 text-ink-3">Objet</span>
|
||||
<input className="min-w-0 flex-1 bg-transparent py-3 outline-none" value={d.subject} onChange={(e) => set({ subject: e.target.value.slice(0, 300) })} />
|
||||
</label>
|
||||
</div>
|
||||
<textarea
|
||||
className="min-h-[50dvh] flex-1 resize-none bg-transparent px-4 py-3 text-[15px] leading-relaxed outline-none sm:min-h-80"
|
||||
value={d.text}
|
||||
onChange={(e) => set({ text: e.target.value })}
|
||||
autoFocus={!initial.inReplyTo}
|
||||
placeholder="Ton message…"
|
||||
/>
|
||||
{error && <p className="border-t border-line px-4 py-2 text-sm text-danger">{error}</p>}
|
||||
<p className="border-t border-line px-4 py-2 pb-[max(0.5rem,env(safe-area-inset-bottom))] text-xs text-ink-3">
|
||||
Envoyé par Bobinoo <contact@bobinoo.org>, en texte simple. Plusieurs destinataires : sépare-les par une virgule.
|
||||
</p>
|
||||
</form>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,264 @@
|
||||
import DOMPurify from 'dompurify'
|
||||
import { Ban, ChevronLeft, CornerUpLeft, Forward, ImageOff, Inbox, MailOpen, Paperclip, Trash2 } from 'lucide-react'
|
||||
import { useEffect, useMemo, useRef, useState, type ReactNode } from 'react'
|
||||
import { ApiError, addrList, call, who, type FolderId, type Message } from './api'
|
||||
import { fullDate, sizeLabel } from './format'
|
||||
|
||||
const REMOTE = /^\s*(https?:)?\/\//i
|
||||
|
||||
/**
|
||||
* HTML d'un e-mail rendu sans danger : nettoyé par DOMPurify (ni script, ni formulaire, ni cadre), affiché dans un
|
||||
* cadre isolé (sandbox, sans scripts). Images distantes bloquées par défaut : elles permettent de savoir que le
|
||||
* message a été ouvert. Liens ouverts dans un nouvel onglet.
|
||||
*/
|
||||
function emailDocument(html: string, showImages: boolean): { doc: string; blocked: number } {
|
||||
const clean = DOMPurify.sanitize(html, {
|
||||
WHOLE_DOCUMENT: true,
|
||||
FORBID_TAGS: ['form', 'input', 'button', 'textarea', 'select', 'iframe', 'frame', 'object', 'embed', 'link', 'meta', 'base', 'audio', 'video'],
|
||||
FORBID_ATTR: ['srcset', 'ping', 'formaction'],
|
||||
})
|
||||
const d = new DOMParser().parseFromString(clean, 'text/html')
|
||||
let blocked = 0
|
||||
if (!showImages) {
|
||||
d.querySelectorAll('img').forEach((img) => {
|
||||
const src = img.getAttribute('src') ?? ''
|
||||
if (REMOTE.test(src)) {
|
||||
img.removeAttribute('src')
|
||||
img.setAttribute('alt', img.getAttribute('alt') || '')
|
||||
blocked++
|
||||
}
|
||||
})
|
||||
d.querySelectorAll('[background]').forEach((el) => {
|
||||
if (REMOTE.test(el.getAttribute('background') ?? '')) {
|
||||
el.removeAttribute('background')
|
||||
blocked++
|
||||
}
|
||||
})
|
||||
const noUrl = (css: string) => css.replace(/url\(\s*(['"]?)\s*(https?:)?\/\/[^)]*\)/gi, () => (blocked++, 'none'))
|
||||
d.querySelectorAll('[style]').forEach((el) => el.setAttribute('style', noUrl(el.getAttribute('style') ?? '')))
|
||||
d.querySelectorAll('style').forEach((s) => (s.textContent = noUrl(s.textContent ?? '')))
|
||||
}
|
||||
d.querySelectorAll('a[href]').forEach((a) => {
|
||||
a.setAttribute('target', '_blank')
|
||||
a.setAttribute('rel', 'noopener noreferrer')
|
||||
})
|
||||
const base = d.createElement('style')
|
||||
base.textContent =
|
||||
'html{background:#fff}body{margin:0;padding:16px;font:15px/1.5 -apple-system,"Segoe UI",Roboto,Helvetica,Arial,sans-serif;color:#111;overflow-wrap:anywhere}img{max-width:100%;height:auto}table{max-width:100%}pre{white-space:pre-wrap}'
|
||||
d.head.prepend(base)
|
||||
return { doc: '<!doctype html>' + d.documentElement.outerHTML, blocked }
|
||||
}
|
||||
|
||||
/** Texte brut avec liens cliquables. */
|
||||
function Linkified({ text }: { text: string }) {
|
||||
const parts = text.split(/(https?:\/\/[^\s<>"]+)/g)
|
||||
return (
|
||||
<>
|
||||
{parts.map((p, k) =>
|
||||
k % 2 ? (
|
||||
<a key={k} href={p} target="_blank" rel="noopener noreferrer" className="text-accent underline underline-offset-2">
|
||||
{p}
|
||||
</a>
|
||||
) : (
|
||||
p
|
||||
),
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function HtmlBody({ html, showImages }: { html: string; showImages: boolean }) {
|
||||
const frame = useRef<HTMLIFrameElement>(null)
|
||||
const { doc } = useMemo(() => emailDocument(html, showImages), [html, showImages])
|
||||
// Hauteur du cadre = hauteur du message (pas de double défilement), recalculée quand les images arrivent
|
||||
const fit = () => {
|
||||
const f = frame.current
|
||||
const body = f?.contentDocument?.body
|
||||
// Hauteur du contenu (et non du cadre : documentElement ne descend jamais sous la hauteur affichée)
|
||||
const h = body ? Math.ceil(body.getBoundingClientRect().height) : 0
|
||||
if (f && h) f.style.height = `${Math.max(h, 80) + 2}px`
|
||||
}
|
||||
const onLoad = () => {
|
||||
fit()
|
||||
frame.current?.contentDocument?.querySelectorAll('img').forEach((img) => img.addEventListener('load', fit))
|
||||
window.setTimeout(fit, 300)
|
||||
}
|
||||
useEffect(() => {
|
||||
window.addEventListener('resize', fit)
|
||||
return () => window.removeEventListener('resize', fit)
|
||||
}, [])
|
||||
return (
|
||||
<iframe
|
||||
ref={frame}
|
||||
title="Contenu du message"
|
||||
sandbox="allow-same-origin allow-popups allow-popups-to-escape-sandbox"
|
||||
srcDoc={doc}
|
||||
onLoad={onLoad}
|
||||
className="block h-40 w-full rounded-md border border-line bg-white"
|
||||
/>
|
||||
)
|
||||
}
|
||||
|
||||
function Action({ icon, label, onClick, danger }: { icon: ReactNode; label: string; onClick: () => void; danger?: boolean }) {
|
||||
return (
|
||||
<button onClick={onClick} className={`btn btn-ghost px-3 py-1.5 ${danger ? 'text-danger' : ''}`} title={label}>
|
||||
{icon}
|
||||
<span className="hidden sm:inline">{label}</span>
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
export default function Reader({
|
||||
token,
|
||||
folder,
|
||||
uid,
|
||||
onBack,
|
||||
onReply,
|
||||
onForward,
|
||||
onChanged,
|
||||
onAuthError,
|
||||
}: {
|
||||
token: string
|
||||
folder: FolderId
|
||||
uid: number
|
||||
onBack: () => void
|
||||
onReply: (m: Message) => void
|
||||
onForward: (m: Message) => void
|
||||
onChanged: (removed: boolean) => void
|
||||
onAuthError: (e: unknown) => void
|
||||
}) {
|
||||
const [msg, setMsg] = useState<Message>()
|
||||
const [error, setError] = useState<string>()
|
||||
const [showImages, setShowImages] = useState(false)
|
||||
const [busy, setBusy] = useState(false)
|
||||
|
||||
useEffect(() => {
|
||||
let alive = true
|
||||
setMsg(undefined)
|
||||
setError(undefined)
|
||||
setShowImages(false)
|
||||
call<Message>(token, 'read', { folder, uid })
|
||||
.then((m) => {
|
||||
if (!alive) return
|
||||
setMsg(m)
|
||||
onChanged(false) // lu : compteurs à jour
|
||||
})
|
||||
.catch((e) => {
|
||||
onAuthError(e)
|
||||
if (alive) setError(e instanceof ApiError ? e.message : 'Erreur inattendue.')
|
||||
})
|
||||
return () => {
|
||||
alive = false
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [token, folder, uid])
|
||||
|
||||
const blocked = useMemo(() => (msg?.html ? emailDocument(msg.html, false).blocked : 0), [msg])
|
||||
|
||||
const act = async (action: string, params: Record<string, unknown>, removed: boolean) => {
|
||||
if (busy) return
|
||||
setBusy(true)
|
||||
try {
|
||||
await call(token, action, { folder, uid, ...params })
|
||||
onChanged(removed)
|
||||
if (removed) onBack()
|
||||
} catch (e) {
|
||||
onAuthError(e)
|
||||
setError(e instanceof ApiError ? e.message : 'Erreur inattendue.')
|
||||
} finally {
|
||||
setBusy(false)
|
||||
}
|
||||
}
|
||||
|
||||
const download = async (index: number) => {
|
||||
try {
|
||||
const a = await call<{ filename: string; contentType: string; data: string }>(token, 'attachment', { folder, uid, index })
|
||||
const bytes = Uint8Array.from(atob(a.data), (c) => c.charCodeAt(0))
|
||||
const url = URL.createObjectURL(new Blob([bytes], { type: a.contentType }))
|
||||
const link = document.createElement('a')
|
||||
link.href = url
|
||||
link.download = a.filename
|
||||
link.click()
|
||||
setTimeout(() => URL.revokeObjectURL(url), 30_000)
|
||||
} catch (e) {
|
||||
onAuthError(e)
|
||||
setError(e instanceof ApiError ? e.message : 'Téléchargement impossible.')
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<article className="min-w-0">
|
||||
<div className="sticky top-0 z-10 -mx-4 flex flex-wrap items-center gap-1.5 border-b border-line bg-bg px-4 py-2 lg:static lg:mx-0 lg:border-0 lg:px-0 lg:pt-0">
|
||||
<button onClick={onBack} className="btn px-2 py-1.5 text-ink-2 lg:hidden" aria-label="Retour">
|
||||
<ChevronLeft size={20} />
|
||||
</button>
|
||||
{msg && (
|
||||
<>
|
||||
<Action icon={<CornerUpLeft size={16} />} label="Répondre" onClick={() => onReply(msg)} />
|
||||
<Action icon={<Forward size={16} />} label="Transférer" onClick={() => onForward(msg)} />
|
||||
<Action icon={<MailOpen size={16} />} label="Non lu" onClick={() => void act('seen', { value: false }, false).then(onBack)} />
|
||||
{folder !== 'junk' && folder !== 'trash' && <Action icon={<Ban size={16} />} label="Indésirable" onClick={() => void act('move', { to: 'junk' }, true)} />}
|
||||
{(folder === 'junk' || folder === 'trash') && <Action icon={<Inbox size={16} />} label="Remettre en réception" onClick={() => void act('move', { to: 'inbox' }, true)} />}
|
||||
{folder === 'trash' || folder === 'junk' ? (
|
||||
<Action
|
||||
icon={<Trash2 size={16} />}
|
||||
label="Supprimer définitivement"
|
||||
danger
|
||||
onClick={() => confirm('Supprimer définitivement ce message ?') && void act('delete', {}, true)}
|
||||
/>
|
||||
) : (
|
||||
<Action icon={<Trash2 size={16} />} label="Corbeille" danger onClick={() => void act('move', { to: 'trash' }, true)} />
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{error && <p className="py-6 text-sm text-danger">{error}</p>}
|
||||
{!msg && !error && <p className="py-6 text-sm text-ink-3">Chargement…</p>}
|
||||
{msg && (
|
||||
<div className="pt-4">
|
||||
<h1 className="text-xl font-bold leading-snug sm:text-2xl">{msg.subject || '(sans objet)'}</h1>
|
||||
<div className="mt-3 text-sm">
|
||||
<p>
|
||||
<span className="font-semibold">{who(msg.from)}</span> <span className="text-ink-3">{msg.from.address && msg.from.name ? `<${msg.from.address}>` : ''}</span>
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-ink-3">
|
||||
À : {addrList(msg.to) || '—'}
|
||||
{msg.cc.length > 0 && ` · Cc : ${addrList(msg.cc)}`}
|
||||
</p>
|
||||
<p className="mt-0.5 text-xs text-ink-3">{fullDate(msg.date)}</p>
|
||||
</div>
|
||||
|
||||
{msg.attachments.length > 0 && (
|
||||
<div className="mt-4 flex flex-wrap gap-2">
|
||||
{msg.attachments.map((a) => (
|
||||
<button key={a.index} onClick={() => void download(a.index)} className="badge gap-1.5 px-2.5 py-1.5 text-xs text-ink">
|
||||
<Paperclip size={13} /> {a.filename} <span className="text-ink-3">{sizeLabel(a.size)}</span>
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{msg.html && blocked > 0 && !showImages && (
|
||||
<p className="mt-4 flex flex-wrap items-center gap-2 border border-line bg-surface px-3 py-2 text-xs text-ink-2">
|
||||
<ImageOff size={14} /> Images distantes bloquées (elles signalent à l'expéditeur que le message a été ouvert).
|
||||
<button onClick={() => setShowImages(true)} className="font-semibold text-accent underline underline-offset-2">
|
||||
Afficher les images
|
||||
</button>
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="mt-4">
|
||||
{msg.html ? (
|
||||
<HtmlBody html={msg.html} showImages={showImages} />
|
||||
) : (
|
||||
<p className="whitespace-pre-wrap break-words text-[15px] leading-relaxed">
|
||||
<Linkified text={msg.text} />
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</article>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
/** Appels à la fonction serveur « mail », par le relais nginx de mail.bobinoo.org (qui ajoute le secret). */
|
||||
export class ApiError extends Error {
|
||||
constructor(
|
||||
public status: number,
|
||||
message: string,
|
||||
) {
|
||||
super(message)
|
||||
}
|
||||
}
|
||||
|
||||
const MESSAGES: Record<string, string> = {
|
||||
session: 'Session expirée : reconnecte-toi.',
|
||||
mfa: 'Code de double authentification requis : reconnecte-toi.',
|
||||
interdit: 'Accès réservé aux administrateurs de Bobinoo.',
|
||||
'trop de requêtes': 'Trop de requêtes, patiente une minute.',
|
||||
}
|
||||
|
||||
export async function call<T>(token: string, action: string, params: Record<string, unknown> = {}): Promise<T> {
|
||||
let res: Response
|
||||
try {
|
||||
res = await fetch('/api/mail', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${token}` },
|
||||
body: JSON.stringify({ action, ...params }),
|
||||
credentials: 'omit',
|
||||
cache: 'no-store',
|
||||
})
|
||||
} catch {
|
||||
throw new ApiError(0, 'Serveur injoignable. Vérifie ta connexion.')
|
||||
}
|
||||
if (res.status === 404) throw new ApiError(404, "La messagerie n'est pas reliée au serveur (secret du VPS absent ou différent).")
|
||||
const body = (await res.json().catch(() => ({}))) as { error?: string }
|
||||
if (!res.ok) throw new ApiError(res.status, MESSAGES[body.error ?? ''] ?? body.error ?? `Erreur ${res.status}`)
|
||||
return body as T
|
||||
}
|
||||
|
||||
export type FolderId = 'inbox' | 'sent' | 'drafts' | 'junk' | 'trash'
|
||||
export interface Folder {
|
||||
id: FolderId
|
||||
total: number
|
||||
unseen: number
|
||||
}
|
||||
export interface Addr {
|
||||
name?: string
|
||||
address?: string
|
||||
}
|
||||
export interface Summary {
|
||||
uid: number
|
||||
subject: string
|
||||
from: Addr
|
||||
to: Addr[]
|
||||
date: string | null
|
||||
seen: boolean
|
||||
answered: boolean
|
||||
flagged: boolean
|
||||
attachments: boolean
|
||||
size: number
|
||||
}
|
||||
export interface Message {
|
||||
uid: number
|
||||
subject: string
|
||||
from: Addr
|
||||
to: Addr[]
|
||||
cc: Addr[]
|
||||
replyTo: Addr[]
|
||||
date: string | null
|
||||
messageId: string | null
|
||||
references: string[]
|
||||
html: string | null
|
||||
text: string
|
||||
attachments: { index: number; filename: string; contentType: string; size: number }[]
|
||||
}
|
||||
|
||||
export const FOLDER_LABEL: Record<FolderId, string> = {
|
||||
inbox: 'Réception',
|
||||
sent: 'Envoyés',
|
||||
drafts: 'Brouillons',
|
||||
junk: 'Indésirables',
|
||||
trash: 'Corbeille',
|
||||
}
|
||||
|
||||
export const who = (a?: Addr) => (a?.name || a?.address || 'Inconnu').trim()
|
||||
export const addrList = (l: Addr[]) => l.map((a) => (a.name ? `${a.name} <${a.address}>` : (a.address ?? ''))).join(', ')
|
||||
@@ -0,0 +1,22 @@
|
||||
const time = new Intl.DateTimeFormat('fr-FR', { hour: '2-digit', minute: '2-digit' })
|
||||
const dayMonth = new Intl.DateTimeFormat('fr-FR', { day: 'numeric', month: 'short' })
|
||||
const short = new Intl.DateTimeFormat('fr-FR', { day: '2-digit', month: '2-digit', year: '2-digit' })
|
||||
const full = new Intl.DateTimeFormat('fr-FR', { dateStyle: 'full', timeStyle: 'short' })
|
||||
|
||||
/** Date de la liste : l'heure aujourd'hui, « 12 nov. » cette année, sinon « 12/11/25 ». */
|
||||
export function listDate(d: string | null): string {
|
||||
if (!d) return ''
|
||||
const date = new Date(d)
|
||||
const now = new Date()
|
||||
if (date.toDateString() === now.toDateString()) return time.format(date)
|
||||
if (date.getFullYear() === now.getFullYear()) return dayMonth.format(date)
|
||||
return short.format(date)
|
||||
}
|
||||
|
||||
export const fullDate = (d: string | null) => (d ? full.format(new Date(d)) : '')
|
||||
|
||||
export function sizeLabel(n: number): string {
|
||||
if (n < 1024) return `${n} o`
|
||||
if (n < 1024 * 1024) return `${Math.round(n / 1024)} Ko`
|
||||
return `${(n / 1024 / 1024).toFixed(1).replace('.', ',')} Mo`
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import '@fontsource-variable/epilogue/wght.css'
|
||||
import '../../admin/src/styles.css'
|
||||
import App from './App'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<App />
|
||||
</StrictMode>,
|
||||
)
|
||||
Generated
+11
-1
@@ -9,6 +9,7 @@
|
||||
"version": "2.2.0",
|
||||
"dependencies": {
|
||||
"@fontsource-variable/epilogue": "5.3.0",
|
||||
"dompurify": "3.4.18",
|
||||
"lucide-react": "0.468.0",
|
||||
"react": "19.3.0",
|
||||
"react-dom": "19.3.0"
|
||||
@@ -3002,7 +3003,7 @@
|
||||
"version": "2.0.7",
|
||||
"resolved": "https://registry.npmjs.org/@types/trusted-types/-/trusted-types-2.0.7.tgz",
|
||||
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
|
||||
"dev": true,
|
||||
"devOptional": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@vitejs/plugin-react": {
|
||||
@@ -3529,6 +3530,15 @@
|
||||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/dompurify": {
|
||||
"version": "3.4.18",
|
||||
"resolved": "https://registry.npmjs.org/dompurify/-/dompurify-3.4.18.tgz",
|
||||
"integrity": "sha512-ofe3wI/uNm68HInABYFJYqQxRw1EaKAjNdrFVKqjUY+UZurvNd2L/HuQe097s/4RivWiZyP6tT7aoT8atjfhwg==",
|
||||
"license": "(MPL-2.0 OR Apache-2.0)",
|
||||
"optionalDependencies": {
|
||||
"@types/trusted-types": "^2.0.7"
|
||||
}
|
||||
},
|
||||
"node_modules/dunder-proto": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/dunder-proto/-/dunder-proto-1.0.1.tgz",
|
||||
|
||||
+3
-1
@@ -11,10 +11,12 @@
|
||||
"preview": "vite preview",
|
||||
"typecheck": "tsc --noEmit",
|
||||
"audit": "npm audit --omit=dev",
|
||||
"build:admin": "vite build --config vite.admin.config.ts"
|
||||
"build:admin": "vite build --config vite.admin.config.ts",
|
||||
"build:mail": "vite build --config vite.mail.config.ts"
|
||||
},
|
||||
"dependencies": {
|
||||
"@fontsource-variable/epilogue": "5.3.0",
|
||||
"dompurify": "3.4.18",
|
||||
"lucide-react": "0.468.0",
|
||||
"react": "19.3.0",
|
||||
"react-dom": "19.3.0"
|
||||
|
||||
@@ -16,3 +16,6 @@ verify_jwt = false
|
||||
|
||||
[functions.admin]
|
||||
verify_jwt = false
|
||||
|
||||
[functions.mail]
|
||||
verify_jwt = false
|
||||
@@ -0,0 +1,443 @@
|
||||
// Messagerie Bobinoo (docs/mail.md) : lit et envoie les e-mails de contact@bobinoo.org (boîte OVH Zimbra),
|
||||
// pour l'interface https://mail.bobinoo.org. Mêmes verrous que la console d'administration :
|
||||
// 1. secret du VPS (en-tête X-Admin-Gate, ajouté par nginx sur mail.bobinoo.org), sinon 404 ;
|
||||
// 2. compte connecté AVEC son code de double authentification (jeton « aal2 ») ;
|
||||
// 3. compte dans admin.admins.
|
||||
// Le mot de passe de la boîte (MAIL_PASSWORD, ou SMTP_PASSWORD) ne quitte jamais le serveur.
|
||||
// Lecture en IMAP (imapflow), envoi en SMTP (nodemailer), copie des envois dans « Envoyés ».
|
||||
|
||||
import postgres from 'npm:postgres@3.4.5'
|
||||
import { ImapFlow } from 'npm:imapflow@2.11.0'
|
||||
import { simpleParser } from 'npm:mailparser@3.14.5'
|
||||
import nodemailer from 'npm:nodemailer@6.9.16'
|
||||
import MailComposer from 'npm:nodemailer@6.9.16/lib/mail-composer/index.js'
|
||||
|
||||
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 MAIL_USER = Deno.env.get('MAIL_USER') ?? 'contact@bobinoo.org'
|
||||
const MAIL_PASSWORD = Deno.env.get('MAIL_PASSWORD') || Deno.env.get('SMTP_PASSWORD') || ''
|
||||
const MAIL_HOST = Deno.env.get('MAIL_HOST') ?? 'ssl0.ovh.net'
|
||||
const FROM_NAME = 'Bobinoo'
|
||||
|
||||
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 EMAIL = /^[^\s@<>(),;:"]{1,64}@[A-Za-z0-9.-]{1,253}\.[A-Za-z]{2,24}$/
|
||||
const PAGE = 50
|
||||
const MAX_MESSAGE = 25 * 1024 * 1024
|
||||
const MAX_ATTACHMENT = 15 * 1024 * 1024
|
||||
|
||||
// ─── Verrous (comme la fonction « admin ») ───
|
||||
|
||||
const enc = new TextEncoder()
|
||||
async function sameSecret(a: string, b: string): Promise<boolean> {
|
||||
const [x, y] = await Promise.all([crypto.subtle.digest('SHA-256', enc.encode(a)), crypto.subtle.digest('SHA-256', enc.encode(b))])
|
||||
const u = new Uint8Array(x)
|
||||
const v = new Uint8Array(y)
|
||||
let diff = 0
|
||||
for (let i = 0; i < u.length; i++) diff |= u[i] ^ v[i]
|
||||
return diff === 0
|
||||
}
|
||||
|
||||
const notFound = () => new Response('Not found', { status: 404 })
|
||||
const json = (status: number, body: unknown) =>
|
||||
new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json; charset=utf-8', 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff' } })
|
||||
|
||||
function tokenAal(token: string): string | undefined {
|
||||
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 }).aal
|
||||
} catch {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
async function verifiedUser(req: Request): Promise<{ id: string; email: string; ok: 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 ?? '', ok: totp && tokenAal(token) === 'aal2' }
|
||||
}
|
||||
|
||||
const hits = new Map<string, number[]>()
|
||||
function limited(key: string): boolean {
|
||||
const now = Date.now()
|
||||
const list = (hits.get(key) ?? []).filter((t) => now - t < 60_000)
|
||||
list.push(now)
|
||||
hits.set(key, list)
|
||||
if (hits.size > 1000) hits.clear()
|
||||
return list.length > 120
|
||||
}
|
||||
|
||||
async function log(adminId: string, action: string, target: string | null, details: Record<string, unknown>) {
|
||||
await sql!`select admin.log(${adminId}::uuid, ${action}::text, ${null}::uuid, ${target}::text, ${sql!.json(details as never)}::jsonb)`
|
||||
}
|
||||
|
||||
// ─── Boîte (IMAP) ───
|
||||
|
||||
/** Erreur à montrer telle quelle dans l'interface. */
|
||||
class UserError extends Error {}
|
||||
|
||||
async function withImap<T>(fn: (c: ImapFlow) => Promise<T>): Promise<T> {
|
||||
const c = new ImapFlow({ host: MAIL_HOST, port: 993, secure: true, auth: { user: MAIL_USER, pass: MAIL_PASSWORD }, logger: false, socketTimeout: 30_000 })
|
||||
try {
|
||||
await c.connect()
|
||||
} catch (e) {
|
||||
console.error('imap connexion', (e as Error)?.message)
|
||||
throw new UserError('Connexion à la boîte impossible (mot de passe MAIL_PASSWORD ?).')
|
||||
}
|
||||
try {
|
||||
return await fn(c)
|
||||
} finally {
|
||||
await c.logout().catch(() => c.close())
|
||||
}
|
||||
}
|
||||
|
||||
type FolderId = 'inbox' | 'sent' | 'drafts' | 'junk' | 'trash'
|
||||
const FOLDER_IDS: FolderId[] = ['inbox', 'sent', 'drafts', 'junk', 'trash']
|
||||
const SPECIAL: Record<string, FolderId> = { '\\Sent': 'sent', '\\Drafts': 'drafts', '\\Junk': 'junk', '\\Trash': 'trash' }
|
||||
const FALLBACK: Record<FolderId, RegExp> = { inbox: /^inbox$/i, sent: /^(sent|envoy)/i, drafts: /^(drafts|brouillon)/i, junk: /^(junk|spam|ind[ée]sirable)/i, trash: /^(trash|corbeille|deleted)/i }
|
||||
|
||||
/** Dossiers de la boîte : réception, envoyés, brouillons, indésirables, corbeille (avec leurs compteurs). */
|
||||
async function folders(c: ImapFlow, withStatus = false) {
|
||||
const list = await c.list(withStatus ? { statusQuery: { messages: true, unseen: true } } : {})
|
||||
const out = new Map<FolderId, { path: string; total: number; unseen: number }>()
|
||||
for (const m of list) {
|
||||
const id: FolderId | undefined = m.path.toUpperCase() === 'INBOX' ? 'inbox' : SPECIAL[m.specialUse ?? '']
|
||||
if (id && !out.has(id)) out.set(id, { path: m.path, total: m.status?.messages ?? 0, unseen: m.status?.unseen ?? 0 })
|
||||
}
|
||||
for (const id of FOLDER_IDS) {
|
||||
if (out.has(id)) continue
|
||||
const m = list.find((x) => FALLBACK[id].test(x.name))
|
||||
if (m) out.set(id, { path: m.path, total: m.status?.messages ?? 0, unseen: m.status?.unseen ?? 0 })
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
async function pathOf(c: ImapFlow, folder: unknown): Promise<string> {
|
||||
const id = FOLDER_IDS.includes(folder as FolderId) ? (folder as FolderId) : 'inbox'
|
||||
const path = (await folders(c)).get(id)?.path
|
||||
if (!path) throw new UserError('Dossier introuvable.')
|
||||
return path
|
||||
}
|
||||
|
||||
interface Addr {
|
||||
name?: string
|
||||
address?: string
|
||||
}
|
||||
const addr = (a?: { name?: string; address?: string }[]): Addr[] => (a ?? []).slice(0, 50).map((x) => ({ name: x.name || undefined, address: x.address || undefined }))
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function hasAttachment(node: any): boolean {
|
||||
if (!node) return false
|
||||
if (node.disposition === 'attachment') return true
|
||||
return Array.isArray(node.childNodes) && node.childNodes.some(hasAttachment)
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function summary(m: any) {
|
||||
return {
|
||||
uid: m.uid as number,
|
||||
subject: (m.envelope?.subject as string | undefined) ?? '',
|
||||
from: addr(m.envelope?.from)[0] ?? {},
|
||||
to: addr(m.envelope?.to),
|
||||
date: (m.envelope?.date ?? m.internalDate ?? null) as Date | null,
|
||||
seen: m.flags?.has('\\Seen') ?? false,
|
||||
answered: m.flags?.has('\\Answered') ?? false,
|
||||
flagged: m.flags?.has('\\Flagged') ?? false,
|
||||
attachments: hasAttachment(m.bodyStructure),
|
||||
size: m.size as number,
|
||||
}
|
||||
}
|
||||
|
||||
const SUMMARY = { uid: true, flags: true, envelope: true, internalDate: true, size: true, bodyStructure: true } as const
|
||||
|
||||
async function listMessages(c: ImapFlow, folder: unknown, page: number) {
|
||||
const path = await pathOf(c, folder)
|
||||
const lock = await c.getMailboxLock(path, { readOnly: true })
|
||||
try {
|
||||
const mb = c.mailbox
|
||||
const total = mb && typeof mb === 'object' ? mb.exists : 0
|
||||
const to = total - page * PAGE
|
||||
if (to < 1) return { total, messages: [] }
|
||||
const from = Math.max(1, to - PAGE + 1)
|
||||
const out = []
|
||||
for await (const m of c.fetch(`${from}:${to}`, SUMMARY)) out.push(summary(m))
|
||||
out.sort((a, b) => b.uid - a.uid)
|
||||
return { total, messages: out }
|
||||
} finally {
|
||||
lock.release()
|
||||
}
|
||||
}
|
||||
|
||||
async function searchMessages(c: ImapFlow, folder: unknown, q: string) {
|
||||
const path = await pathOf(c, folder)
|
||||
const lock = await c.getMailboxLock(path, { readOnly: true })
|
||||
try {
|
||||
const uids = (await c.search({ or: [{ subject: q }, { from: q }, { to: q }, { body: q }] }, { uid: true })) || []
|
||||
const last = uids.slice(-PAGE)
|
||||
if (!last.length) return { total: 0, messages: [] }
|
||||
const out = []
|
||||
for await (const m of c.fetch(last.join(','), SUMMARY, { uid: true })) out.push(summary(m))
|
||||
out.sort((a, b) => b.uid - a.uid)
|
||||
return { total: uids.length, messages: out }
|
||||
} finally {
|
||||
lock.release()
|
||||
}
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
async function parseOne(c: ImapFlow, path: string, uid: number, markSeen: boolean): Promise<any> {
|
||||
const lock = await c.getMailboxLock(path)
|
||||
try {
|
||||
const msg = await c.fetchOne(String(uid), { uid: true, size: true, flags: true }, { uid: true })
|
||||
if (!msg) throw new UserError('Message introuvable (déplacé ou supprimé ?).')
|
||||
if ((msg.size ?? 0) > MAX_MESSAGE) throw new UserError('Message trop volumineux pour être affiché ici.')
|
||||
const full = await c.fetchOne(String(uid), { source: true }, { uid: true })
|
||||
if (!full || !full.source) throw new UserError('Message illisible.')
|
||||
if (markSeen && !msg.flags?.has('\\Seen')) await c.messageFlagsAdd(String(uid), ['\\Seen'], { uid: true })
|
||||
return await simpleParser(full.source)
|
||||
} finally {
|
||||
lock.release()
|
||||
}
|
||||
}
|
||||
|
||||
/** Octets → base64, par morceaux (un seul String.fromCharCode(...) déborderait la pile au-delà de ~100 Ko). */
|
||||
function base64(content: ArrayLike<number>): string {
|
||||
const bytes = new Uint8Array(content as ArrayLike<number>)
|
||||
let bin = ''
|
||||
for (let i = 0; i < bytes.length; i += 0x8000) bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000))
|
||||
return btoa(bin)
|
||||
}
|
||||
|
||||
/** Images intégrées (cid:) remplacées par leur contenu, dans la limite de 3 Mo. */
|
||||
// deno-lint-ignore no-explicit-any
|
||||
function inlineImages(html: string, attachments: any[]): string {
|
||||
let budget = 3 * 1024 * 1024
|
||||
for (const a of attachments) {
|
||||
if (!a.cid || !/^image\/(png|jpe?g|gif|webp)$/i.test(String(a.contentType)) || a.size > budget) continue
|
||||
budget -= a.size
|
||||
html = html.split(`cid:${a.cid}`).join(`data:${a.contentType};base64,${base64(a.content)}`)
|
||||
}
|
||||
return html
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const visibleAttachments = (attachments: any[]) =>
|
||||
attachments.map((a, index) => ({ a, index })).filter(({ a }) => !(a.related && a.cid) || a.contentDisposition === 'attachment')
|
||||
|
||||
async function readMessage(c: ImapFlow, folder: unknown, uid: number) {
|
||||
const path = await pathOf(c, folder)
|
||||
const p = await parseOne(c, path, uid, true)
|
||||
const html = typeof p.html === 'string' ? inlineImages(p.html, p.attachments ?? []).slice(0, 2_000_000) : null
|
||||
return {
|
||||
uid,
|
||||
subject: p.subject ?? '',
|
||||
// deno-lint-ignore no-explicit-any
|
||||
from: addr((p.from?.value ?? []) as any)[0] ?? {},
|
||||
// deno-lint-ignore no-explicit-any
|
||||
to: addr((p.to?.value ?? []) as any),
|
||||
// deno-lint-ignore no-explicit-any
|
||||
cc: addr((p.cc?.value ?? []) as any),
|
||||
// deno-lint-ignore no-explicit-any
|
||||
replyTo: addr((p.replyTo?.value ?? []) as any),
|
||||
date: p.date ?? null,
|
||||
messageId: p.messageId ?? null,
|
||||
references: Array.isArray(p.references) ? p.references : p.references ? [p.references] : [],
|
||||
html,
|
||||
text: typeof p.text === 'string' ? p.text.slice(0, 500_000) : '',
|
||||
attachments: visibleAttachments(p.attachments ?? []).map(({ a, index }) => ({
|
||||
index,
|
||||
filename: a.filename || 'pièce jointe',
|
||||
contentType: a.contentType,
|
||||
size: a.size,
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
async function readAttachment(c: ImapFlow, folder: unknown, uid: number, index: number) {
|
||||
const path = await pathOf(c, folder)
|
||||
const p = await parseOne(c, path, uid, false)
|
||||
const a = (p.attachments ?? [])[index]
|
||||
if (!a) throw new UserError('Pièce jointe introuvable.')
|
||||
if (a.size > MAX_ATTACHMENT) throw new UserError('Pièce jointe trop volumineuse (15 Mo maximum ici).')
|
||||
return { filename: a.filename || 'piece-jointe', contentType: a.contentType || 'application/octet-stream', data: base64(a.content) }
|
||||
}
|
||||
|
||||
// ─── Envoi (SMTP) ───
|
||||
|
||||
function recipients(v: unknown): string[] {
|
||||
const list = (typeof v === 'string' ? v.split(/[,;]/) : Array.isArray(v) ? v : []).map((x) => String(x).trim()).filter(Boolean)
|
||||
if (list.length > 20) throw new UserError('20 destinataires au maximum.')
|
||||
for (const r of list) if (!EMAIL.test(r)) throw new UserError(`Adresse invalide : ${r.slice(0, 80)}`)
|
||||
return list
|
||||
}
|
||||
|
||||
async function sendMessage(body: Record<string, unknown>) {
|
||||
const to = recipients(body.to)
|
||||
const cc = recipients(body.cc)
|
||||
if (!to.length) throw new UserError('Ajoute au moins un destinataire.')
|
||||
const subject = str(body.subject, 300)
|
||||
const text = typeof body.text === 'string' ? body.text.slice(0, 100_000) : ''
|
||||
const inReplyTo = str(body.inReplyTo, 500) || undefined
|
||||
const references = Array.isArray(body.references) ? body.references.map((r) => str(r, 500)).filter(Boolean).slice(-20) : undefined
|
||||
const mail = { from: { name: FROM_NAME, address: MAIL_USER }, to, cc: cc.length ? cc : undefined, subject, text, inReplyTo, references }
|
||||
const raw: Uint8Array = await new MailComposer(mail).compile().build()
|
||||
const transport = nodemailer.createTransport({ host: MAIL_HOST, port: 465, secure: true, auth: { user: MAIL_USER, pass: MAIL_PASSWORD } })
|
||||
try {
|
||||
await transport.sendMail({ envelope: { from: MAIL_USER, to: [...to, ...cc] }, raw })
|
||||
} catch (e) {
|
||||
console.error('smtp', (e as Error)?.message)
|
||||
throw new UserError("L'envoi a échoué. Réessaie dans un instant.")
|
||||
}
|
||||
// Copie dans « Envoyés » ; réponse : le message d'origine est marqué « répondu »
|
||||
await withImap(async (c) => {
|
||||
const f = await folders(c)
|
||||
const sent = f.get('sent')?.path
|
||||
if (sent) await c.append(sent, raw, ['\\Seen'])
|
||||
const replied = typeof body.answeredUid === 'number' ? body.answeredUid : 0
|
||||
if (replied > 0) {
|
||||
const path = f.get(FOLDER_IDS.includes(body.answeredFolder as FolderId) ? (body.answeredFolder as FolderId) : 'inbox')?.path
|
||||
if (path) {
|
||||
const lock = await c.getMailboxLock(path)
|
||||
try {
|
||||
await c.messageFlagsAdd(String(replied), ['\\Answered'], { uid: true })
|
||||
} finally {
|
||||
lock.release()
|
||||
}
|
||||
}
|
||||
}
|
||||
}).catch((e) => console.error('copie envoyés', (e as Error)?.message))
|
||||
return { ok: true, to, subject }
|
||||
}
|
||||
|
||||
const str = (v: unknown, max: number) => (typeof v === 'string' ? v.trim().slice(0, max) : '')
|
||||
const uidOf = (v: unknown) => (typeof v === 'number' && Number.isInteger(v) && v > 0 ? v : 0)
|
||||
|
||||
Deno.serve(async (req) => {
|
||||
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()
|
||||
|
||||
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.ok) return json(403, { error: 'mfa' })
|
||||
const [{ ok: isAdmin }] = await sql`select admin.is_admin(${user.id}::uuid) as ok`
|
||||
if (!isAdmin) {
|
||||
await log(user.id, 'accès refusé (messagerie)', user.email, {})
|
||||
return json(403, { error: 'interdit' })
|
||||
}
|
||||
if (!MAIL_PASSWORD) return json(503, { error: 'Mot de passe de la boîte non configuré (secret MAIL_PASSWORD dans Supabase).' })
|
||||
|
||||
const text = await req.text()
|
||||
if (text.length > 200_000) return json(413, { error: 'trop long' })
|
||||
let body: Record<string, unknown>
|
||||
try {
|
||||
body = JSON.parse(text) as Record<string, unknown>
|
||||
} catch {
|
||||
return json(400, { error: 'json' })
|
||||
}
|
||||
const action = str(body.action, 30)
|
||||
|
||||
try {
|
||||
switch (action) {
|
||||
case 'hello': {
|
||||
await log(user.id, 'connexion (messagerie)', user.email, { appareil: str(req.headers.get('User-Agent'), 200) })
|
||||
return json(200, { mailbox: MAIL_USER })
|
||||
}
|
||||
case 'folders':
|
||||
return json(
|
||||
200,
|
||||
await withImap(async (c) => {
|
||||
const f = await folders(c, true)
|
||||
return FOLDER_IDS.filter((id) => f.has(id)).map((id) => ({ id, total: f.get(id)!.total, unseen: f.get(id)!.unseen }))
|
||||
}),
|
||||
)
|
||||
case 'list': {
|
||||
const page = typeof body.page === 'number' && Number.isInteger(body.page) && body.page >= 0 && body.page < 1000 ? body.page : 0
|
||||
const q = str(body.q, 100)
|
||||
return json(200, await withImap((c) => (q ? searchMessages(c, body.folder, q) : listMessages(c, body.folder, page))))
|
||||
}
|
||||
case 'read': {
|
||||
const uid = uidOf(body.uid)
|
||||
if (!uid) return json(400, { error: 'paramètres' })
|
||||
return json(200, await withImap((c) => readMessage(c, body.folder, uid)))
|
||||
}
|
||||
case 'attachment': {
|
||||
const uid = uidOf(body.uid)
|
||||
const index = typeof body.index === 'number' && Number.isInteger(body.index) && body.index >= 0 ? body.index : -1
|
||||
if (!uid || index < 0) return json(400, { error: 'paramètres' })
|
||||
return json(200, await withImap((c) => readAttachment(c, body.folder, uid, index)))
|
||||
}
|
||||
case 'seen': {
|
||||
const uid = uidOf(body.uid)
|
||||
if (!uid || typeof body.value !== 'boolean') return json(400, { error: 'paramètres' })
|
||||
await withImap(async (c) => {
|
||||
const lock = await c.getMailboxLock(await pathOf(c, body.folder))
|
||||
try {
|
||||
if (body.value) await c.messageFlagsAdd(String(uid), ['\\Seen'], { uid: true })
|
||||
else await c.messageFlagsRemove(String(uid), ['\\Seen'], { uid: true })
|
||||
} finally {
|
||||
lock.release()
|
||||
}
|
||||
})
|
||||
return json(200, { ok: true })
|
||||
}
|
||||
case 'move': {
|
||||
const uid = uidOf(body.uid)
|
||||
const to = body.to as FolderId
|
||||
if (!uid || !['inbox', 'junk', 'trash'].includes(to)) return json(400, { error: 'paramètres' })
|
||||
await withImap(async (c) => {
|
||||
const f = await folders(c)
|
||||
const from = f.get(FOLDER_IDS.includes(body.folder as FolderId) ? (body.folder as FolderId) : 'inbox')?.path
|
||||
const dest = f.get(to)?.path
|
||||
if (!from || !dest) throw new UserError('Dossier introuvable.')
|
||||
const lock = await c.getMailboxLock(from)
|
||||
try {
|
||||
await c.messageMove(String(uid), dest, { uid: true })
|
||||
} finally {
|
||||
lock.release()
|
||||
}
|
||||
})
|
||||
return json(200, { ok: true })
|
||||
}
|
||||
case 'delete': {
|
||||
// Suppression définitive : seulement depuis la corbeille ou les indésirables
|
||||
const uid = uidOf(body.uid)
|
||||
if (!uid || !['trash', 'junk'].includes(body.folder as string)) return json(400, { error: 'paramètres' })
|
||||
await withImap(async (c) => {
|
||||
const lock = await c.getMailboxLock(await pathOf(c, body.folder))
|
||||
try {
|
||||
await c.messageDelete(String(uid), { uid: true })
|
||||
} finally {
|
||||
lock.release()
|
||||
}
|
||||
})
|
||||
await log(user.id, 'e-mail supprimé', null, { dossier: String(body.folder) })
|
||||
return json(200, { ok: true })
|
||||
}
|
||||
case 'send': {
|
||||
const r = await sendMessage(body)
|
||||
await log(user.id, 'e-mail envoyé', r.to.join(', ').slice(0, 200), { objet: r.subject })
|
||||
return json(200, { ok: true })
|
||||
}
|
||||
default:
|
||||
return json(400, { error: 'action inconnue' })
|
||||
}
|
||||
} catch (e) {
|
||||
if (e instanceof UserError) return json(400, { error: e.message })
|
||||
console.error('mail', action, (e as Error)?.message)
|
||||
return json(500, { error: 'erreur serveur' })
|
||||
}
|
||||
})
|
||||
+1
-1
@@ -15,5 +15,5 @@
|
||||
"allowImportingTsExtensions": false,
|
||||
"types": ["vite/client", "vite-plugin-pwa/client"]
|
||||
},
|
||||
"include": ["src", "vite.config.ts", "admin/src", "vite.admin.config.ts"]
|
||||
"include": ["src", "vite.config.ts", "admin/src", "vite.admin.config.ts", "mail/src", "vite.mail.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { defineConfig, loadEnv } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
/**
|
||||
* Messagerie Bobinoo (docs/mail.md) : interface de contact@bobinoo.org, site à part construit dans dist-mail/.
|
||||
* Servie par nginx sur https://mail.bobinoo.org (deploy/nginx/mail.conf).
|
||||
*/
|
||||
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: 'mail',
|
||||
envDir: '..',
|
||||
base: '/',
|
||||
plugins: [react(), tailwindcss()],
|
||||
build: { outDir: '../dist-mail', emptyOutDir: true, sourcemap: false },
|
||||
}
|
||||
})
|
||||
Reference in new issue
Block a user