// 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 { 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() 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) { 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(fn: (c: ImapFlow) => Promise): Promise { 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 = { '\\Sent': 'sent', '\\Drafts': 'drafts', '\\Junk': 'junk', '\\Trash': 'trash' } const FALLBACK: Record = { 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() 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 { 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 { 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): string { const bytes = new Uint8Array(content as ArrayLike) 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) { 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 try { body = JSON.parse(text) as Record } 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' }) } })