feat(accounts): suppression des comptes inactifs avec avertissement 30 jours avant
Planificateur : après INACTIVE_ACCOUNT_MONTHS mois (24 par défaut, 0 pour désactiver) sans connexion ni job, un mail part via le SMTP du serveur (SYSTEM_SMTP_*), puis le compte est supprimé 30 jours plus tard s'il est resté inactif. Pas de suppression sans avertissement reçu (sinon seulement journalisé), jamais un administrateur ni un compte suspendu. Horloge injectable. La politique de confidentialité annonce la suppression comme en place.
This commit is contained in:
parent
c9066e9e8d
commit
433c74fc54
6 changed files with 381 additions and 4 deletions
|
|
@ -51,6 +51,23 @@ function ratio(v, def, name) {
|
|||
return n;
|
||||
}
|
||||
|
||||
// SMTP du serveur (mails système : avertissement avant suppression d'un compte inactif). Facultatif ; toutes les variables ensemble.
|
||||
function systemSmtpConfig() {
|
||||
const keys = ['SYSTEM_SMTP_HOST', 'SYSTEM_SMTP_USER', 'SYSTEM_SMTP_PASSWORD', 'SYSTEM_SMTP_FROM'];
|
||||
const set = keys.filter((k) => env[k]);
|
||||
if (!set.length) return null;
|
||||
if (set.length < keys.length) throw new Error(`SMTP du serveur : variables incomplètes (manque ${keys.filter((k) => !env[k]).join(', ')})`);
|
||||
return { host: env.SYSTEM_SMTP_HOST, port: Number(env.SYSTEM_SMTP_PORT || 587), user: env.SYSTEM_SMTP_USER, pass: env.SYSTEM_SMTP_PASSWORD, fromEmail: env.SYSTEM_SMTP_FROM };
|
||||
}
|
||||
|
||||
function inactiveMonths() {
|
||||
const raw = (env.INACTIVE_ACCOUNT_MONTHS || '').trim();
|
||||
if (raw === '') return 24;
|
||||
const n = Number(raw);
|
||||
if (!Number.isInteger(n) || n < 0 || n > 120) throw new Error('INACTIVE_ACCOUNT_MONTHS doit être un nombre entier de mois entre 0 (désactivé) et 120');
|
||||
return n;
|
||||
}
|
||||
|
||||
const flag = (v, def) => (v == null || v === '' ? def : !/^(0|false|off|no|non)$/i.test(String(v).trim()));
|
||||
|
||||
// Bac à sable des exécutions Claude. En production il est obligatoire : SANDBOX=off n'y est pas pris en compte.
|
||||
|
|
@ -85,6 +102,8 @@ export function loadConfig() {
|
|||
},
|
||||
apple: appleConfig(),
|
||||
recaptcha: recaptchaConfig(),
|
||||
systemSmtp: systemSmtpConfig(),
|
||||
inactiveMonths: inactiveMonths(),
|
||||
production: env.NODE_ENV === 'production',
|
||||
// Développement : autorise les hôtes privés (SMTP local, etc.). En production, seulement pour les administrateurs.
|
||||
allowPrivateHosts: flag(env.ALLOW_PRIVATE_HOSTS, false),
|
||||
|
|
|
|||
109
src/services/inactive.js
Normal file
109
src/services/inactive.js
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
// Suppression des comptes inactifs (annoncée dans la politique de confidentialité), lancée par le planificateur.
|
||||
// - inactif = aucune connexion ni job depuis INACTIVE_ACCOUNT_MONTHS mois (24 par défaut) ;
|
||||
// - un mail d'avertissement part 30 jours avant, via le SMTP du serveur (SYSTEM_SMTP_*) ;
|
||||
// - un compte n'est supprimé que s'il a REÇU cet avertissement et qu'il est resté inactif les 30 jours suivants : sans SMTP du
|
||||
// serveur, l'avertissement est seulement journalisé et rien n'est supprimé automatiquement ;
|
||||
// - jamais un administrateur, jamais un compte suspendu (la suspension sert aussi à garder la trace d'un abus).
|
||||
import { now, getSetting, setSetting } from '../db.js';
|
||||
import { INACTIVITY } from '../limits.js';
|
||||
import { logAudit } from '../audit.js';
|
||||
import { deleteUser } from '../users.js';
|
||||
import { createTransport } from './mailer.js';
|
||||
import { pinSmtp } from '../netguard.js';
|
||||
import { CONTACT_EMAIL } from '../site/layout.js';
|
||||
|
||||
const DAY = 86400;
|
||||
|
||||
/** Même instant, `n` mois plus tard (calendrier UTC). */
|
||||
export function addMonths(ts, n) {
|
||||
const d = new Date(ts * 1000);
|
||||
d.setUTCMonth(d.getUTCMonth() + n);
|
||||
return Math.floor(d.getTime() / 1000);
|
||||
}
|
||||
|
||||
/** Dernière activité : connexion, création du compte ou dernier job lancé. */
|
||||
export async function lastActivity(db, user) {
|
||||
const job = await db.prepare('SELECT MAX(created_at) t FROM jobs WHERE user_id = ?').get(Number(user.id));
|
||||
return Math.max(Number(user.last_login_at) || 0, Number(user.created_at) || 0, Number(job?.t) || 0);
|
||||
}
|
||||
|
||||
const dateFr = (ts) => new Date(ts * 1000).toLocaleDateString('fr-FR', { dateStyle: 'long', timeZone: 'Europe/Paris' });
|
||||
|
||||
export function warningMail(cfg, user, deleteAt) {
|
||||
const text = [
|
||||
'Bonjour,',
|
||||
'',
|
||||
`Ton compte AiTools (${user.email}) n'a pas servi depuis longtemps. Conformément à notre politique de confidentialité, il sera supprimé avec toutes ses données (projets, prospects, modèles, réglages) à partir du ${dateFr(deleteAt)}.`,
|
||||
'',
|
||||
`Pour le garder, il suffit de te connecter avant cette date : ${cfg.appUrl}/login`,
|
||||
`Pour récupérer tes prospects avant, exporte-les en CSV depuis le tableau de bord (${cfg.appUrl}/).`,
|
||||
'',
|
||||
`Une question ? ${CONTACT_EMAIL}`,
|
||||
'',
|
||||
"AiTools · message automatique, envoyé une seule fois.",
|
||||
].join('\n');
|
||||
return { subject: 'Ton compte AiTools sera supprimé pour inactivité', text };
|
||||
}
|
||||
|
||||
async function sendWarning(app, user, deleteAt) {
|
||||
const smtp = app.cfg.systemSmtp;
|
||||
if (!smtp) return { sent: false, reason: "SMTP du serveur non configuré (SYSTEM_SMTP_HOST)" };
|
||||
const mail = warningMail(app.cfg, user, deleteAt);
|
||||
const transport = (app.createTransport || createTransport)(await pinSmtp(app, null, smtp));
|
||||
try {
|
||||
await transport.sendMail({ from: smtp.fromEmail, to: user.email, subject: mail.subject, text: mail.text });
|
||||
return { sent: true };
|
||||
} catch (e) {
|
||||
return { sent: false, reason: `envoi impossible (${String(e.message).slice(0, 120)})`, transient: true };
|
||||
} finally { transport.close?.(); }
|
||||
}
|
||||
|
||||
/**
|
||||
* Un passage : avertit les comptes qui approchent de l'échéance, supprime ceux qui l'ont dépassée après avertissement.
|
||||
* `at` est injectable (horloge des tests). months = 0 désactive la suppression.
|
||||
* @returns {{warned: number, deleted: number, unsent: number}}
|
||||
*/
|
||||
export async function runInactiveCleanup(app, { at = now(), months = app.cfg.inactiveMonths ?? INACTIVITY.defaultMonths, log = console } = {}) {
|
||||
const out = { warned: 0, deleted: 0, unsent: 0 };
|
||||
if (!months || months < 1) return out;
|
||||
const { db } = app;
|
||||
const warnSec = INACTIVITY.warningDays * DAY;
|
||||
// Pré-filtre en base : seuls les comptes dont la dernière connexion approche de l'échéance sont examinés un par un
|
||||
const horizon = addMonths(at, -months) + warnSec;
|
||||
const rows = await db.prepare(`SELECT id, email, created_at, last_login_at FROM users
|
||||
WHERE is_admin = 0 AND plan <> 'admin' AND status = 'active' AND COALESCE(last_login_at, created_at) <= ?`).all(horizon);
|
||||
for (const user of rows) {
|
||||
const act = await lastActivity(db, user);
|
||||
const deadline = addMonths(act, months);
|
||||
if (at < deadline - warnSec) continue; // un job récent a repoussé l'échéance
|
||||
const warnedAt = Number(await getSetting(db, user.id, 'inactive_warned_at', '0')) || 0;
|
||||
const warned = warnedAt > act; // un avertissement antérieur à la dernière activité ne compte plus
|
||||
|
||||
if (!warned) {
|
||||
const deleteAt = Math.max(deadline, at + warnSec);
|
||||
const r = await sendWarning(app, user, deleteAt);
|
||||
if (r.sent) {
|
||||
await setSetting(db, user.id, 'inactive_warned_at', String(at));
|
||||
await logAudit(db, { action: 'inactive_warning', target: user, detail: `avertissement envoyé, suppression possible dès le ${dateFr(deleteAt)}`, at });
|
||||
out.warned++;
|
||||
} else {
|
||||
out.unsent++;
|
||||
log.warn?.(`[inactifs] compte ${user.id} : avertissement non envoyé, ${r.reason}. Aucune suppression automatique.`);
|
||||
// Une seule trace au journal d'audit par période d'inactivité (pas à chaque passage du planificateur)
|
||||
const noted = Number(await getSetting(db, user.id, 'inactive_noted_at', '0')) || 0;
|
||||
if (!r.transient && noted <= act) {
|
||||
await setSetting(db, user.id, 'inactive_noted_at', String(at));
|
||||
await logAudit(db, { action: 'inactive_warning', target: user, detail: `avertissement NON envoyé : ${r.reason}. Compte inactif à traiter à la main.`, at });
|
||||
}
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if (at >= deadline && at >= warnedAt + warnSec) {
|
||||
await logAudit(db, { action: 'inactive_delete', target: user, detail: `inactif depuis le ${dateFr(act)}, avertissement du ${dateFr(warnedAt)}`, at });
|
||||
app.worker?.abortUser(user.id);
|
||||
await deleteUser(app, user.id);
|
||||
out.deleted++;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
|
@ -9,10 +9,15 @@ import { enqueue } from './jobs.js';
|
|||
import { getProject } from '../projects.js';
|
||||
import { maybeSendWeekly } from './report.js';
|
||||
import { snapshotAll } from './metrics.js';
|
||||
import { runInactiveCleanup } from './inactive.js';
|
||||
import { purgeAudit } from '../audit.js';
|
||||
import { INACTIVITY } from '../limits.js';
|
||||
import { now } from '../db.js';
|
||||
|
||||
export class Scheduler {
|
||||
constructor(app, { everyMs = 15 * 60_000, log = console } = {}) {
|
||||
constructor(app, { everyMs = 15 * 60_000, log = console, clock = now } = {}) {
|
||||
this.app = app;
|
||||
this.clock = clock; // secondes ; injectable pour les tests
|
||||
this.everyMs = everyMs;
|
||||
this.log = log;
|
||||
this.running = false;
|
||||
|
|
@ -57,6 +62,11 @@ export class Scheduler {
|
|||
catch (e) { this.log.error('[rapport hebdo]', e.message); }
|
||||
}
|
||||
await snapshotAll(this.app, { log: this.log });
|
||||
// Entretien : comptes inactifs (avertissement puis suppression) et ancien journal d'audit
|
||||
try {
|
||||
await runInactiveCleanup(this.app, { at: this.clock(), log: this.log });
|
||||
await purgeAudit(this.app.db, INACTIVITY.auditRetentionMonths, this.clock());
|
||||
} catch (e) { this.log.error('[inactifs]', e.message); }
|
||||
} finally { this.running = false; }
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -94,7 +94,7 @@ export function mentionsPage({ appUrl }) {
|
|||
|
||||
// ---------- Politique de confidentialité ----------
|
||||
// `captcha` : reCAPTCHA configuré. Les paragraphes qui le concernent n'apparaissent que dans ce cas, comme Apple.
|
||||
export function privacyPage({ appUrl, apple = false, captcha = false }) {
|
||||
export function privacyPage({ appUrl, apple = false, captcha = false, inactiveMonths = 24 }) {
|
||||
return legalPage({
|
||||
appUrl, path: '/confidentialite',
|
||||
title: 'Politique de confidentialité · AiTools',
|
||||
|
|
@ -124,6 +124,7 @@ export function privacyPage({ appUrl, apple = false, captcha = false }) {
|
|||
<tr><th scope="row">Prospects</th><td>Entreprise, adresse professionnelle, site, ville, secteur, phrase d'accroche, page source, score, statut, notes, prochaine action, historique d'envoi, objet et date d'une réponse.</td><td>Fournir le service pour ton compte (voir « rôles »). La base légale du démarchage est la tienne, en B2B en règle générale l'intérêt légitime.</td></tr>
|
||||
<tr><th scope="row">Activité</th><td>Type, état, durée, coût et nombre de tokens de chaque job IA, résultat du job. Chaque jour, trois nombres lus dans la base de ton projet si tu l'as reliée (utilisateurs, clients, revenu).</td><td>Fournir le service, appliquer tes budgets et plafonds. Exécution du contrat.</td></tr>
|
||||
<tr><th scope="row">Adresse IP</th><td>Ton adresse IP sert à limiter le nombre de requêtes (protection contre les abus). Elle reste en mémoire du serveur, quelques minutes à quelques heures, et n'est pas enregistrée en base de données.</td><td>Sécurité du service. Intérêt légitime.</td></tr>
|
||||
<tr><th scope="row">Modération</th><td>Actions d'administration sur un compte (suspension, plan, suppression) et pauses d'envoi décidées quand trop de mails sont rejetés : date, action, identifiant du compte et adresse masquée.</td><td>Sécurité du service et lutte contre les abus. Intérêt légitime.</td></tr>
|
||||
<tr><th scope="row">Liste d'opposition</th><td>Adresse email, motif (désinscription, refus, mail rejeté) et date.</td><td>Ne plus jamais contacter une personne qui s'y est opposée, pour tous les comptes. Obligation légale, intérêt légitime.</td></tr>
|
||||
</tbody>
|
||||
</table></div>
|
||||
|
|
@ -136,7 +137,8 @@ export function privacyPage({ appUrl, apple = false, captcha = false }) {
|
|||
<thead><tr><th scope="col">Donnée</th><th scope="col">Durée</th></tr></thead>
|
||||
<tbody>
|
||||
<tr><th scope="row">Compte et toutes ses données</th><td>Tant que le compte existe. Effacés quand tu supprimes ton compte depuis Mon compte, copie du code comprise.</td></tr>
|
||||
<tr><th scope="row">Compte inactif</th><td>Suppression prévue après 24 mois sans connexion. Cette suppression automatique n'est pas encore en place.</td></tr>
|
||||
<tr><th scope="row">Compte inactif</th><td>${inactiveMonths ? `Suppression automatique après ${inactiveMonths} mois sans connexion ni job, avec un mail d'avertissement 30 jours avant. Un compte suspendu ou administrateur n'est pas concerné.` : 'Aucune suppression automatique pour inactivité.'}</td></tr>
|
||||
<tr><th scope="row">Journal d'administration</th><td>12 mois. Il note les actions des administrateurs (suspension, changement de plan, suppression) et les pauses d'envoi, avec un identifiant et une adresse masquée.</td></tr>
|
||||
<tr><th scope="row">Session</th><td>30 jours au plus, effacée à la déconnexion. Les états de connexion durent 10 minutes.</td></tr>
|
||||
<tr><th scope="row">Clé API ou jeton Claude</th><td>Jusqu'à ce que tu le délies ou supprimes ton compte.</td></tr>
|
||||
<tr><th scope="row">Prospects, notes et journaux d'envoi</th><td>Jusqu'à la suppression du projet ou du compte. En tant que responsable de traitement, ne garde pas une fiche plus de 3 ans après le dernier contact.</td></tr>
|
||||
|
|
|
|||
|
|
@ -6,7 +6,7 @@ import { robotsTxt, sitemapXml } from './seo.js';
|
|||
|
||||
export function registerSiteRoutes(router, { cfg }) {
|
||||
const apple = !!cfg.apple;
|
||||
const ctx = { appUrl: cfg.appUrl, apple, captcha: !!cfg.recaptcha };
|
||||
const ctx = { appUrl: cfg.appUrl, apple, captcha: !!cfg.recaptcha, inactiveMonths: cfg.inactiveMonths ?? 24 };
|
||||
const open = { public: true };
|
||||
|
||||
router.get('/fonctionnement', async ({ res }) => html(res, howPage(ctx)), open);
|
||||
|
|
|
|||
237
test/inactive.test.js
Normal file
237
test/inactive.test.js
Normal file
|
|
@ -0,0 +1,237 @@
|
|||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { 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 { addMonths, runInactiveCleanup, warningMail } from '../src/services/inactive.js';
|
||||
import { Scheduler } from '../src/services/scheduler.js';
|
||||
import { recentAudit } from '../src/admin.js';
|
||||
import { loadConfig } from '../src/config.js';
|
||||
|
||||
// Suppression des comptes inactifs avec une horloge injectée : avertissement 30 jours avant, suppression seulement après
|
||||
// avertissement reçu, jamais un administrateur.
|
||||
|
||||
const DAY = 86400;
|
||||
const T0 = Date.parse('2025-01-15T10:00:00Z') / 1000; // date de dernière connexion de référence
|
||||
const at = (months, days = 0) => addMonths(T0, months) + days * DAY;
|
||||
|
||||
async function world({ smtp = true, months = 24 } = {}) {
|
||||
const db = await testDb();
|
||||
const mails = [];
|
||||
const app = {
|
||||
db, resolveHost: async () => [{ address: '93.184.216.34', family: 4 }],
|
||||
cfg: {
|
||||
dataDir: '/tmp/aitools-inactive', appUrl: 'https://ai.test', secretKey: randomBytes(32), inactiveMonths: months,
|
||||
systemSmtp: smtp ? { host: 'smtp.serveur.fr', port: 587, user: 'u', pass: 'p', fromEmail: 'noreply@ai.test' } : null,
|
||||
},
|
||||
createTransport: (cfg) => ({ sendMail: async (m) => { mails.push({ ...m, via: cfg.host }); }, close() {} }),
|
||||
};
|
||||
const log = { warns: [], warn: (...a) => log.warns.push(a.join(' ')), error() {} };
|
||||
return { db, app, mails, log };
|
||||
}
|
||||
async function member(w, o = {}) {
|
||||
const id = await addUser(w.db, { admin: false, email: o.email || `m${Math.random().toString(36).slice(2, 8)}@ex.fr`, ...o });
|
||||
await w.db.prepare('UPDATE users SET created_at = ?, last_login_at = ? WHERE id = ?').run(o.createdAt ?? T0 - 10 * DAY, o.lastLogin ?? T0, id);
|
||||
return id;
|
||||
}
|
||||
const exists = async (w, id) => !!(await w.db.prepare('SELECT 1 x FROM users WHERE id = ?').get(id));
|
||||
const run = (w, when, extra = {}) => runInactiveCleanup(w.app, { at: when, log: w.log, ...extra });
|
||||
|
||||
test('chronologie : rien avant 23 mois, avertissement à J-30, suppression à J0 si avertissement reçu et resté inactif', async () => {
|
||||
const w = await world();
|
||||
const id = await member(w, { email: 'ada@ex.fr' });
|
||||
assert.deepEqual(await run(w, at(23)), { warned: 0, deleted: 0, unsent: 0 }, '23 mois : rien');
|
||||
assert.equal(w.mails.length, 0);
|
||||
assert.deepEqual(await run(w, at(24, -31)), { warned: 0, deleted: 0, unsent: 0 }, 'à 31 jours de l\'échéance : encore rien');
|
||||
|
||||
// 30 jours avant l'échéance : un avertissement, via le SMTP du serveur, jamais de suppression ce jour-là
|
||||
const warnDay = at(24, -30);
|
||||
assert.deepEqual(await run(w, warnDay), { warned: 1, deleted: 0, unsent: 0 });
|
||||
assert.equal(w.mails.length, 1);
|
||||
assert.equal(w.mails[0].to, 'ada@ex.fr');
|
||||
assert.equal(w.mails[0].from, 'noreply@ai.test');
|
||||
assert.equal(w.mails[0].via, '93.184.216.34', 'le SMTP du serveur passe aussi par le filtre SSRF');
|
||||
assert.match(w.mails[0].text, /supprimé avec toutes ses données/);
|
||||
assert.match(w.mails[0].text, /https:\/\/ai\.test\/login/);
|
||||
assert.match(w.mails[0].text, /15 janvier 2027/);
|
||||
assert.equal(await exists(w, id), true);
|
||||
// Passages suivants (toutes les 15 min) : ni second mail, ni suppression avant l'échéance
|
||||
assert.deepEqual(await run(w, warnDay + 900), { warned: 0, deleted: 0, unsent: 0 });
|
||||
assert.deepEqual(await run(w, at(24, -1)), { warned: 0, deleted: 0, unsent: 0 });
|
||||
assert.equal(w.mails.length, 1, 'un seul avertissement');
|
||||
assert.equal(await exists(w, id), true);
|
||||
// Échéance atteinte (24 mois) : supprimé
|
||||
assert.deepEqual(await run(w, at(24, 0)), { warned: 0, deleted: 1, unsent: 0 });
|
||||
assert.equal(await exists(w, id), false);
|
||||
const log = await recentAudit(w.db);
|
||||
assert.deepEqual(log.map((l) => l.action), ['inactive_delete', 'inactive_warning']);
|
||||
assert.equal(log[0].target, 'a***@ex.fr');
|
||||
assert.equal(log[0].admin, 'système');
|
||||
});
|
||||
|
||||
test('un avertissement tardif ne permet pas de supprimer tout de suite : 30 jours de délai après le mail', async () => {
|
||||
const w = await world();
|
||||
const id = await member(w);
|
||||
const late = at(30); // inactif depuis 30 mois, mais premier passage seulement maintenant
|
||||
assert.deepEqual(await run(w, late), { warned: 1, deleted: 0, unsent: 0 });
|
||||
assert.equal(await exists(w, id), true);
|
||||
assert.match(w.mails[0].text, new RegExp(String(new Date((late + 30 * DAY) * 1000).getUTCFullYear())));
|
||||
assert.deepEqual(await run(w, late + 29 * DAY), { warned: 0, deleted: 0, unsent: 0 });
|
||||
assert.equal(await exists(w, id), true);
|
||||
assert.deepEqual(await run(w, late + 30 * DAY), { warned: 0, deleted: 1, unsent: 0 });
|
||||
assert.equal(await exists(w, id), false);
|
||||
});
|
||||
|
||||
test('une connexion après l\'avertissement sauve le compte ; l\'ancien avertissement ne vaut plus', async () => {
|
||||
const w = await world();
|
||||
const id = await member(w);
|
||||
await run(w, at(24, -30));
|
||||
assert.equal(w.mails.length, 1);
|
||||
await w.db.prepare('UPDATE users SET last_login_at = ? WHERE id = ?').run(at(24, -10), id); // il se reconnecte
|
||||
assert.deepEqual(await run(w, at(24, 5)), { warned: 0, deleted: 0, unsent: 0 });
|
||||
assert.equal(await exists(w, id), true);
|
||||
// 24 mois après sa nouvelle connexion : il faut un nouvel avertissement avant toute suppression
|
||||
const later = addMonths(at(24, -10), 24);
|
||||
assert.deepEqual(await run(w, later), { warned: 1, deleted: 0, unsent: 0 });
|
||||
assert.equal(w.mails.length, 2);
|
||||
assert.equal(await exists(w, id), true);
|
||||
});
|
||||
|
||||
test('un job récent compte comme activité', async () => {
|
||||
const w = await world();
|
||||
const id = await member(w);
|
||||
await w.db.prepare("INSERT INTO jobs(user_id, type, status, created_at) VALUES(?, 'send', 'done', ?)").run(id, at(20));
|
||||
assert.deepEqual(await run(w, at(24, -20)), { warned: 0, deleted: 0, unsent: 0 }, 'dernière activité il y a 4 mois seulement');
|
||||
assert.equal(w.mails.length, 0);
|
||||
});
|
||||
|
||||
test('jamais un administrateur, ni un compte suspendu, ni un compte actif', async () => {
|
||||
const w = await world();
|
||||
const admin = await addUser(w.db, { admin: true });
|
||||
await w.db.prepare('UPDATE users SET created_at = ?, last_login_at = ? WHERE id = ?').run(T0 - 3000 * DAY, T0 - 3000 * DAY, admin);
|
||||
const planAdmin = await member(w); await w.db.prepare("UPDATE users SET plan = 'admin' WHERE id = ?").run(planAdmin);
|
||||
const suspended = await member(w, { status: 'suspended' });
|
||||
const active = await member(w, { lastLogin: at(40) });
|
||||
const never = await member(w, { createdAt: at(40), lastLogin: null });
|
||||
await w.db.prepare('UPDATE users SET last_login_at = NULL WHERE id = ?').run(never);
|
||||
const when = at(60);
|
||||
assert.deepEqual(await run(w, when), { warned: 0, deleted: 0, unsent: 0 });
|
||||
assert.deepEqual(await run(w, when + 31 * DAY), { warned: 0, deleted: 0, unsent: 0 });
|
||||
assert.equal(w.mails.length, 0);
|
||||
for (const id of [admin, planAdmin, suspended, active, never]) assert.equal(await exists(w, id), true, `compte ${id}`);
|
||||
});
|
||||
|
||||
test('sans SMTP du serveur : avertissement journalisé, JAMAIS de suppression automatique', async () => {
|
||||
const w = await world({ smtp: false });
|
||||
const id = await member(w);
|
||||
const r = await run(w, at(30));
|
||||
assert.deepEqual(r, { warned: 0, deleted: 0, unsent: 1 });
|
||||
assert.ok(w.log.warns.some((l) => /avertissement non envoyé/.test(l) && /SYSTEM_SMTP_HOST/.test(l)));
|
||||
const [entry] = await recentAudit(w.db);
|
||||
assert.equal(entry.action, 'inactive_warning');
|
||||
assert.match(entry.detail, /NON envoyé/);
|
||||
// Passages suivants : toujours rien de supprimé, et une seule trace au journal d'audit
|
||||
for (let i = 1; i <= 5; i++) await run(w, at(30) + i * 900);
|
||||
await run(w, at(40));
|
||||
assert.equal(await exists(w, id), true);
|
||||
assert.equal((await recentAudit(w.db)).length, 1);
|
||||
});
|
||||
|
||||
test('SMTP du serveur en panne : réessai au passage suivant, pas de suppression, pas de bruit dans le journal d\'audit', async () => {
|
||||
const w = await world();
|
||||
const id = await member(w);
|
||||
let fail = true;
|
||||
w.app.createTransport = () => ({ sendMail: async (m) => { if (fail) throw new Error('421 indisponible'); w.mails.push(m); }, close() {} });
|
||||
assert.deepEqual(await run(w, at(30)), { warned: 0, deleted: 0, unsent: 1 });
|
||||
assert.deepEqual(await run(w, at(30) + 900), { warned: 0, deleted: 0, unsent: 1 });
|
||||
assert.equal((await recentAudit(w.db)).length, 0);
|
||||
assert.equal(await getSetting(w.db, id, 'inactive_warned_at'), null);
|
||||
fail = false;
|
||||
assert.deepEqual(await run(w, at(30) + 1800), { warned: 1, deleted: 0, unsent: 0 });
|
||||
assert.equal(w.mails.length, 1);
|
||||
});
|
||||
|
||||
test('durée réglable (INACTIVE_ACCOUNT_MONTHS) et désactivable (0)', async () => {
|
||||
const w = await world({ months: 12 });
|
||||
const id = await member(w);
|
||||
assert.equal((await run(w, at(12, -30))).warned, 1);
|
||||
assert.equal((await run(w, at(12))).deleted, 1);
|
||||
assert.equal(await exists(w, id), false);
|
||||
const off = await world({ months: 0 });
|
||||
const kept = await member(off);
|
||||
assert.deepEqual(await run(off, at(100)), { warned: 0, deleted: 0, unsent: 0 });
|
||||
assert.equal(await exists(off, kept), true);
|
||||
});
|
||||
|
||||
test('la suppression a les mêmes effets que celle du compte : données effacées, liste d\'opposition conservée', async () => {
|
||||
const w = await world();
|
||||
const id = await member(w);
|
||||
const p = Number((await w.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(id, T0)).lastInsertRowid);
|
||||
await w.db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, 'E', 'e@x.fr', ?)").run(p, T0);
|
||||
await w.db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('opp@x.fr', 'unsubscribe', ?)").run(T0);
|
||||
await w.db.prepare("INSERT INTO sessions(id, user_id, created_at, expires_at) VALUES('s1', ?, ?, ?)").run(id, T0, T0 + 99);
|
||||
await run(w, at(24, -30));
|
||||
await run(w, at(24));
|
||||
assert.equal((await w.db.prepare('SELECT COUNT(*) n FROM projects WHERE user_id = ?').get(id)).n, 0);
|
||||
assert.equal((await w.db.prepare('SELECT COUNT(*) n FROM prospects WHERE project_id = ?').get(p)).n, 0);
|
||||
assert.equal((await w.db.prepare('SELECT COUNT(*) n FROM sessions WHERE user_id = ?').get(id)).n, 0);
|
||||
assert.equal((await w.db.prepare('SELECT COUNT(*) n FROM blacklist').get()).n, 1);
|
||||
});
|
||||
|
||||
test('le planificateur lance le nettoyage avec son horloge injectable', async () => {
|
||||
const w = await world();
|
||||
const id = await member(w);
|
||||
let clock = at(24, -30);
|
||||
const sch = new Scheduler(w.app, { log: w.log, clock: () => clock });
|
||||
w.app.fetchRecap = async () => ({});
|
||||
await sch.tick();
|
||||
assert.equal(w.mails.length, 1);
|
||||
clock = at(24, 1);
|
||||
await sch.tick();
|
||||
assert.equal(await exists(w, id), false);
|
||||
await sch.stop();
|
||||
});
|
||||
|
||||
test('configuration : INACTIVE_ACCOUNT_MONTHS (24 par défaut) et SMTP du serveur toutes variables ensemble', () => {
|
||||
const base = { APP_URL: 'https://x.fr', SECRET_KEY: 'a'.repeat(64), GOOGLE_CLIENT_ID: 'g', GOOGLE_CLIENT_SECRET: 's', DB_DRIVER: 'sqlite' };
|
||||
const keep = { ...process.env };
|
||||
const withEnv = (extra, fn) => {
|
||||
for (const k of Object.keys(process.env)) if (/^(INACTIVE_|SYSTEM_SMTP)/.test(k)) delete process.env[k];
|
||||
Object.assign(process.env, base, extra);
|
||||
try { return fn(); } finally { for (const k of Object.keys(process.env)) if (!(k in keep)) delete process.env[k]; Object.assign(process.env, keep); }
|
||||
};
|
||||
assert.equal(withEnv({}, () => loadConfig().inactiveMonths), 24);
|
||||
assert.equal(withEnv({ INACTIVE_ACCOUNT_MONTHS: '18' }, () => loadConfig().inactiveMonths), 18);
|
||||
assert.equal(withEnv({ INACTIVE_ACCOUNT_MONTHS: '0' }, () => loadConfig().inactiveMonths), 0);
|
||||
assert.throws(() => withEnv({ INACTIVE_ACCOUNT_MONTHS: '-1' }, loadConfig), /INACTIVE_ACCOUNT_MONTHS/);
|
||||
assert.throws(() => withEnv({ INACTIVE_ACCOUNT_MONTHS: 'deux ans' }, loadConfig), /INACTIVE_ACCOUNT_MONTHS/);
|
||||
assert.equal(withEnv({}, () => loadConfig().systemSmtp), null);
|
||||
const full = { SYSTEM_SMTP_HOST: 'smtp.x.fr', SYSTEM_SMTP_USER: 'u', SYSTEM_SMTP_PASSWORD: 'p', SYSTEM_SMTP_FROM: 'n@x.fr' };
|
||||
assert.deepEqual(withEnv(full, () => loadConfig().systemSmtp), { host: 'smtp.x.fr', port: 587, user: 'u', pass: 'p', fromEmail: 'n@x.fr' });
|
||||
assert.throws(() => withEnv({ SYSTEM_SMTP_HOST: 'smtp.x.fr' }, loadConfig), /incomplètes/);
|
||||
});
|
||||
|
||||
test('politique de confidentialité : la suppression automatique est annoncée comme en place, avec la durée configurée', async () => {
|
||||
const s = await startApp({ cfg: { inactiveMonths: 18 } });
|
||||
const off = await startApp({ cfg: { inactiveMonths: 0 } });
|
||||
try {
|
||||
const page = async (x) => (await x.anon.get('/confidentialite', { headers: { accept: 'text/html' } })).text();
|
||||
const h = await page(s);
|
||||
assert.match(h, /Suppression automatique après 18 mois sans connexion ni job, avec un mail d'avertissement 30 jours avant/);
|
||||
assert.doesNotMatch(h, /pas encore en place|prévue/);
|
||||
assert.match(h, /Journal d'administration/);
|
||||
assert.match(await page(off), /Aucune suppression automatique pour inactivité/);
|
||||
const def = await startApp();
|
||||
try { assert.match(await page(def), /après 24 mois/); } finally { await def.close(); }
|
||||
} finally { await s.close(); await off.close(); }
|
||||
});
|
||||
|
||||
test('mail d\'avertissement : jamais le mot de passe ni de donnée métier, lien de connexion et d\'export', () => {
|
||||
const m = warningMail({ appUrl: 'https://ai.test' }, { email: 'ada@ex.fr' }, T0);
|
||||
assert.match(m.subject, /supprimé pour inactivité/);
|
||||
assert.match(m.text, /ada@ex\.fr/);
|
||||
assert.match(m.text, /export/i);
|
||||
assert.ok(m.text.includes('contact@tony-averty.dev'));
|
||||
});
|
||||
Loading…
Reference in a new issue