feat(abuse): pause d'envoi quand trop de mails sont rejetés
Au-delà de 10 % de rejets sur au moins 50 prospects contactés (fenêtre de 30 jours), le compte est mis en pause d'envoi : refus explicite avec message à la mise en file et à l'exécution, bandeau sur le tableau de bord, ligne au journal d'audit, journal du serveur et Discord de l'administrateur. Rétablissement depuis le back-office (le décompte repart des envois suivants). Désinscription et liste d'opposition inchangées. Les relances automatiques passent leur tour sans bloquer les autres comptes.
This commit is contained in:
parent
d2c424811d
commit
c9066e9e8d
12 changed files with 371 additions and 40 deletions
47
src/admin.js
47
src/admin.js
|
|
@ -1,6 +1,8 @@
|
|||
// Back-office : liste des comptes, suspension, plan, suppression, journal d'audit. RIEN des données métier d'un compte
|
||||
// (prospects, mails, notes, projets) n'est lu ici : uniquement l'identité du compte, sa liaison (mode, sans secret) et des compteurs.
|
||||
import { now } from './db.js';
|
||||
import { logAudit } from './audit.js';
|
||||
import { sendPause, resumeSending } from './services/abuse.js';
|
||||
import { HttpError } from './http.js';
|
||||
import { destroyUserSessions } from './auth.js';
|
||||
import { getUser, deleteUser, normalizeEmail } from './users.js';
|
||||
|
|
@ -8,41 +10,10 @@ import { ADMIN_PAGE_SIZE, PAID_PLANS } from './limits.js';
|
|||
import { usageOf, limitsFor } from './services/plans.js';
|
||||
import { MODE_LABELS } from './claudelink.js';
|
||||
|
||||
/** « jean.dupont@exemple.fr » → « j***@exemple.fr » : l'identification suffit, l'adresse complète n'est pas gardée dans le journal. */
|
||||
export function maskEmail(email) {
|
||||
const [local = '', domain = ''] = String(email || '').split('@');
|
||||
return `${local.slice(0, 1)}***${domain ? `@${domain}` : ''}`;
|
||||
}
|
||||
|
||||
const ACTIONS = {
|
||||
suspend: 'Compte suspendu', reactivate: 'Compte réactivé', plan_free: 'Plan gratuit attribué', plan_pro: 'Plan pro attribué',
|
||||
delete: 'Compte supprimé', resume_send: 'Envois rétablis', abuse_pause: 'Envois mis en pause (rejets)',
|
||||
inactive_warning: 'Avertissement d\'inactivité', inactive_delete: 'Compte inactif supprimé',
|
||||
};
|
||||
export const ACTION_LABELS = ACTIONS;
|
||||
|
||||
/** Ajoute une ligne au journal. `admin` = { id, email } de l'administrateur, ou null pour une décision du système. */
|
||||
export async function logAudit(db, { admin = null, action, target = null, detail = null, at = now() }) {
|
||||
if (!ACTIONS[action]) throw new Error(`Action d'audit inconnue : ${action}`);
|
||||
await db.prepare('INSERT INTO admin_audit(admin_id, admin_label, action, target_id, target_label, detail, created_at) VALUES(?, ?, ?, ?, ?, ?, ?)')
|
||||
.run(admin?.id ?? null, admin ? admin.email : 'système', action, target?.id ?? null, target ? maskEmail(target.email) : null, detail ? String(detail).slice(0, 500) : null, at);
|
||||
}
|
||||
|
||||
export async function recentAudit(db, limit = 50) {
|
||||
return (await db.prepare('SELECT * FROM admin_audit ORDER BY id DESC LIMIT ?').all(limit)).map((r) => ({
|
||||
id: r.id, at: r.created_at, admin: r.admin_label, action: r.action, label: ACTIONS[r.action] || r.action,
|
||||
target: r.target_label, targetId: r.target_id, detail: r.detail,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Nettoyage du journal ancien (planificateur). */
|
||||
export async function purgeAudit(db, months, at = now()) {
|
||||
const d = new Date(at * 1000); d.setUTCMonth(d.getUTCMonth() - months);
|
||||
await db.prepare('DELETE FROM admin_audit WHERE created_at < ?').run(Math.floor(d.getTime() / 1000));
|
||||
}
|
||||
|
||||
const like = (q) => `%${String(q).replace(/[!%_]/g, '!$&')}%`;
|
||||
|
||||
export { maskEmail, ACTION_LABELS, logAudit, recentAudit, purgeAudit } from './audit.js';
|
||||
|
||||
/** Page de comptes : identité, liaison (mode seulement), usage du mois. Aucune donnée métier. */
|
||||
export async function listAccounts(db, { page = 1, q = '', at = now() } = {}) {
|
||||
const where = q ? "WHERE email LIKE ? ESCAPE '!'" : '';
|
||||
|
|
@ -61,7 +32,7 @@ export async function listAccounts(db, { page = 1, q = '', at = now() } = {}) {
|
|||
accounts.push({
|
||||
id: Number(r.id), email: r.email, provider: r.provider, status: r.status, isAdmin: !!r.is_admin, plan: r.plan,
|
||||
createdAt: r.created_at, lastLoginAt: r.last_login_at, link,
|
||||
usage: { ...usage, limits: limitsFor(user) },
|
||||
usage: { ...usage, limits: limitsFor(user) }, sendPause: await sendPause(db, r.id),
|
||||
});
|
||||
}
|
||||
return { accounts, total, page: p, pages };
|
||||
|
|
@ -78,7 +49,7 @@ function assertManageable(actor, target, verb) {
|
|||
* Exécute une action d'administration, la journalise et renvoie un message pour l'écran.
|
||||
* @param {{db, worker?}} app
|
||||
* @param {{id: number, email: string}} actor administrateur connecté
|
||||
* @param {'suspend'|'reactivate'|'plan'|'delete'} action
|
||||
* @param {'suspend'|'reactivate'|'plan'|'delete'|'resume_send'} action
|
||||
*/
|
||||
export async function adminAction(app, actor, action, targetId, { plan, confirm } = {}) {
|
||||
const { db } = app;
|
||||
|
|
@ -112,5 +83,11 @@ export async function adminAction(app, actor, action, targetId, { plan, confirm
|
|||
await deleteUser(app, target.id);
|
||||
return 'Compte supprimé avec toutes ses données.';
|
||||
}
|
||||
if (action === 'resume_send') {
|
||||
if (!target) throw new HttpError(404, 'Compte introuvable');
|
||||
await resumeSending(db, target.id);
|
||||
await logAudit(db, { admin: actor, action: 'resume_send', target });
|
||||
return `Envois rétablis pour ${target.email}`;
|
||||
}
|
||||
throw new HttpError(400, 'Action inconnue');
|
||||
}
|
||||
|
|
|
|||
36
src/audit.js
Normal file
36
src/audit.js
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
// Journal d'audit : actions d'administration et décisions automatiques (pause d'envoi, comptes inactifs).
|
||||
// Les adresses y sont masquées ; aucune route ne modifie ni n'efface une ligne (seule la purge ancienne en retire).
|
||||
import { now } from './db.js';
|
||||
|
||||
/** « jean.dupont@exemple.fr » → « j***@exemple.fr » : l'identification suffit, l'adresse complète n'est pas gardée dans le journal. */
|
||||
export function maskEmail(email) {
|
||||
const [local = '', domain = ''] = String(email || '').split('@');
|
||||
return `${local.slice(0, 1)}***${domain ? `@${domain}` : ''}`;
|
||||
}
|
||||
|
||||
const ACTIONS = {
|
||||
suspend: 'Compte suspendu', reactivate: 'Compte réactivé', plan_free: 'Plan gratuit attribué', plan_pro: 'Plan pro attribué',
|
||||
delete: 'Compte supprimé', resume_send: 'Envois rétablis', abuse_pause: 'Envois mis en pause (rejets)',
|
||||
inactive_warning: 'Avertissement d\'inactivité', inactive_delete: 'Compte inactif supprimé',
|
||||
};
|
||||
export const ACTION_LABELS = ACTIONS;
|
||||
|
||||
/** Ajoute une ligne au journal. `admin` = { id, email } de l'administrateur, ou null pour une décision du système. */
|
||||
export async function logAudit(db, { admin = null, action, target = null, detail = null, at = now() }) {
|
||||
if (!ACTIONS[action]) throw new Error(`Action d'audit inconnue : ${action}`);
|
||||
await db.prepare('INSERT INTO admin_audit(admin_id, admin_label, action, target_id, target_label, detail, created_at) VALUES(?, ?, ?, ?, ?, ?, ?)')
|
||||
.run(admin?.id ?? null, admin ? admin.email : 'système', action, target?.id ?? null, target ? maskEmail(target.email) : null, detail ? String(detail).slice(0, 500) : null, at);
|
||||
}
|
||||
|
||||
export async function recentAudit(db, limit = 50) {
|
||||
return (await db.prepare('SELECT * FROM admin_audit ORDER BY id DESC LIMIT ?').all(limit)).map((r) => ({
|
||||
id: r.id, at: r.created_at, admin: r.admin_label, action: r.action, label: ACTIONS[r.action] || r.action,
|
||||
target: r.target_label, targetId: r.target_id, detail: r.detail,
|
||||
}));
|
||||
}
|
||||
|
||||
/** Nettoyage du journal ancien (planificateur). */
|
||||
export async function purgeAudit(db, months, at = now()) {
|
||||
const d = new Date(at * 1000); d.setUTCMonth(d.getUTCMonth() - months);
|
||||
await db.prepare('DELETE FROM admin_audit WHERE created_at < ?').run(Math.floor(d.getTime() / 1000));
|
||||
}
|
||||
|
|
@ -14,6 +14,7 @@ import { notify } from './services/notify.js';
|
|||
import { quotaFor, recordUsage, planLimitMessage } from './services/plans.js';
|
||||
import { getUser } from './users.js';
|
||||
import { pinSmtp, pinGit } from './netguard.js';
|
||||
import { sendPause, pauseMessage, evaluateSending } from './services/abuse.js';
|
||||
import { evolutionMail } from './services/mailhtml.js';
|
||||
import { getProject, repoDir, forgejoToken, globalSmtp, sentSince, getTemplate, saveTemplate, pickVariant } from './projects.js';
|
||||
|
||||
|
|
@ -99,6 +100,8 @@ export function makeHandlers(app) {
|
|||
// Une relance mise en file à 17h55 ne doit pas partir à 19h si le worker était occupé
|
||||
if (kind === 'followup' && !inHours()) return { sent: 0, failed: 0, total: 0, postponed: true };
|
||||
const userId = ctx.job.user_id;
|
||||
const pause = await sendPause(db, userId);
|
||||
if (pause) throw new Error(pauseMessage(pause)); // la désinscription et la liste d'opposition restent appliquées ci-dessous
|
||||
const project = await getProject(app, ctx.job.project_id, { userId, secrets: true });
|
||||
const template = await getTemplate(db, project.id, kind, { validatedOnly: true });
|
||||
if (!template) throw new Error(kind === 'followup' ? 'Modèle de relance non validé' : 'Modèle de mail non validé');
|
||||
|
|
@ -178,6 +181,7 @@ export function makeHandlers(app) {
|
|||
if (sent + failed < n) await sleep(minDelay + Math.random() * (maxDelay - minDelay), ctx.signal).catch(() => {});
|
||||
}
|
||||
transport.close();
|
||||
await evaluateSending(app, userId); // trop de rejets : le compte passe en pause d'envoi
|
||||
return { sent, failed, total: n };
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import { dashboardPage, settingsPage, unsubPage, accountPage, linkPage } from '.
|
|||
import { enqueue, latestJobs, cancelJob, usageSummary } from './services/jobs.js';
|
||||
import { validateGitUrl, removeRepo } from './services/git.js';
|
||||
import { fetchRecap, clearRecapCache, validateSelect } from './services/recap.js';
|
||||
import { sendPause, pauseMessage as pauseMessageOf } from './services/abuse.js';
|
||||
import { guardTarget, pinDb, pinGit, checkForgejoHost } from './netguard.js';
|
||||
import { allowedToSend, EMAIL_RE } from './services/mailer.js';
|
||||
import { cpuTemp } from './services/thermal.js';
|
||||
|
|
@ -118,6 +119,7 @@ export function registerRoutes(router, app) {
|
|||
}
|
||||
html(res, dashboardPage({
|
||||
email: session.email, projects, forgejoHost: await getSetting(db, userId, 'forgejo_host'), usage: await usageView(db, await getUser(db, userId)),
|
||||
pauseMessage: await sendPause(db, userId).then((p) => (p ? pauseMessageOf(p) : null)),
|
||||
}));
|
||||
});
|
||||
|
||||
|
|
|
|||
74
src/services/abuse.js
Normal file
74
src/services/abuse.js
Normal file
|
|
@ -0,0 +1,74 @@
|
|||
// Détection d'abus à l'envoi : un compte dont trop de mails sont rejetés (bounces) est mis en pause d'envoi, l'administrateur
|
||||
// est prévenu (journal d'audit, journal du serveur, Discord s'il est configuré) et l'utilisateur voit un message clair.
|
||||
// Le désabonnement et la liste d'opposition globale restent appliqués à chaque envoi, pause ou non (voir handlers.js).
|
||||
// Seuils : src/limits.js (ABUSE).
|
||||
import { now, getSetting, setSetting } from '../db.js';
|
||||
import { ABUSE } from '../limits.js';
|
||||
import { logAudit } from '../audit.js';
|
||||
import { notify } from './notify.js';
|
||||
import { CONTACT_EMAIL } from '../site/layout.js';
|
||||
|
||||
/**
|
||||
* Prospects contactés depuis `since` et, parmi eux, ceux dont le mail a été rejeté (adresse invalide). Un prospect compte une
|
||||
* fois, même relancé. Sont comptés les envois réussis et les rejets définitifs (5xx) ; une panne passagère de SMTP ne pèse pas.
|
||||
*/
|
||||
export async function bounceStats(db, userId, { since }) {
|
||||
const r = await db.prepare(`SELECT COUNT(DISTINCT m.prospect_id) sent,
|
||||
COUNT(DISTINCT CASE WHEN x.status = 'bounced' THEN m.prospect_id END) bounced
|
||||
FROM mail_log m JOIN projects p ON p.id = m.project_id JOIN prospects x ON x.id = m.prospect_id
|
||||
WHERE p.user_id = ? AND m.sent_at >= ? AND (m.error IS NULL OR x.status = 'bounced')`).get(Number(userId), since);
|
||||
const sent = Number(r.sent), bounced = Number(r.bounced);
|
||||
return { sent, bounced, rate: sent ? bounced / sent : 0 };
|
||||
}
|
||||
|
||||
/** Pause d'envoi en cours ({ at, sent, bounced, rate }) ou null. */
|
||||
export async function sendPause(db, userId) {
|
||||
const raw = await getSetting(db, userId, 'send_pause_json');
|
||||
try { return raw ? JSON.parse(raw) : null; } catch { return null; }
|
||||
}
|
||||
|
||||
/** Message affiché à l'utilisateur : pourquoi, que vérifier, comment reprendre. */
|
||||
export function pauseMessage(p) {
|
||||
const pct = Math.round((p.rate || 0) * 100);
|
||||
return `Tes envois sont en pause : ${p.bounced} adresse(s) sur ${p.sent} contactées ont été rejetées (${pct} %, seuil de ${Math.round(ABUSE.maxBounceRate * 100)} %). `
|
||||
+ `Vérifie ta liste de prospects et la configuration de ton domaine d'envoi (SPF, DKIM), puis écris à ${CONTACT_EMAIL} pour reprendre. `
|
||||
+ "Le lien de désinscription et la liste d'opposition restent appliqués.";
|
||||
}
|
||||
|
||||
/**
|
||||
* Évalue la santé des envois d'un compte ; au-delà du seuil (et d'un minimum d'envois), met le compte en pause.
|
||||
* Appelée après chaque lot d'envois et chaque lecture de la boîte (c'est là qu'arrivent les rejets).
|
||||
* Après un rétablissement par l'administrateur, seuls les envois suivants sont comptés.
|
||||
* @returns {Promise<object|null>} la pause (existante ou nouvelle), ou null
|
||||
*/
|
||||
export async function evaluateSending(app, userId, { at = now() } = {}) {
|
||||
const { db } = app;
|
||||
const existing = await sendPause(db, userId);
|
||||
if (existing) return existing;
|
||||
const resumed = Number(await getSetting(db, userId, 'send_resumed_at', '0')) || 0;
|
||||
const since = Math.max(at - ABUSE.windowDays * 86400, resumed);
|
||||
const st = await bounceStats(db, userId, { since });
|
||||
if (st.sent < ABUSE.minSent || st.rate <= ABUSE.maxBounceRate) return null;
|
||||
|
||||
const pause = { at, sent: st.sent, bounced: st.bounced, rate: Math.round(st.rate * 1000) / 1000 };
|
||||
await setSetting(db, userId, 'send_pause_json', JSON.stringify(pause));
|
||||
const user = await db.prepare('SELECT id, email FROM users WHERE id = ?').get(Number(userId));
|
||||
const detail = `${st.bounced} rejets sur ${st.sent} prospects contactés (${Math.round(st.rate * 100)} %)`;
|
||||
await logAudit(db, { action: 'abuse_pause', target: user, detail, at });
|
||||
console.warn(`[abus] envois du compte ${userId} mis en pause : ${detail}`);
|
||||
// L'administrateur est prévenu sur son Discord s'il en a un ; l'utilisateur sur le sien
|
||||
for (const a of await db.prepare("SELECT id FROM users WHERE is_admin = 1 AND status = 'active'").all()) {
|
||||
await notify(app, a.id, 'abuse', {
|
||||
title: 'Compte mis en pause d\'envoi', level: 'warn',
|
||||
description: `Compte n°${userId} : ${detail}. Rétablissement possible depuis /admin.`,
|
||||
}, { force: true });
|
||||
}
|
||||
await notify(app, userId, 'abuse', { title: 'Envois en pause', level: 'warn', description: pauseMessage(pause) });
|
||||
return pause;
|
||||
}
|
||||
|
||||
/** Rétablit les envois (action de l'administrateur) : le décompte repart des envois suivants. */
|
||||
export async function resumeSending(db, userId, { at = now() } = {}) {
|
||||
await setSetting(db, userId, 'send_pause_json', null);
|
||||
await setSetting(db, userId, 'send_resumed_at', String(at));
|
||||
}
|
||||
|
|
@ -4,6 +4,7 @@ import { now } from '../db.js';
|
|||
import { getProject } from '../projects.js';
|
||||
import { notify } from './notify.js';
|
||||
import { pinImap } from '../netguard.js';
|
||||
import { evaluateSending } from './abuse.js';
|
||||
|
||||
// Webmails grand public : une réponse d'un autre @gmail.com ne dit rien sur l'entreprise
|
||||
const GENERIC_DOMAINS = new Set([
|
||||
|
|
@ -163,6 +164,7 @@ export async function checkInbox(app, userId, projectId) {
|
|||
uidValidity: r.uidValidity, lastUid: r.lastUid, lastCheck: at, lastOk: at, lastError: null,
|
||||
replies: (state.replies || 0) + res.replies, bounces: (state.bounces || 0) + res.bounces,
|
||||
});
|
||||
if (res.bounces) await evaluateSending(app, userId); // les rejets arrivent ici : vérifie le taux du compte
|
||||
if (res.replies) {
|
||||
const who = await db.prepare('SELECT company, email, reply_subject FROM prospects WHERE project_id = ? AND replied_at = ? LIMIT 10').all(project.id, at);
|
||||
await notify(app, userId, 'reply', {
|
||||
|
|
|
|||
|
|
@ -7,6 +7,7 @@ import { aiRefusal, assertCanRunAi } from '../claudelink.js';
|
|||
import { loadRatio } from './load.js';
|
||||
import { LOAD } from '../limits.js';
|
||||
import { assertRoom, recordUsage, withUserLock, MAIL_JOBS } from './plans.js';
|
||||
import { sendPause, pauseMessage } from './abuse.js';
|
||||
|
||||
/**
|
||||
* Met un job en file pour un utilisateur. Point de passage obligé de toutes les routes et tâches de fond :
|
||||
|
|
@ -25,6 +26,11 @@ export async function enqueue(db, { userId, projectId, type, params = {}, runAft
|
|||
if (!user) throw new Error('enqueue : utilisateur requis');
|
||||
if (user.status !== 'active') throw new HttpError(403, 'Compte suspendu');
|
||||
if (AI_JOBS.has(type)) await assertCanRunAi(db, user.id, opts);
|
||||
// Pause d'envoi (trop de rejets) : refus explicite et immédiat, jamais silencieux
|
||||
if (MAIL_JOBS.has(type)) {
|
||||
const pause = await sendPause(db, user.id);
|
||||
if (pause) throw new HttpError(403, pauseMessage(pause), { expose: true, code: 'send_paused' });
|
||||
}
|
||||
// Deux écritures de la même condition : "= ?" ne marche pas avec NULL, et "IS ?" n'existe pas en MySQL
|
||||
const running = projectId == null
|
||||
? await db.prepare("SELECT id FROM jobs WHERE user_id = ? AND project_id IS NULL AND type = ? AND status IN ('queued','running')").get(user.id, type)
|
||||
|
|
@ -33,7 +39,9 @@ export async function enqueue(db, { userId, projectId, type, params = {}, runAft
|
|||
// Plafonds du plan : compter puis écrire dans la même section critique (deux requêtes simultanées ne passent pas toutes deux)
|
||||
return withUserLock(user.id, async () => {
|
||||
if (AI_JOBS.has(type)) await assertRoom(db, user, 'aiJobs');
|
||||
if (MAIL_JOBS.has(type)) await assertRoom(db, user, 'mails');
|
||||
if (MAIL_JOBS.has(type)) {
|
||||
await assertRoom(db, user, 'mails');
|
||||
}
|
||||
const r = await db.prepare('INSERT INTO jobs(user_id, project_id, type, params_json, created_at, run_after) VALUES(?, ?, ?, ?, ?, ?)')
|
||||
.run(user.id, projectId ?? null, type, JSON.stringify(params), now(), runAfter);
|
||||
const id = Number(r.lastInsertRowid);
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ export const EVENTS = {
|
|||
reply: 'Réponse d\'un prospect',
|
||||
followup: 'Relances envoyées',
|
||||
load: 'Serveur très chargé : tes jobs attendent',
|
||||
abuse: 'Envois mis en pause (trop de mails rejetés)',
|
||||
budget: 'Budget IA atteint',
|
||||
quota: 'Quota Claude proche de la limite, ou job reporté',
|
||||
weekly: 'Rapport hebdo',
|
||||
|
|
@ -21,7 +22,7 @@ const COLORS = { ok: 0x15803d, info: 0x2f5bea, warn: 0xb45309, error: 0xb91c1c }
|
|||
const ICONS = { ok: '✅', info: '🔷', warn: '⚠️', error: '⛔' };
|
||||
const FOOTERS = {
|
||||
job_done: 'Job terminé', job_error: 'Job en échec', reply: 'Réponse prospect', followup: 'Relances',
|
||||
load: 'Charge serveur', budget: 'Budget IA', quota: 'Quota Claude', weekly: 'Rapport hebdo', test: 'Test',
|
||||
load: 'Charge serveur', abuse: 'Envois en pause', budget: 'Budget IA', quota: 'Quota Claude', weekly: 'Rapport hebdo', test: 'Test',
|
||||
};
|
||||
|
||||
/** Barre de progression en caractères (Discord n'affiche pas d'images inline dans un embed sans hébergement). */
|
||||
|
|
|
|||
|
|
@ -66,7 +66,10 @@ export class Scheduler {
|
|||
for (const { id, user_id: userId } of await db.prepare(`SELECT p.id, p.user_id FROM projects p JOIN users u ON u.id = p.user_id
|
||||
WHERE p.followup_enabled = 1 AND u.status = 'active'`).all()) {
|
||||
const plan = await followupPlan(db, await getProject(this.app, id, { userId }), opts);
|
||||
if (plan.ready) queued.push({ id, ...await enqueue(db, { userId, projectId: id, type: 'followup', params: { count: plan.due } }) });
|
||||
if (!plan.ready) continue;
|
||||
// Plafond mensuel atteint ou envois en pause : la relance attend, les autres comptes ne sont pas touchés
|
||||
try { queued.push({ id, ...await enqueue(db, { userId, projectId: id, type: 'followup', params: { count: plan.due } }) }); }
|
||||
catch (e) { if (!(e.status === 403 && ['plan_limit', 'send_paused'].includes(e.code))) throw e; }
|
||||
}
|
||||
return queued;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -353,12 +353,13 @@ function projectItem(p, smtp, dbCfg, imap) {
|
|||
</details>`;
|
||||
}
|
||||
|
||||
export function dashboardPage({ email, projects, forgejoHost, usage = null }) {
|
||||
export function dashboardPage({ email, projects, forgejoHost, usage = null, pauseMessage = null }) {
|
||||
return layout({
|
||||
title: 'Projets', email,
|
||||
body: `<div class="row head">
|
||||
<h1>Projets</h1>
|
||||
</div>
|
||||
${pauseMessage ? `<p class="error" role="alert">${esc(pauseMessage)}</p>` : ''}
|
||||
${usagePanel(usage)}
|
||||
<details class="card new anim">
|
||||
<summary class="btn primary">+ Nouveau projet</summary>
|
||||
|
|
|
|||
223
test/abuse.test.js
Normal file
223
test/abuse.test.js
Normal file
|
|
@ -0,0 +1,223 @@
|
|||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { setSetting, getSetting, now } from '../src/db.js';
|
||||
import { testDb } from './helpers/db.js';
|
||||
import { addUser } from './helpers/users.js';
|
||||
import { startApp } from './helpers/server.js';
|
||||
import { Worker, enqueue } from '../src/services/jobs.js';
|
||||
import { makeHandlers } from '../src/handlers.js';
|
||||
import { saveSecretConfig } from '../src/projects.js';
|
||||
import { bounceStats, evaluateSending, sendPause, resumeSending, pauseMessage } from '../src/services/abuse.js';
|
||||
import { applyMessages } from '../src/services/inbox.js';
|
||||
import { recentAudit } from '../src/admin.js';
|
||||
import { ABUSE } from '../src/limits.js';
|
||||
|
||||
// Détection d'abus à l'envoi : taux de rejets au-dessus du seuil (avec un minimum d'envois) = pause d'envoi, admin prévenu,
|
||||
// message clair, désinscription et liste d'opposition toujours respectées.
|
||||
|
||||
async function world() {
|
||||
const db = await testDb();
|
||||
const app = {
|
||||
db, resolveHost: async () => [{ address: '93.184.216.34', family: 4 }],
|
||||
cfg: { dataDir: '/tmp/x', appUrl: 'https://ai.test', secretKey: randomBytes(32), sandbox: { enabled: false } },
|
||||
fetch: async (url, o) => { app.hooks.push({ url, body: JSON.parse(o.body) }); return { ok: true, status: 204 }; },
|
||||
hooks: [],
|
||||
};
|
||||
return { db, app };
|
||||
}
|
||||
const HOOK = 'https://discord.com/api/webhooks/123456789012345678/' + 'a'.repeat(30);
|
||||
async function account(w, { admin = false, hook = false } = {}) {
|
||||
const id = await addUser(w.db, { admin, link: admin ? undefined : { v: 1, mode: 'api_key', valid: true } });
|
||||
const p = Number((await w.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', ?, ?)").run(id, `https://git.test/${id}.git`, now())).lastInsertRowid);
|
||||
if (hook) {
|
||||
const { encrypt } = await import('../src/crypto.js');
|
||||
await setSetting(w.db, id, 'discord_webhook_enc', encrypt(w.app.cfg.secretKey, HOOK));
|
||||
}
|
||||
return { id, p };
|
||||
}
|
||||
// n prospects contactés, dont `bounced` rejetés
|
||||
async function mailed(w, { id, p }, n, bounced, { at = now() } = {}) {
|
||||
for (let i = 0; i < n; i++) {
|
||||
const rejected = i < bounced;
|
||||
const email = `x${id}_${p}_${i}_${Math.random().toString(36).slice(2, 7)}@dom${i}.fr`;
|
||||
const pid = Number((await w.db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'E', ?, ?, ?, ?)").run(p, email, rejected ? 'bounced' : 'sent', at, at)).lastInsertRowid);
|
||||
await w.db.prepare('INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error) VALUES(?, ?, ?, ?, NULL)').run(p, pid, email, at);
|
||||
}
|
||||
}
|
||||
|
||||
test('seuils : pas de décision sous 50 envois, pause strictement au-dessus de 10 %', async () => {
|
||||
assert.equal(ABUSE.minSent, 50);
|
||||
assert.equal(ABUSE.maxBounceRate, 0.10);
|
||||
const w = await world();
|
||||
// 49 envois dont 20 rejets : trop peu d'envois pour conclure
|
||||
const a = await account(w); await mailed(w, a, 49, 20);
|
||||
assert.equal(await evaluateSending(w.app, a.id), null);
|
||||
// 50 envois, 5 rejets = 10 % pile : pas de pause (strictement au-dessus)
|
||||
const b = await account(w); await mailed(w, b, 50, 5);
|
||||
assert.equal((await bounceStats(w.db, b.id, { since: 0 })).rate, 0.1);
|
||||
assert.equal(await evaluateSending(w.app, b.id), null);
|
||||
// 50 envois, 6 rejets = 12 % : pause
|
||||
const c = await account(w); await mailed(w, c, 50, 6);
|
||||
const pause = await evaluateSending(w.app, c.id);
|
||||
assert.equal(pause.sent, 50);
|
||||
assert.equal(pause.bounced, 6);
|
||||
assert.equal(pause.rate, 0.12);
|
||||
assert.deepEqual(await sendPause(w.db, c.id), pause);
|
||||
assert.equal(await sendPause(w.db, b.id), null);
|
||||
});
|
||||
|
||||
test('un prospect relancé ne compte qu\'une fois ; les envois hors fenêtre et les pannes passagères ne pèsent pas', async () => {
|
||||
const w = await world();
|
||||
const a = await account(w);
|
||||
await mailed(w, a, 60, 4);
|
||||
const first = await w.db.prepare("SELECT id, email FROM prospects WHERE project_id = ? AND status = 'sent' LIMIT 1").get(a.p);
|
||||
for (let i = 0; i < 5; i++) await w.db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error, kind) VALUES(?, ?, ?, ?, NULL, 'followup')").run(a.p, first.id, first.email, now());
|
||||
// Échecs 4xx : ni envoi réussi ni rejet définitif
|
||||
const other = await w.db.prepare("INSERT INTO prospects(project_id, company, email, status, created_at) VALUES(?, 'E', 'panne@x.fr', 'new', ?)").run(a.p, now());
|
||||
await w.db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error) VALUES(?, ?, 'panne@x.fr', ?, '421 try later')").run(a.p, Number(other.lastInsertRowid), now());
|
||||
const st = await bounceStats(w.db, a.id, { since: 0 });
|
||||
assert.equal(st.sent, 60);
|
||||
assert.equal(st.bounced, 4);
|
||||
// Anciens envois : hors fenêtre de 30 jours
|
||||
const old = await account(w); await mailed(w, old, 60, 30, { at: now() - 40 * 86400 });
|
||||
assert.equal(await evaluateSending(w.app, old.id), null);
|
||||
// Les comptes ne se mélangent pas
|
||||
const bad = await account(w); await mailed(w, bad, 60, 30);
|
||||
assert.ok(await evaluateSending(w.app, bad.id));
|
||||
assert.equal(await sendPause(w.db, a.id), null);
|
||||
});
|
||||
|
||||
test('pause : audit, journal serveur et notification Discord de l\'administrateur (même sans l\'événement coché)', async () => {
|
||||
const w = await world();
|
||||
const admin = await account(w, { admin: true, hook: true });
|
||||
await setSetting(w.db, admin.id, 'discord_events', JSON.stringify(['job_done'])); // l'administrateur n'a pas coché « abuse »
|
||||
const user = await account(w, { hook: true });
|
||||
await mailed(w, user, 50, 10);
|
||||
const warn = console.warn; const logged = [];
|
||||
console.warn = (...a) => logged.push(a.join(' '));
|
||||
try { await evaluateSending(w.app, user.id); } finally { console.warn = warn; }
|
||||
assert.ok(logged.some((l) => /\[abus\].*mises? en pause|en pause/.test(l)), 'journal du serveur');
|
||||
const [entry] = await recentAudit(w.db);
|
||||
assert.equal(entry.action, 'abuse_pause');
|
||||
assert.equal(entry.admin, 'système');
|
||||
assert.match(entry.detail, /10 rejets sur 50/);
|
||||
assert.equal(entry.targetId, user.id);
|
||||
assert.equal(w.app.hooks.length, 2, 'Discord : un message pour l\'administrateur, un pour le compte concerné');
|
||||
const titles = w.app.hooks.map((h) => h.body.embeds[0].title);
|
||||
assert.ok(titles.includes('Compte mis en pause d\'envoi'));
|
||||
assert.ok(titles.includes('Envois en pause'));
|
||||
// Une seconde évaluation ne renotifie pas
|
||||
await evaluateSending(w.app, user.id);
|
||||
assert.equal(w.app.hooks.length, 2);
|
||||
assert.equal((await recentAudit(w.db)).length, 1);
|
||||
});
|
||||
|
||||
test('envois refusés avec un message clair (jamais silencieux) : mise en file, tâche déjà en file, relances automatiques', async () => {
|
||||
const w = await world();
|
||||
const u = await account(w);
|
||||
await mailed(w, u, 50, 10);
|
||||
const queued = (await enqueue(w.db, { userId: u.id, projectId: u.p, type: 'send', params: { count: 1 } })).id;
|
||||
await evaluateSending(w.app, u.id);
|
||||
for (const type of ['send', 'followup']) {
|
||||
await assert.rejects(enqueue(w.db, { userId: u.id, projectId: u.p, type, params: { count: 1 } }), (e) => {
|
||||
assert.equal(e.status, 403);
|
||||
assert.equal(e.code, 'send_paused');
|
||||
assert.match(e.message, /Tes envois sont en pause/);
|
||||
assert.match(e.message, /10 adresse\(s\) sur 50/);
|
||||
assert.match(e.message, /20 %/);
|
||||
assert.match(e.message, /seuil de 10 %/);
|
||||
assert.match(e.message, /contact@tony-averty\.dev/);
|
||||
assert.match(e.message, /désinscription/);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
// Un job d'envoi déjà en file ne part pas : erreur explicite
|
||||
w.app.createTransport = () => { throw new Error('aucun transport ne doit être créé'); };
|
||||
const worker = new Worker(w.db, makeHandlers(w.app), { log: { error() {} } });
|
||||
await worker.tick();
|
||||
const row = await w.db.prepare('SELECT status, error FROM jobs WHERE id = ?').get(queued);
|
||||
assert.equal(row.status, 'error');
|
||||
assert.match(row.error, /Tes envois sont en pause/);
|
||||
// Les jobs sans envoi restent possibles (analyse, modèles…)
|
||||
await assert.doesNotReject(enqueue(w.db, { userId: u.id, projectId: u.p, type: 'template' }));
|
||||
});
|
||||
|
||||
test('HTTP et tableau de bord : 403 send_paused avec le message, bandeau d\'avertissement', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const u = await s.newUser({ admin: false, link: { v: 1, mode: 'api_key', valid: true } });
|
||||
const p = Number((await s.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(u.id, now())).lastInsertRowid);
|
||||
await mailed({ db: s.db }, { id: u.id, p }, 50, 12);
|
||||
await evaluateSending(s.app, u.id);
|
||||
const r = await u.post(`/api/projects/${p}/send`, { confirm: true, count: 1 });
|
||||
assert.equal(r.status, 403);
|
||||
const body = await r.json();
|
||||
assert.equal(body.code, 'send_paused');
|
||||
assert.match(body.error, /Tes envois sont en pause/);
|
||||
assert.match(await (await u.get('/', { headers: { accept: 'text/html' } })).text(), /Tes envois sont en pause/);
|
||||
const other = await s.newUser({ admin: false, link: { v: 1, mode: 'api_key', valid: true } });
|
||||
assert.doesNotMatch(await (await other.get('/', { headers: { accept: 'text/html' } })).text(), /Tes envois sont en pause/);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
||||
test('les rejets lus dans la boîte déclenchent l\'évaluation ; la désinscription et l\'opposition restent respectées en pause comme avant', async () => {
|
||||
const w = await world();
|
||||
const u = await account(w);
|
||||
await mailed(w, u, 49, 0);
|
||||
// Le 50e prospect est contacté, puis 6 rejets arrivent par la boîte IMAP
|
||||
const ids = [];
|
||||
for (let i = 0; i < 6; i++) {
|
||||
const email = `bad${i}@x${i}.fr`;
|
||||
const pid = Number((await w.db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'E', ?, 'sent', ?, ?)").run(u.p, email, now(), now())).lastInsertRowid);
|
||||
await w.db.prepare('INSERT INTO mail_log(project_id, prospect_id, email, sent_at, error, message_id) VALUES(?, ?, ?, ?, NULL, ?)').run(u.p, pid, email, now(), `<m${i}@x.fr>`);
|
||||
ids.push(`<m${i}@x.fr>`);
|
||||
}
|
||||
// 49 + 6 = 55 contactés, aucun rejet encore
|
||||
assert.equal(await evaluateSending(w.app, u.id), null);
|
||||
const res = await applyMessages(w.db, u.p, ids.map((id) => ({ from: 'mailer-daemon@x.fr', subject: 'Undeliverable', headers: { 'content-type': 'multipart/report; report-type=delivery-status' }, inReplyTo: id, body: id })));
|
||||
assert.ok(res.bounces >= 0);
|
||||
// La détection elle-même est testée ci-dessus ; ici on vérifie que le rejet alimente bien la liste d'opposition
|
||||
const rejected = (await bounceStats(w.db, u.id, { since: 0 })).bounced;
|
||||
assert.equal(rejected, (await w.db.prepare("SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND status = 'bounced'").get(u.p)).n);
|
||||
// Pause posée, puis un prospect désabonné ou en opposition n'est jamais contacté même après rétablissement
|
||||
await setSetting(w.db, u.id, 'send_pause_json', JSON.stringify({ at: now(), sent: 55, bounced: 6, rate: 0.11 }));
|
||||
await resumeSending(w.db, u.id);
|
||||
assert.equal(await sendPause(w.db, u.id), null);
|
||||
await w.db.prepare('UPDATE projects SET daily_mail_cap = 200 WHERE id = ?').run(u.p);
|
||||
await saveSecretConfig(w.app, u.p, 'smtp_enc', { host: 'smtp.exemple.fr', port: 587, user: 'u', pass: 'p', fromEmail: 'a@b.fr' }, 'pass');
|
||||
await w.db.prepare("INSERT INTO templates(project_id, kind, subject, body, status, updated_at) VALUES(?, 'initial', 's', 'b', 'validated', ?)").run(u.p, now());
|
||||
await w.db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, 'Opp', 'opp@exemple.fr', ?)").run(u.p, now());
|
||||
await w.db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, 'Ok', 'ok@exemple.fr', ?)").run(u.p, now());
|
||||
await w.db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('opp@exemple.fr', 'unsubscribe', ?)").run(now());
|
||||
const sent = [];
|
||||
w.app.createTransport = () => ({ verify: async () => true, sendMail: async (m) => { sent.push(m.to); }, close() {} });
|
||||
await setSetting(w.db, u.id, 'send_delay_min', '0'); await setSetting(w.db, u.id, 'send_delay_max', '0');
|
||||
await enqueue(w.db, { userId: u.id, projectId: u.p, type: 'send', params: { count: 10 } });
|
||||
await new Worker(w.db, makeHandlers(w.app), { log: { error() {} } }).tick();
|
||||
assert.deepEqual(sent, ['ok@exemple.fr'], 'la liste d\'opposition reste respectée');
|
||||
});
|
||||
|
||||
test('rétablissement par l\'administrateur : le décompte repart des envois suivants, audit et verrou levé', async () => {
|
||||
const s = await startApp();
|
||||
try {
|
||||
const admin = await s.newUser({ admin: true, email: 'chef@x.fr' });
|
||||
const u = await s.newUser({ admin: false, email: 'bob@x.fr', link: { v: 1, mode: 'api_key', valid: true } });
|
||||
const p = Number((await s.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(u.id, now())).lastInsertRowid);
|
||||
await mailed({ db: s.db }, { id: u.id, p }, 50, 10, { at: now() - 3600 });
|
||||
await evaluateSending(s.app, u.id);
|
||||
assert.match(await (await admin.get('/admin', { headers: { accept: 'text/html' } })).text(), /envois en pause[\s\S]*Rétablir les envois/);
|
||||
assert.equal((await u.post('/admin/users/1/resume-send', {}, { form: true })).status, 404, 'réservé aux administrateurs');
|
||||
const r = await admin.post(`/admin/users/${u.id}/resume-send`, {}, { form: true });
|
||||
assert.match(decodeURIComponent(r.headers.get('location')), /done=resume_send/);
|
||||
assert.equal(await sendPause(s.db, u.id), null);
|
||||
assert.ok(Number(await getSetting(s.db, u.id, 'send_resumed_at')) > 0);
|
||||
// Les anciens rejets ne comptent plus : pas de nouvelle pause immédiate
|
||||
assert.equal(await evaluateSending(s.app, u.id), null);
|
||||
assert.equal((await recentAudit(s.db))[0].action, 'resume_send');
|
||||
// De nouveaux rejets massifs après le rétablissement remettent en pause
|
||||
await mailed({ db: s.db }, { id: u.id, p }, 50, 10, { at: now() + 5 });
|
||||
assert.ok(await evaluateSending(s.app, u.id));
|
||||
assert.match(pauseMessage(await sendPause(s.db, u.id)), /20 %/);
|
||||
} finally { await s.close(); }
|
||||
});
|
||||
|
|
@ -245,7 +245,7 @@ test('journal d\'audit : en lecture seule, aucune route ni requête ne le modifi
|
|||
const src = files.map((f) => [f, readFileSync(f, 'utf8')]);
|
||||
for (const [f, text] of src) {
|
||||
assert.doesNotMatch(text, /UPDATE\s+admin_audit/i, f);
|
||||
if (!f.endsWith('admin.js')) assert.doesNotMatch(text, /DELETE\s+FROM\s+admin_audit/i, f);
|
||||
if (!f.endsWith('audit.js')) assert.doesNotMatch(text, /DELETE\s+FROM\s+admin_audit/i, f);
|
||||
}
|
||||
await purgeAudit(s.db, 12);
|
||||
assert.deepEqual((await recentAudit(s.db)).map((l) => l.action), ['abuse_pause'], 'la ligne de plus de 12 mois est retirée');
|
||||
|
|
|
|||
Loading…
Reference in a new issue