diff --git a/package-lock.json b/package-lock.json index f9bf8e7..2655b13 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,7 @@ "name": "aitools", "version": "0.1.0", "dependencies": { + "imapflow": "^1.7.8", "mysql2": "^3.11.0", "nodemailer": "^6.9.15", "pg": "^8.13.0" @@ -16,6 +17,12 @@ "node": ">=22.13" } }, + "node_modules/@pinojs/redact": { + "version": "0.4.0", + "resolved": "https://registry.npmjs.org/@pinojs/redact/-/redact-0.4.0.tgz", + "integrity": "sha512-k2ENnmBugE/rzQfEcdWHcCY+/FM3VLzH9cYEsbdsoqrvzAKRhUZeRNhAZvB8OitQJ1TBed3yqWtdjzS6wJKBwg==", + "license": "MIT" + }, "node_modules/@types/node": { "version": "26.6.5", "resolved": "https://registry.npmjs.org/@types/node/-/node-26.6.5.tgz", @@ -26,6 +33,26 @@ "undici-types": "~8.9.0" } }, + "node_modules/@zone-eu/mailsplit": { + "version": "5.4.16", + "resolved": "https://registry.npmjs.org/@zone-eu/mailsplit/-/mailsplit-5.4.16.tgz", + "integrity": "sha512-zQ9iXvlT3Wi/hazeC1MdI4rQc1UJwJ6IQ6QzSZ5KDxLZZWQSazWLOzImLFluXadKShJ9WJvI1xH+AyVS8b9azg==", + "license": "(MIT OR EUPL-1.1+)", + "dependencies": { + "libbase64": "1.3.0", + "libmime": "5.4.3", + "libqp": "2.1.1" + } + }, + "node_modules/atomic-sleep": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/atomic-sleep/-/atomic-sleep-1.0.0.tgz", + "integrity": "sha512-kNOjDqAh7px0XWNI+4QbzoiR/nTkHAWNud2uvnJquD1/x5a7EQZMJT0AczqK0Qn67oY/TTQ1LbUKajZpp3I9tQ==", + "license": "MIT", + "engines": { + "node": ">=8.0.0" + } + }, "node_modules/aws-ssl-profiles": { "version": "1.1.2", "resolved": "https://registry.npmjs.org/aws-ssl-profiles/-/aws-ssl-profiles-1.1.2.tgz", @@ -35,6 +62,15 @@ "node": ">= 6.0.0" } }, + "node_modules/encoding-japanese": { + "version": "2.3.0", + "resolved": "https://registry.npmjs.org/encoding-japanese/-/encoding-japanese-2.3.0.tgz", + "integrity": "sha512-eQyh1vzHz13DUkZcJO+0IOAoKXRQwKV5IBffeuYsWZyRLGiSzfzXObCqWvqFXdX0UU8qOk+lBXbkUhMCpdJe4Q==", + "license": "MIT", + "engines": { + "node": ">=18.0.0" + } + }, "node_modules/generate-function": { "version": "2.3.1", "resolved": "https://registry.npmjs.org/generate-function/-/generate-function-2.3.1.tgz", @@ -60,12 +96,61 @@ "url": "https://opencollective.com/express" } }, + "node_modules/imapflow": { + "version": "1.7.8", + "resolved": "https://registry.npmjs.org/imapflow/-/imapflow-1.7.8.tgz", + "integrity": "sha512-dJoCIdZOJh26Rn2PdwEzwj0bRDgGBxxX38pio534FagIHVuR2l0SAfLr6sJo32YfuJHiSs/U2ntNDHnMg3/Hlg==", + "license": "MIT", + "dependencies": { + "@zone-eu/mailsplit": "5.4.16", + "encoding-japanese": "2.3.0", + "iconv-lite": "0.7.3", + "libbase64": "1.3.0", + "libmime": "5.4.3", + "libqp": "2.1.1", + "pino": "10.3.1", + "socks": "2.8.9" + } + }, + "node_modules/ip-address": { + "version": "10.7.4", + "resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.7.4.tgz", + "integrity": "sha512-DWBMKyeM25D70nrIiTkgQth59/G+naKOTep6huF9j+GmeK3DMD60Zvxg5d5qQnz+38AHgou6ean2LECX+lrKDg==", + "license": "MIT", + "engines": { + "node": ">= 12" + } + }, "node_modules/is-property": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/is-property/-/is-property-1.0.2.tgz", "integrity": "sha512-Ks/IoX00TtClbGQr4TWXemAnktAQvYB7HzcCxDGqEZU6oCmb2INHuOoKxbtR+HFkmYWBKv/dOZtGRiAjDhj92g==", "license": "MIT" }, + "node_modules/libbase64": { + "version": "1.3.0", + "resolved": "https://registry.npmjs.org/libbase64/-/libbase64-1.3.0.tgz", + "integrity": "sha512-GgOXd0Eo6phYgh0DJtjQ2tO8dc0IVINtZJeARPeiIJqge+HdsWSuaDTe8ztQ7j/cONByDZ3zeB325AHiv5O0dg==", + "license": "MIT" + }, + "node_modules/libmime": { + "version": "5.4.3", + "resolved": "https://registry.npmjs.org/libmime/-/libmime-5.4.3.tgz", + "integrity": "sha512-di9BoDabBUMqjeD/wGj+hHpSgdqAph5ui7w6OdY6NpzU6O6VFLQsMOg9tqCjm/zf9OHzAM9EZxSOF7uIb8O8Hw==", + "license": "MIT", + "dependencies": { + "encoding-japanese": "2.3.0", + "iconv-lite": "0.7.3", + "libbase64": "1.3.0", + "libqp": "2.1.1" + } + }, + "node_modules/libqp": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/libqp/-/libqp-2.1.1.tgz", + "integrity": "sha512-0Wd+GPz1O134cP62YU2GTOPNA7Qgl09XwCqM5zpBv87ERCXdfDtyKXvV7c9U22yWJh44QZqBocFnXN11K96qow==", + "license": "MIT" + }, "node_modules/long": { "version": "5.3.2", "resolved": "https://registry.npmjs.org/long/-/long-5.3.2.tgz", @@ -129,6 +214,15 @@ "node": ">=6.0.0" } }, + "node_modules/on-exit-leak-free": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/on-exit-leak-free/-/on-exit-leak-free-2.1.2.tgz", + "integrity": "sha512-0eJJY6hXLGf1udHwfNftBqH+g73EU4B504nZeKpz1sYRKafAghwxEJunB2O7rDZkL4PGfsMVnTXZ2EjibbqcsA==", + "license": "MIT", + "engines": { + "node": ">=14.0.0" + } + }, "node_modules/pg": { "version": "8.23.1", "resolved": "https://registry.npmjs.org/pg/-/pg-8.23.1.tgz", @@ -218,6 +312,43 @@ "split2": "^4.1.0" } }, + "node_modules/pino": { + "version": "10.3.1", + "resolved": "https://registry.npmjs.org/pino/-/pino-10.3.1.tgz", + "integrity": "sha512-r34yH/GlQpKZbU1BvFFqOjhISRo1MNx1tWYsYvmj6KIRHSPMT2+yHOEb1SG6NMvRoHRF0a07kCOox/9yakl1vg==", + "license": "MIT", + "dependencies": { + "@pinojs/redact": "^0.4.0", + "atomic-sleep": "^1.0.0", + "on-exit-leak-free": "^2.1.0", + "pino-abstract-transport": "^3.0.0", + "pino-std-serializers": "^7.0.0", + "process-warning": "^5.0.0", + "quick-format-unescaped": "^4.0.3", + "real-require": "^0.2.0", + "safe-stable-stringify": "^2.3.1", + "sonic-boom": "^4.0.1", + "thread-stream": "^4.0.0" + }, + "bin": { + "pino": "bin.js" + } + }, + "node_modules/pino-abstract-transport": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/pino-abstract-transport/-/pino-abstract-transport-3.0.0.tgz", + "integrity": "sha512-wlfUczU+n7Hy/Ha5j9a/gZNy7We5+cXp8YL+X+PG8S0KXxw7n/JXA3c46Y0zQznIJ83URJiwy7Lh56WLokNuxg==", + "license": "MIT", + "dependencies": { + "split2": "^4.0.0" + } + }, + "node_modules/pino-std-serializers": { + "version": "7.1.0", + "resolved": "https://registry.npmjs.org/pino-std-serializers/-/pino-std-serializers-7.1.0.tgz", + "integrity": "sha512-BndPH67/JxGExRgiX1dX0w1FvZck5Wa4aal9198SrRhZjH3GxKQUKIBnYJTdj2HDN3UQAS06HlfcSbQj2OHmaw==", + "license": "MIT" + }, "node_modules/postgres-array": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/postgres-array/-/postgres-array-2.0.0.tgz", @@ -257,12 +388,85 @@ "node": ">=0.10.0" } }, + "node_modules/process-warning": { + "version": "5.1.1", + "resolved": "https://registry.npmjs.org/process-warning/-/process-warning-5.1.1.tgz", + "integrity": "sha512-oCkNVj4OKnKEcocVBcDfiIugN1/cE6rgfT3nCtzeqZPA8+rIxMaQ0xXzIkGP8Gj2qUaP1UR7uhJ1VD8lUCpzCg==", + "funding": [ + { + "type": "github", + "url": "https://github.com/sponsors/fastify" + }, + { + "type": "opencollective", + "url": "https://opencollective.com/fastify" + } + ], + "license": "MIT" + }, + "node_modules/quick-format-unescaped": { + "version": "4.0.4", + "resolved": "https://registry.npmjs.org/quick-format-unescaped/-/quick-format-unescaped-4.0.4.tgz", + "integrity": "sha512-tYC1Q1hgyRuHgloV/YXs2w15unPVh8qfu/qCTfhTYamaw7fyhumKa2yGpdSo87vY32rIclj+4fWYQXUMs9EHvg==", + "license": "MIT" + }, + "node_modules/real-require": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-0.2.0.tgz", + "integrity": "sha512-57frrGM/OCTLqLOAh0mhVA9VBMHd+9U7Zb2THMGdBUoZVOtGbJzjxsYGDJ3A9AYYCP4hn6y1TVbaOfzWtm5GFg==", + "license": "MIT", + "engines": { + "node": ">= 12.13.0" + } + }, + "node_modules/safe-stable-stringify": { + "version": "2.5.0", + "resolved": "https://registry.npmjs.org/safe-stable-stringify/-/safe-stable-stringify-2.5.0.tgz", + "integrity": "sha512-b3rppTKm9T+PsVCBEOUR46GWI7fdOs00VKZ1+9c1EWDaDMvjQc6tUwuFyIprgGgTcWoVHSKrU8H31ZHA2e0RHA==", + "license": "MIT", + "engines": { + "node": ">=10" + } + }, "node_modules/safer-buffer": { "version": "2.1.2", "resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz", "integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==", "license": "MIT" }, + "node_modules/smart-buffer": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/smart-buffer/-/smart-buffer-4.2.0.tgz", + "integrity": "sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg==", + "license": "MIT", + "engines": { + "node": ">= 6.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/socks": { + "version": "2.8.9", + "resolved": "https://registry.npmjs.org/socks/-/socks-2.8.9.tgz", + "integrity": "sha512-LJhUYUvItdQ0LkJTmPeaEObWXAqFyfmP85x0tch/ez9cahmhlBBLbIqDFnvBnUJGagb0JbIQrkBs1wJ+yRYpEw==", + "license": "MIT", + "dependencies": { + "ip-address": "^10.1.1", + "smart-buffer": "^4.2.0" + }, + "engines": { + "node": ">= 10.0.0", + "npm": ">= 3.0.0" + } + }, + "node_modules/sonic-boom": { + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/sonic-boom/-/sonic-boom-4.2.1.tgz", + "integrity": "sha512-w6AxtubXa2wTXAUsZMMWERrsIRAdrK0Sc+FUytWvYAhBJLyuI4llrMIC1DtlNSdI99EI86KZum2MMq3EAZlF9Q==", + "license": "MIT", + "dependencies": { + "atomic-sleep": "^1.0.0" + } + }, "node_modules/split2": { "version": "4.2.0", "resolved": "https://registry.npmjs.org/split2/-/split2-4.2.0.tgz", @@ -287,6 +491,24 @@ "url": "https://github.com/mysqljs/sql-escaper?sponsor=1" } }, + "node_modules/thread-stream": { + "version": "4.2.0", + "resolved": "https://registry.npmjs.org/thread-stream/-/thread-stream-4.2.0.tgz", + "integrity": "sha512-e2zZ96wSChazBsbENf/Pcm/4swHt2cEKQ92rhUjkL9GCKiTDJIaTBenjE/m9DXi0QBmTMDkFDdOomUy20A1tDQ==", + "license": "MIT", + "dependencies": { + "real-require": "^1.0.0" + }, + "engines": { + "node": ">=20" + } + }, + "node_modules/thread-stream/node_modules/real-require": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/real-require/-/real-require-1.0.0.tgz", + "integrity": "sha512-P4nbQYQfePJxRSmY+v/KINxVucm4NF3p3s7pJveMTtom52FR4YGltUQLB8idDXwDDWW+eYrWDFbuzUnjoWHF7g==", + "license": "MIT" + }, "node_modules/undici-types": { "version": "8.9.0", "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-8.9.0.tgz", diff --git a/package.json b/package.json index 47ca3ed..a1d1748 100644 --- a/package.json +++ b/package.json @@ -16,6 +16,7 @@ "hooks": "git config core.hooksPath .githooks" }, "dependencies": { + "imapflow": "^1.7.8", "mysql2": "^3.11.0", "nodemailer": "^6.9.15", "pg": "^8.13.0" diff --git a/public/app.css b/public/app.css index db2b237..e59788a 100644 --- a/public/app.css +++ b/public/app.css @@ -97,3 +97,5 @@ pre.md { white-space: pre-wrap; background: var(--locked); padding: 12px; border .toast.error { background: var(--err); color: #fff; } form.send { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--line); } @media (max-width: 640px) { .sys { order: 3; flex-basis: 100%; } } +.inbox { margin: 10px 0 4px; line-height: 1.9; } +.inbox:empty { display: none; } diff --git a/public/app.js b/public/app.js index 936872f..212824a 100644 --- a/public/app.js +++ b/public/app.js @@ -23,6 +23,12 @@ } const formData = (form) => Object.fromEntries(new FormData(form)); + const ago = (ts) => { + if (!ts) return 'jamais'; + const m = Math.round((Date.now() / 1000 - ts) / 60); + return m < 1 ? "à l'instant" : m < 60 ? `il y a ${m} min` : m < 1440 ? `il y a ${Math.round(m / 60)} h` : `il y a ${Math.round(m / 1440)} j`; + }; + const pct = (x) => `${Math.round(x * 100)} %`; const ACTIVE = ['queued', 'running']; const LABELS = { analyze: 'Analyse', prospect: 'Recherche', template: 'Modèle', send: 'Envoi', evolution: 'Évolutions' }; @@ -124,6 +130,19 @@ : `${s.stats.new} prospect(s) en attente · max ${s.sendMax} maintenant`; $('[data-count]', el).textContent = `(${s.stats.total || 0})`; + // Boîte de réception + test A/B + const ib = $('[data-inbox]', el); + const ab = s.ab.length > 1 + ? `
Test A/B : ${s.ab.map((v) => `${v.variant} ${v.replied}/${v.sent} réponses (${pct(v.rate)})`).join(' · ')}` : ''; + if (!s.hasImap) { + ib.innerHTML = `Boîte non connectée : configure l'IMAP (Configuration du projet) pour détecter les réponses.${ab}`; + } else { + const i = s.inbox || {}; + const head = i.lastError ? `Boîte en erreur : ${esc(i.lastError)}` : `Boîte vérifiée ${ago(i.lastOk)}`; + ib.innerHTML = `${head} · ${i.replies || 0} réponse(s) · ${i.bounces || 0} adresse(s) invalide(s) + ${ab}`; + } + state.set(id, st); schedule(el, running.length ? 4000 : 30_000); } @@ -177,6 +196,16 @@ } if (e.target.matches('[data-recap-refresh]')) loadRecap(e.target.closest('.project'), true); + + const inboxBtn = e.target.closest('[data-inbox-check]'); + if (inboxBtn) { + inboxBtn.disabled = true; + try { + const r = await api(`/api/projects/${inboxBtn.dataset.inboxCheck}/inbox/check`, {}); + toast(`Boîte lue : ${r.check.replies} nouvelle(s) réponse(s), ${r.check.bounces} rejet(s)`); + } catch (err) { toast(err.message, 'error'); } + refreshProject(inboxBtn.closest('.project')); + } }); // ---------- Formulaires ---------- @@ -218,6 +247,14 @@ break; } case 'smtp': data.pass ||= ''; await api(`/api/projects/${id}/smtp`, data); toast('SMTP enregistré'); form.pass.value = ''; break; + case 'imap': { + const r = await api(`/api/projects/${id}/imap`, data); + form.pass.value = ''; + if (r.disabled) toast('Détection des réponses désactivée'); + else if (r.ok) toast(`Boîte connectée : ${r.check.replies} réponse(s) trouvée(s)`); + else toast(r.error, 'error'); + break; + } case 'db': data.ssl = form.ssl.checked; await api(`/api/projects/${id}/db`, data); toast('Accès BDD enregistré'); form.password.value = ''; break; case 'delete': await api(`/api/projects/${id}/delete`, {}); location.reload(); break; } diff --git a/src/db.js b/src/db.js index b13d713..65bd7ae 100644 --- a/src/db.js +++ b/src/db.js @@ -88,6 +88,13 @@ export const MIGRATIONS = [ ALTER TABLE mail_log ADD COLUMN message_id TEXT; CREATE INDEX mail_log_msgid ON mail_log(message_id); `, + // 4 — détection des réponses via IMAP + ` + ALTER TABLE prospects ADD COLUMN replied_at INTEGER; + ALTER TABLE prospects ADD COLUMN reply_subject TEXT; + ALTER TABLE projects ADD COLUMN imap_enc TEXT; + ALTER TABLE projects ADD COLUMN inbox_json TEXT; -- état de la dernière lecture IMAP + `, ]; export function openDb(dataDir) { diff --git a/src/projects.js b/src/projects.js index 2458991..2d78a96 100644 --- a/src/projects.js +++ b/src/projects.js @@ -15,11 +15,14 @@ export function getProject(app, id, { secrets = false } = {}) { profile: parse(p.profile_json), profileCommit: p.profile_commit, profileAt: p.profile_at, target: parse(p.target_json), targetValidated: !!p.target_validated, dailyMailCap: p.daily_mail_cap, createdAt: p.created_at, - hasSmtp: !!p.smtp_enc, hasDb: !!p.db_enc, + hasSmtp: !!p.smtp_enc, hasDb: !!p.db_enc, hasImap: !!p.imap_enc, + inbox: parse(p.inbox_json), }; if (secrets) { out.smtp = decryptJson(app.cfg.secretKey, p.smtp_enc); out.dbCfg = decryptJson(app.cfg.secretKey, p.db_enc); + out.imapCfg = decryptJson(app.cfg.secretKey, p.imap_enc); + out.imap = imapCredentials(out.imapCfg, out.smtp); } return out; } @@ -35,7 +38,7 @@ export function createProject(app, { name, gitUrl }) { // Les secrets vides dans le formulaire = on garde l'ancien (le formulaire ne les réaffiche jamais) export function saveSecretConfig(app, id, column, incoming, secretField) { - if (!['smtp_enc', 'db_enc'].includes(column)) throw new Error('Colonne invalide'); + if (!['smtp_enc', 'db_enc', 'imap_enc'].includes(column)) throw new Error('Colonne invalide'); const current = decryptJson(app.cfg.secretKey, app.db.prepare(`SELECT ${column} c FROM projects WHERE id = ?`).get(id)?.c) || {}; const next = { ...current, ...incoming }; if (!incoming[secretField]) next[secretField] = current[secretField]; @@ -71,6 +74,16 @@ export function sentSince(db, since, projectId = null) { return (projectId == null ? db.prepare(sql).get(since) : db.prepare(sql).get(since, projectId)).n; } +// IMAP : utilisateur vide = mêmes identifiants que le SMTP du projet (cas le plus courant) +export function imapCredentials(imap, smtp) { + if (!imap?.host) return null; + const reuse = !imap.user; + const user = reuse ? smtp?.user : imap.user; + const pass = reuse ? smtp?.pass : imap.pass; + if (!user || !pass) return null; + return { host: imap.host, port: Number(imap.port || 993), user, pass, reuseSmtp: reuse }; +} + // ---------- Modèles de mail ---------- export const TEMPLATE_KINDS = ['initial', 'followup']; @@ -97,3 +110,12 @@ export function pickVariant(db, projectId, template) { for (const r of rows) count[r.variant] = r.n; return count.B < count.A ? 'B' : 'A'; } + +// Taux de réponse par objet (A/B) sur les premiers mails +export function abStats(db, projectId) { + const rows = db.prepare(`SELECT m.variant v, COUNT(*) sent, SUM(p.replied_at IS NOT NULL) replied + FROM mail_log m JOIN prospects p ON p.id = m.prospect_id + WHERE m.project_id = ? AND m.kind = 'initial' AND m.error IS NULL AND m.variant IS NOT NULL + GROUP BY m.variant ORDER BY m.variant`).all(projectId); + return rows.map((r) => ({ variant: r.v, sent: r.sent, replied: r.replied, rate: r.sent ? r.replied / r.sent : 0 })); +} diff --git a/src/routes.js b/src/routes.js index f312ec6..f25b1f8 100644 --- a/src/routes.js +++ b/src/routes.js @@ -8,9 +8,10 @@ import { validateGitUrl, removeRepo } from './services/git.js'; import { fetchRecap, clearRecapCache, validateSelect } from './services/recap.js'; import { allowedToSend, EMAIL_RE } from './services/mailer.js'; import { cpuTemp } from './services/thermal.js'; +import { checkInbox } from './services/inbox.js'; import { getProject, listProjects, createProject, saveSecretConfig, publicConfig, globalSmtp, - prospectStats, sentSince, repoDir, getTemplate, saveTemplate, + prospectStats, sentSince, repoDir, getTemplate, saveTemplate, abStats, } from './projects.js'; const lines = (s) => String(s || '').split('\n').map((x) => x.trim()).filter(Boolean).slice(0, 20); @@ -50,7 +51,7 @@ export function registerRoutes(router, app) { router.get('/', ({ res, session }) => { const projects = listProjects(app).map((p) => { const full = getProject(app, p.id, { secrets: true }); - return { project: p, smtp: publicConfig(full.smtp, 'pass'), dbCfg: publicConfig(full.dbCfg, 'password') }; + return { project: p, smtp: publicConfig(full.smtp, 'pass'), dbCfg: publicConfig(full.dbCfg, 'password'), imap: publicConfig(full.imapCfg, 'pass') }; }); html(res, dashboardPage({ email: session.email, projects, forgejoHost: getSetting(db, 'forgejo_host') })); }); @@ -134,6 +135,7 @@ export function registerRoutes(router, app) { json(res, { jobs, template: tpl, stats, sendMax, targetValidated: p.targetValidated, hasProfile: !!p.profile, hasSmtp: p.hasSmtp, + hasImap: p.hasImap, inbox: p.inbox, ab: abStats(db, p.id), }); }); @@ -202,6 +204,28 @@ export function registerRoutes(router, app) { json(res, { ok: true }); }); + // Boîte de réception : on enregistre puis on teste tout de suite la connexion + router.post('/api/projects/:id/imap', async ({ req, res, params }) => { + const p = getProject(app, pid(params)); + const b = await readBody(req); + const host = String(b.host || '').trim(); + if (!host) { + db.prepare('UPDATE projects SET imap_enc = NULL, inbox_json = NULL WHERE id = ?').run(p.id); + return json(res, { ok: true, disabled: true }); + } + saveSecretConfig(app, p.id, 'imap_enc', { + host, port: int(b.port, 1, 65535, 993), user: String(b.user || '').trim(), pass: b.pass || '', + }, 'pass'); + try { json(res, { ok: true, check: await checkInbox(app, p.id) }); } + catch (e) { json(res, { ok: false, error: e.message }); } + }); + + router.post('/api/projects/:id/inbox/check', async ({ res, params }) => { + const p = getProject(app, pid(params)); + try { json(res, { ok: true, check: await checkInbox(app, p.id) }); } + catch (e) { throw new HttpError(502, e.message); } + }); + router.post('/api/projects/:id/db', async ({ req, res, params }) => { const p = getProject(app, pid(params)); const b = await readBody(req); diff --git a/src/server.js b/src/server.js index 77ef6a8..08562ac 100644 --- a/src/server.js +++ b/src/server.js @@ -9,6 +9,7 @@ import { getSession, checkOrigin, purgeExpired } from './auth.js'; import { registerRoutes } from './routes.js'; import { Worker } from './services/jobs.js'; import { makeHandlers } from './handlers.js'; +import { Scheduler } from './services/scheduler.js'; import { layout } from './views.js'; const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..'); @@ -67,14 +68,17 @@ export function createApp(cfg, { db = openDb(cfg.dataDir), worker = true, create server.requestTimeout = 30_000; let w = null; + let scheduler = null; if (worker) { w = new Worker(db, makeHandlers(app), { thermalMax: cfg.thermalMax }); w.start(); + scheduler = new Scheduler(app); + scheduler.start(); } const purge = setInterval(() => purgeExpired(db), 3600_000); purge.unref(); - app.close = () => new Promise((r) => { w?.stop(); clearInterval(purge); server.close(() => { db.close(); r(); }); }); + app.close = () => new Promise((r) => { w?.stop(); scheduler?.stop(); clearInterval(purge); server.close(() => { db.close(); r(); }); }); app.server = server; return app; } diff --git a/src/services/inbox.js b/src/services/inbox.js new file mode 100644 index 0000000..c687861 --- /dev/null +++ b/src/services/inbox.js @@ -0,0 +1,167 @@ +// Lecture de la boîte de réception (IMAP) : rattache les réponses et les bounces aux prospects. +// Aucun token Claude : uniquement des en-têtes de mails. +import { now } from '../db.js'; +import { getProject } from '../projects.js'; + +// Webmails grand public : une réponse d'un autre @gmail.com ne dit rien sur l'entreprise +const GENERIC_DOMAINS = new Set([ + 'gmail.com', 'googlemail.com', 'yahoo.fr', 'yahoo.com', 'hotmail.fr', 'hotmail.com', 'outlook.fr', 'outlook.com', + 'live.fr', 'live.com', 'msn.com', 'icloud.com', 'me.com', 'orange.fr', 'wanadoo.fr', 'free.fr', 'sfr.fr', 'neuf.fr', + 'laposte.net', 'bbox.fr', 'gmx.fr', 'gmx.com', 'aol.com', 'protonmail.com', 'proton.me', +]); + +const MSGID_RE = /<[^<>\s@]+@[^<>\s]+>/g; +const ids = (s) => String(s || '').match(MSGID_RE) || []; +const HEADER_FIELDS = ['references', 'auto-submitted', 'x-autoreply', 'x-autorespond', 'precedence', 'content-type']; + +// En-têtes bruts (Buffer) → { nom: valeur } avec les lignes repliées dépliées +export function parseHeaders(raw) { + const out = {}; + const text = Buffer.isBuffer(raw) ? raw.toString('utf8') : String(raw || ''); + for (const line of text.replace(/\r?\n[ \t]+/g, ' ').split(/\r?\n/)) { + const i = line.indexOf(':'); + if (i > 0) out[line.slice(0, i).trim().toLowerCase()] = line.slice(i + 1).trim(); + } + return out; +} + +/** @returns {{type: 'reply'|'auto'|'bounce', from: string, ids: string[]}} */ +export function classify(msg) { + const h = msg.headers || {}; + const from = String(msg.from || '').toLowerCase(); + const subject = String(msg.subject || '').trim(); + const refs = [...new Set([...ids(msg.inReplyTo), ...ids(h.references)])]; + + const bounce = /^(mailer-daemon|postmaster)@/.test(from) + || /report-type=["']?delivery-status/i.test(h['content-type'] || '') + || /^(undeliver|delivery status notification|mail delivery failed|returned mail|non remis|échec de (la )?remise)/i.test(subject); + if (bounce) return { type: 'bounce', from, ids: [...new Set([...refs, ...ids(msg.body)])] }; + + const auto = (h['auto-submitted'] && !/^no$/i.test(h['auto-submitted'])) + || h['x-autoreply'] || h['x-autorespond'] + || /^(auto_reply|bulk|junk|list)$/i.test(h.precedence || '') + || /^(absence|out of office|automatic reply|réponse automatique|auto:|autoreply|abwesend)/i.test(subject); + if (auto) return { type: 'auto', from, ids: refs }; + + return { type: 'reply', from, ids: refs }; +} + +/** Applique une liste de messages aux prospects du projet. Idempotent. */ +export function applyMessages(db, projectId, messages, { at = now() } = {}) { + const res = { replies: 0, bounces: 0, ignored: 0 }; + const byMsgId = db.prepare('SELECT prospect_id FROM mail_log WHERE project_id = ? AND message_id = ? AND prospect_id IS NOT NULL LIMIT 1'); + const byEmail = db.prepare('SELECT id FROM prospects WHERE project_id = ? AND email = ? LIMIT 1'); + const byDomain = db.prepare("SELECT id FROM prospects WHERE project_id = ? AND status = 'sent' AND substr(email, instr(email, '@') + 1) = ?"); + const markReply = db.prepare("UPDATE prospects SET status = 'replied', replied_at = ?, reply_subject = ? WHERE id = ? AND status = 'sent'"); + const markBounce = db.prepare("UPDATE prospects SET status = 'bounced' WHERE id = ? AND status = 'sent'"); + const blacklist = db.prepare("INSERT OR IGNORE INTO blacklist(email, reason, created_at) SELECT email, 'bounce', ? FROM prospects WHERE id = ?"); + + const fromIds = (list) => { + for (const id of list) { const r = byMsgId.get(projectId, id); if (r) return r.prospect_id; } + return null; + }; + + for (const msg of messages) { + const c = classify(msg); + if (c.type === 'bounce') { + const pid = fromIds(c.ids); + if (pid && markBounce.run(pid).changes) { blacklist.run(at, pid); res.bounces++; } else res.ignored++; + continue; + } + if (c.type === 'auto') { res.ignored++; continue; } + + // Réponse : 1) fil de discussion, 2) même adresse, 3) même domaine pro (un seul prospect en attente dessus) + let pid = fromIds(c.ids) ?? byEmail.get(projectId, c.from)?.id ?? null; + if (!pid) { + const domain = c.from.split('@')[1]; + if (domain && !GENERIC_DOMAINS.has(domain)) { + const rows = byDomain.all(projectId, domain); + if (rows.length === 1) pid = rows[0].id; + } + } + if (pid && markReply.run(at, String(msg.subject || '').slice(0, 300), pid).changes) res.replies++; + else res.ignored++; + } + return res; +} + +/** Lit les nouveaux messages de INBOX depuis le dernier UID vu. */ +export async function fetchInbox(creds, state, { since, max = 500 }) { + const { ImapFlow } = await import('imapflow'); + const client = new ImapFlow({ + host: creds.host, port: creds.port, secure: creds.port === 993, + auth: { user: creds.user, pass: creds.pass }, logger: false, + socketTimeout: 60_000, connectionTimeout: 15_000, + }); + // Sans écouteur, une erreur réseau tardive (timeout après un échec d'auth) ferait planter tout le serveur + client.on('error', () => {}); + try { + await client.connect(); + } catch (e) { + client.close(); + throw e; + } + const out = { messages: [], uidValidity: null, lastUid: 0 }; + let lock; + try { + lock = await client.getMailboxLock('INBOX'); + const uidValidity = String(client.mailbox.uidValidity); + let lastUid = state?.uidValidity === uidValidity ? Number(state.lastUid || 0) : 0; + const found = lastUid + ? await client.search({ uid: `${lastUid + 1}:*` }, { uid: true }) + : await client.search({ since }, { uid: true }); + // "N:*" renvoie toujours au moins le dernier message, même déjà vu + const uids = (found || []).filter((u) => u > lastUid).sort((a, b) => a - b).slice(-max); + + if (uids.length) { + // Pas d'autre commande IMAP possible pendant cette boucle + for await (const m of client.fetch(uids.join(','), { uid: true, envelope: true, headers: HEADER_FIELDS }, { uid: true })) { + out.messages.push({ + uid: m.uid, + from: m.envelope?.from?.[0]?.address || '', + subject: m.envelope?.subject || '', + inReplyTo: m.envelope?.inReplyTo || '', + headers: parseHeaders(m.headers), + }); + } + // Les bounces citent notre Message-ID dans le corps : on lit seulement leur début + for (const msg of out.messages) { + if (classify(msg).type !== 'bounce') continue; + const full = await client.fetchOne(String(msg.uid), { source: { maxLength: 100_000 } }, { uid: true }); + msg.body = full?.source ? full.source.toString('utf8') : ''; + } + lastUid = Math.max(lastUid, ...uids); + } + out.uidValidity = uidValidity; + out.lastUid = lastUid; + } finally { + lock?.release(); + await client.logout().catch(() => {}); + } + return out; +} + +/** Vérifie la boîte d'un projet et mémorise l'état (dernier UID, erreurs, compteurs). */ +export async function checkInbox(app, projectId) { + const { db } = app; + const project = getProject(app, projectId, { secrets: true }); + if (!project.imap) throw new Error('Boîte IMAP non configurée'); + const state = project.inbox || {}; + const firstSent = db.prepare('SELECT MIN(sent_at) t FROM mail_log WHERE project_id = ?').get(project.id).t; + const since = new Date(((firstSent || now()) - 86400) * 1000); + const at = now(); + const save = (s) => db.prepare('UPDATE projects SET inbox_json = ? WHERE id = ?').run(JSON.stringify(s), project.id); + try { + const r = await (app.fetchInbox || fetchInbox)(project.imap, state, { since }); + const res = applyMessages(db, project.id, r.messages, { at }); + save({ + uidValidity: r.uidValidity, lastUid: r.lastUid, lastCheck: at, lastOk: at, lastError: null, + replies: (state.replies || 0) + res.replies, bounces: (state.bounces || 0) + res.bounces, + }); + return res; + } catch (e) { + const msg = String(e.responseText || e.message || e).slice(0, 300); + save({ ...state, lastCheck: at, lastError: msg }); + throw new Error(`IMAP : ${msg}`); + } +} diff --git a/src/services/scheduler.js b/src/services/scheduler.js new file mode 100644 index 0000000..4e22bd0 --- /dev/null +++ b/src/services/scheduler.js @@ -0,0 +1,33 @@ +// Tâches de fond légères (sans Claude) : lecture des boîtes IMAP toutes les 15 min. +import { checkInbox } from './inbox.js'; + +export class Scheduler { + constructor(app, { everyMs = 15 * 60_000, log = console } = {}) { + this.app = app; + this.everyMs = everyMs; + this.log = log; + this.running = false; + } + + start() { + this.timer = setInterval(() => this.tick(), this.everyMs); + this.timer.unref(); + // Premier passage peu après le démarrage + this.first = setTimeout(() => this.tick(), 60_000); + this.first.unref(); + } + + stop() { clearInterval(this.timer); clearTimeout(this.first); } + + async tick() { + if (this.running) return; + this.running = true; + try { + const projects = this.app.db.prepare('SELECT id FROM projects WHERE imap_enc IS NOT NULL').all(); + for (const { id } of projects) { + try { await checkInbox(this.app, id); } + catch (e) { this.log.error(`[inbox ${id}]`, e.message); } + } + } finally { this.running = false; } + } +} diff --git a/src/views.js b/src/views.js index ec4f9fa..fe77236 100644 --- a/src/views.js +++ b/src/views.js @@ -56,7 +56,7 @@ function targetForm(p) { `; } -function configForms(p, smtp, dbCfg) { +function configForms(p, smtp, dbCfg, imap) { return `
Configuration du projet

SMTP d'envoi

@@ -71,6 +71,17 @@ function configForms(p, smtp, dbCfg) {
+
+

Boîte de réception (IMAP)

+

Sert à détecter les réponses et les adresses invalides. Utilisateur vide = mêmes identifiants que le SMTP. Hôte vide = désactivé.

+
+ + + + +
+ +

Base de données (récapitulatif)

Utilise un compte en lecture seule. Chaque requête doit renvoyer un seul nombre.

@@ -94,7 +105,7 @@ function configForms(p, smtp, dbCfg) {
`; } -function projectItem(p, smtp, dbCfg) { +function projectItem(p, smtp, dbCfg, imap) { const profile = p.profile; return `
${esc(p.name)} @@ -146,6 +157,7 @@ function projectItem(p, smtp, dbCfg) {
+

Prospects
@@ -169,7 +181,7 @@ function projectItem(p, smtp, dbCfg) {

Chargement…

- ${configForms(p, smtp, dbCfg)} + ${configForms(p, smtp, dbCfg, imap)}
`; } @@ -190,7 +202,7 @@ export function dashboardPage({ email, projects, forgejoHost }) {
-${projects.length ? projects.map((x) => projectItem(x.project, x.smtp, x.dbCfg)).join('\n') : '

Aucun projet pour l\'instant.

'} +${projects.length ? projects.map((x) => projectItem(x.project, x.smtp, x.dbCfg, x.imap)).join('\n') : '

Aucun projet pour l\'instant.

'}
`, }); } diff --git a/test/inbox.live.test.js b/test/inbox.live.test.js new file mode 100644 index 0000000..37d5b7f --- /dev/null +++ b/test/inbox.live.test.js @@ -0,0 +1,37 @@ +// Test de bout en bout contre un vrai serveur IMAP. Ignoré par défaut. +// IMAP_TEST=host:port:user:pass npm test (la boîte doit contenir les 4 mails de test, cf. README) +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; +import { openDb, now } from '../src/db.js'; +import { checkInbox } from '../src/services/inbox.js'; +import { createProject, saveSecretConfig, getProject } from '../src/projects.js'; + +const live = process.env.IMAP_TEST; + +test('checkInbox sur un vrai serveur IMAP', { skip: !live && 'IMAP_TEST non défini' }, async () => { + const [host, port, user, pass] = live.split(':'); + const db = openDb(':memory:'); + const app = { db, cfg: { secretKey: randomBytes(32) } }; + const id = createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' }); + saveSecretConfig(app, id, 'smtp_enc', { host: 'smtp.x', user, pass, fromEmail: user }, 'pass'); + saveSecretConfig(app, id, 'imap_enc', { host, port: Number(port), user: '', pass: '' }, 'pass'); + const add = (email, msgId) => { + const pid = Number(db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'X', ?, 'sent', ?, ?)") + .run(id, email, now() - 86400 * 30, now()).lastInsertRowid); + db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, message_id) VALUES(?, ?, ?, ?, 'initial', ?)") + .run(id, pid, email, now() - 86400 * 30, msgId); + return pid; + }; + const fournil = add('contact@fournil.fr', ''); + const zen = add('hello@zen.fr', ''); + const ferme = add('contact@ferme.fr', ''); + + assert.deepEqual(await checkInbox(app, id), { replies: 1, bounces: 1, ignored: 2 }); + const st = (pid) => db.prepare('SELECT status FROM prospects WHERE id = ?').get(pid).status; + assert.equal(st(fournil), 'replied'); + assert.equal(st(zen), 'sent', 'une absence n\'est pas une réponse'); + assert.equal(st(ferme), 'bounced'); + assert.deepEqual(await checkInbox(app, id), { replies: 0, bounces: 0, ignored: 0 }, 'rien de relu'); + assert.equal(getProject(app, id).inbox.lastUid, 4); +}); diff --git a/test/inbox.test.js b/test/inbox.test.js new file mode 100644 index 0000000..503080d --- /dev/null +++ b/test/inbox.test.js @@ -0,0 +1,127 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; +import { openDb, now } from '../src/db.js'; +import { parseHeaders, classify, applyMessages, checkInbox } from '../src/services/inbox.js'; +import { createProject, saveSecretConfig, getProject, imapCredentials } from '../src/projects.js'; + +function setup() { + const db = openDb(':memory:'); + const app = { db, cfg: { secretKey: randomBytes(32) } }; + const id = createProject(app, { name: 'P', gitUrl: 'https://git.x/T/P.git' }); + const add = (company, email, msgId, status = 'sent') => { + const r = db.prepare('INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, ?, ?, ?, ?, ?)') + .run(id, company, email, status, now(), now()); + const pid = Number(r.lastInsertRowid); + if (msgId) { + db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, kind, message_id) VALUES(?, ?, ?, ?, 'initial', ?)") + .run(id, pid, email, now(), msgId); + } + return pid; + }; + const status = (pid) => db.prepare('SELECT status, replied_at, reply_subject FROM prospects WHERE id = ?').get(pid); + return { db, app, id, add, status }; +} + +test('parseHeaders déplie les en-têtes multi-lignes', () => { + const h = parseHeaders(Buffer.from('References: \r\n \r\nAuto-Submitted: auto-replied\r\n\r\n')); + assert.equal(h.references, ' '); + assert.equal(h['auto-submitted'], 'auto-replied'); +}); + +test('classify : réponse, réponse automatique, bounce', () => { + assert.equal(classify({ from: 'Jean@Fournil.fr', subject: 'Re: Idée', inReplyTo: '<1@codebzh.fr>' }).type, 'reply'); + assert.deepEqual(classify({ from: 'a@b.fr', inReplyTo: '<1@x.fr>', headers: { references: '<0@x.fr> <1@x.fr>' } }).ids, ['<1@x.fr>', '<0@x.fr>']); + assert.equal(classify({ from: 'a@b.fr', subject: 'Absence du 12 au 20', headers: {} }).type, 'auto'); + assert.equal(classify({ from: 'a@b.fr', subject: 'Re: x', headers: { 'auto-submitted': 'auto-replied' } }).type, 'auto'); + assert.equal(classify({ from: 'a@b.fr', subject: 'Re: x', headers: { 'auto-submitted': 'no' } }).type, 'reply'); + assert.equal(classify({ from: 'a@b.fr', subject: 'Out of Office: Re: x', headers: {} }).type, 'auto'); + const b = classify({ from: 'MAILER-DAEMON@mx.orange.fr', subject: 'Undelivered Mail', body: 'Original-Message-ID: <42@codebzh.fr>' }); + assert.equal(b.type, 'bounce'); + assert.deepEqual(b.ids, ['<42@codebzh.fr>']); + assert.equal(classify({ from: 'x@y.fr', subject: 'Rapport', headers: { 'content-type': 'multipart/report; report-type=delivery-status' } }).type, 'bounce'); +}); + +test('réponse rattachée par le fil (In-Reply-To), même depuis une autre adresse', () => { + const s = setup(); + const p = s.add('Fournil', 'contact@fournil.fr', ''); + const r = applyMessages(s.db, s.id, [{ from: 'jean.dupont@gmail.com', subject: 'Re: Une idée', inReplyTo: '' }]); + assert.deepEqual(r, { replies: 1, bounces: 0, ignored: 0 }); + assert.equal(s.status(p).status, 'replied'); + assert.equal(s.status(p).reply_subject, 'Re: Une idée'); + assert.ok(s.status(p).replied_at > 0); +}); + +test('réponse rattachée par adresse puis par domaine pro', () => { + const s = setup(); + const byMail = s.add('Zen', 'hello@zen.fr', null); + const byDomain = s.add('Atelier', 'contact@atelier-bois.fr', null); + const r = applyMessages(s.db, s.id, [ + { from: 'Hello@Zen.fr', subject: 'Intéressé' }, + { from: 'marc@atelier-bois.fr', subject: 'Re: votre message' }, + ]); + assert.equal(r.replies, 2); + assert.equal(s.status(byMail).status, 'replied'); + assert.equal(s.status(byDomain).status, 'replied'); +}); + +test('pas de faux positif : webmail générique, domaine ambigu, réponse auto, statut déjà traité', () => { + const s = setup(); + const g = s.add('Perso', 'boulanger.rennes@gmail.com', null); + const a1 = s.add('Groupe A', 'rennes@groupe.fr', null); + const a2 = s.add('Groupe B', 'nantes@groupe.fr', null); + const client = s.add('Déjà client', 'boss@client.fr', null, 'client'); + const r = applyMessages(s.db, s.id, [ + { from: 'autre@gmail.com', subject: 'Re: ?' }, // gmail : on ne devine pas + { from: 'direction@groupe.fr', subject: 'Re: ?' }, // 2 prospects sur ce domaine + { from: 'boulanger.rennes@gmail.com', subject: 'Absence', headers: {} }, + { from: 'boss@client.fr', subject: 'Merci' }, // déjà client : on ne rétrograde pas + { from: 'inconnu@ailleurs.fr', subject: 'Spam' }, + ]); + assert.deepEqual(r, { replies: 0, bounces: 0, ignored: 5 }); + for (const pid of [g, a1, a2]) assert.equal(s.status(pid).status, 'sent'); + assert.equal(s.status(client).status, 'client'); +}); + +test('bounce : prospect rejeté + liste d\'opposition, et traitement idempotent', () => { + const s = setup(); + const p = s.add('Fermé', 'contact@ferme-definitivement.fr', ''); + const bounce = { from: 'mailer-daemon@mx.ovh.net', subject: 'Mail delivery failed', body: 'Message-ID: \n550 user unknown' }; + assert.equal(applyMessages(s.db, s.id, [bounce]).bounces, 1); + assert.equal(s.status(p).status, 'bounced'); + assert.equal(s.db.prepare("SELECT reason FROM blacklist WHERE email = 'contact@ferme-definitivement.fr'").get().reason, 'bounce'); + assert.deepEqual(applyMessages(s.db, s.id, [bounce]), { replies: 0, bounces: 0, ignored: 1 }); +}); + +test('imapCredentials : utilisateur vide = identifiants SMTP', () => { + const smtp = { user: 'tony@x.fr', pass: 'smtp' }; + assert.deepEqual(imapCredentials({ host: 'imap.x.fr' }, smtp), { host: 'imap.x.fr', port: 993, user: 'tony@x.fr', pass: 'smtp', reuseSmtp: true }); + assert.equal(imapCredentials({ host: 'imap.x.fr', user: 'autre', pass: 'p', port: '143' }, smtp).port, 143); + assert.equal(imapCredentials({ host: '' }, smtp), null); + assert.equal(imapCredentials({ host: 'imap.x.fr' }, null), null); +}); + +test('checkInbox : reprend au dernier UID, mémorise l\'état et les erreurs', async () => { + const s = setup(); + saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'smtp.x', user: 'u', pass: 'p', fromEmail: 'a@x.fr' }, 'pass'); + saveSecretConfig(s.app, s.id, 'imap_enc', { host: 'imap.x', port: 993, user: '', pass: '' }, 'pass'); + const p = s.add('Fournil', 'contact@fournil.fr', ''); + const calls = []; + s.app.fetchInbox = async (creds, state) => { + calls.push({ creds, state }); + if (calls.length === 3) throw Object.assign(new Error('x'), { responseText: 'AUTHENTICATIONFAILED' }); + return calls.length === 1 + ? { uidValidity: '7', lastUid: 12, messages: [{ uid: 12, from: 'contact@fournil.fr', subject: 'Re: idée' }] } + : { uidValidity: '7', lastUid: 12, messages: [] }; + }; + assert.deepEqual(await checkInbox(s.app, s.id), { replies: 1, bounces: 0, ignored: 0 }); + assert.equal(calls[0].creds.user, 'u', 'identifiants SMTP réutilisés'); + await checkInbox(s.app, s.id); + assert.deepEqual(calls[1].state && { v: calls[1].state.uidValidity, u: calls[1].state.lastUid }, { v: '7', u: 12 }); + await assert.rejects(checkInbox(s.app, s.id), /AUTHENTICATIONFAILED/); + const inbox = getProject(s.app, s.id).inbox; + assert.equal(inbox.lastError, 'AUTHENTICATIONFAILED'); + assert.equal(inbox.replies, 1); + assert.equal(inbox.lastUid, 12, 'le dernier UID est conservé après une erreur'); + assert.equal(s.status(p).status, 'replied'); +});