diff --git a/.gitea/workflows/deploy.yml b/.gitea/workflows/deploy.yml index 2d1583b..96dc073 100644 --- a/.gitea/workflows/deploy.yml +++ b/.gitea/workflows/deploy.yml @@ -35,7 +35,7 @@ jobs: env: VITE_SUPABASE_URL: ${{ vars.VITE_SUPABASE_URL }} VITE_SUPABASE_ANON_KEY: ${{ secrets.VITE_SUPABASE_ANON_KEY }} - run: cd src && npm run build && 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 }} diff --git a/.gitignore b/.gitignore index f865532..5c39df1 100644 --- a/.gitignore +++ b/.gitignore @@ -12,3 +12,4 @@ _to_delete .env.deploy tsconfig.tsbuildinfo dist-admin +dist-mail diff --git a/CLAUDE.md b/CLAUDE.md index 0ecd9b9..210da18 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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`. diff --git a/deploy/nginx/mail.conf b/deploy/nginx/mail.conf index 112e792..ceb3dc3 100644 --- a/deploy/nginx/mail.conf +++ b/deploy/nginx/mail.conf @@ -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/azuucine/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/; } diff --git a/deploy/nginx/site.conf b/deploy/nginx/site.conf index 5fb611e..b9fc3b4 100644 --- a/deploy/nginx/site.conf +++ b/deploy/nginx/site.conf @@ -48,5 +48,5 @@ server { # Console d'administration : https://admin.bobinoo.org (voir admin.conf et docs/admin.md) include /srv/azuucine/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/azuucine/current/nginx/mail.conf; diff --git a/deploy/release.sh b/deploy/release.sh index 42fc83a..0ced2c8 100755 --- a/deploy/release.sh +++ b/deploy/release.sh @@ -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 diff --git a/docs/emails/README.md b/docs/emails/README.md index 8913c0e..473ac1a 100644 --- a/docs/emails/README.md +++ b/docs/emails/README.md @@ -20,6 +20,6 @@ DMARC `_dmarc` TXT `v=DMARC1; p=none; rua=mailto:`. ## 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`. diff --git a/docs/mail.md b/docs/mail.md new file mode 100644 index 0000000..c321301 --- /dev/null +++ b/docs/mail.md @@ -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. diff --git a/mail/index.html b/mail/index.html new file mode 100644 index 0000000..10383e5 --- /dev/null +++ b/mail/index.html @@ -0,0 +1,18 @@ + + + + + + + + + + + + Bobinoo Mail + + +
+ + + diff --git a/mail/src/App.tsx b/mail/src/App.tsx new file mode 100644 index 0000000..f00c2a6 --- /dev/null +++ b/mail/src/App.tsx @@ -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 = { + inbox: , + sent: , + drafts: , + junk: , + trash: , +} + +function Logo() { + return ( + + Bobinoo Mail + + ) +} + +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() + + 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 (setNotice(undefined), setSession({ token, mailbox }))} /> + return +} + +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() + const codeRef = useRef(null) + + const submit = async (e: FormEvent) => { + e.preventDefault() + if (busy) return + setBusy(true) + setError(undefined) + try { + if (!step) { + const r = await signIn(email, password) + setPassword('') + if (!r.factorId) { + await signOut(r.token) + throw new AuthError("Ce compte n'a pas la double authentification. Active-la d'abord dans l'app 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 ( +
+ +

contact@bobinoo.org

+

Connecte-toi avec ton compte Bobinoo (administrateur), puis ton code de double authentification.

+ {notice &&

{notice}

} +
+ {!step ? ( + <> + setEmail(e.target.value)} required /> + setPassword(e.target.value)} required /> + + ) : ( + <> +

Code à 6 chiffres de ton application d'authentification :

+ setCode(e.target.value)} + required + /> + + )} + {error &&

{error}

} + + {step && ( + + )} +
+
+ ) +} + +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([]) + const [folder, setFolder] = useState('inbox') + const [list, setList] = useState() + 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() + const [selected, setSelected] = useState() + const [draft, setDraft] = useState() + const [toast, setToast] = useState() + + 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(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 = ( +
+
+ setQ(e.target.value.slice(0, 100))} enterKeyHint="search" /> + + +
+ {query && ( +

+ Résultats pour « {query} » ·{' '} + +

+ )} + {error &&

{error}

} + {!list && !error &&

Chargement…

} + {list && !list.length &&

{query ? 'Aucun message trouvé.' : 'Aucun message.'}

} +
    + {list?.map((m) => { + const person = folder === 'sent' || folder === 'drafts' ? `À : ${m.to.map(who).join(', ') || '—'}` : who(m.from) + return ( +
  • + +
  • + ) + })} +
+ {list && !query && list.length < total && ( + + )} +
+ ) + + return ( +
+
+
+ + {mailbox} + + +
+ +
+ +
+ + {listPane} + {selected ? ( + 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} + /> + ) : ( +

Choisis un message pour le lire.

+ )} +
+ + {draft && ( + setDraft(undefined)} + onSent={() => { + setDraft(undefined) + flash('Message envoyé') + loadFolders() + if (folder === 'sent') void loadList(0, true) + }} + onAuthError={onAuthError} + /> + )} + {toast &&

{toast}

} +
+ ) +} + +function FolderButton({ f, active, onClick }: { f: Folder; active: boolean; onClick: () => void }) { + return ( + + ) +} diff --git a/mail/src/Compose.tsx b/mail/src/Compose.tsx new file mode 100644 index 0000000..723da92 --- /dev/null +++ b/mail/src/Compose.tsx @@ -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() + const set = (patch: Partial) => 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 ( +
+
+
+ + {initial.inReplyTo ? 'Réponse' : 'Nouveau message'} + +
+
+ + {showCc && ( + + )} + +
+