Messagerie Bobinoo : https://mail.bobinoo.org, interface de contact@bobinoo.org
- Site à part (mail/, build:mail → dist-mail/) aux couleurs de Bobinoo : dossiers (réception, envoyés, brouillons, indésirables, corbeille), liste, lecture, pièces jointes, écrire / répondre / transférer, non lu, indésirable, corbeille, suppression définitive, recherche, vérification chaque minute. - E-mails HTML nettoyés (DOMPurify) et affichés dans un cadre isolé sans script ; images distantes bloquées par défaut (« Afficher les images »). - Fonction Edge « mail » (déployée) : IMAP / SMTP vers la boîte OVH (mot de passe MAIL_PASSWORD côté serveur), copie des envois dans « Envoyés ». Mêmes verrous que la console : secret X-Admin-Gate, compte admin + double authentification, limite d'appels, journal. - nginx : mail.conf sert la messagerie (CSP, sans cache, noindex) et relaie /api/mail ; webmail.bobinoo.org renvoie vers mail.bobinoo.org. Guide : docs/mail.md. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01YVo1qxKoBQCaMd7Ue8PGbe
This commit is contained in:
21 files changed
+1489
-12
No files matched your search
@@ -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>
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user