diff --git a/public/app.css b/public/app.css index dd48fe6..e821274 100644 --- a/public/app.css +++ b/public/app.css @@ -366,3 +366,10 @@ form.send { margin-top: 6px; padding-top: 0; border-top: 0; } .bar > span.w-90 { width: 90%; } .bar > span.w-95 { width: 95%; } .bar > span.w-100 { width: 100%; } + +/* ---------- Administration ---------- */ +.admin-table td { vertical-align: top; } +.admin-actions { display: grid; gap: 6px; min-width: 200px; } +form.inline { display: inline-flex; gap: 6px; align-items: end; flex-wrap: wrap; margin: 0; } +.admin-actions .del summary { list-style: none; cursor: pointer; display: inline-block; } +.admin-pager { display: flex; gap: 8px; } diff --git a/src/admin.js b/src/admin.js new file mode 100644 index 0000000..85f665e --- /dev/null +++ b/src/admin.js @@ -0,0 +1,116 @@ +// 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 { HttpError } from './http.js'; +import { destroyUserSessions } from './auth.js'; +import { getUser, deleteUser, normalizeEmail } from './users.js'; +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, '!$&')}%`; + +/** 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 '!'" : ''; + const args = q ? [like(q)] : []; + const total = Number((await db.prepare(`SELECT COUNT(*) n FROM users ${where}`).get(...args)).n); + const pages = Math.max(1, Math.ceil(total / ADMIN_PAGE_SIZE)); + const p = Math.min(Math.max(1, Math.floor(Number(page)) || 1), pages); + const rows = await db.prepare(`SELECT id, email, provider, status, is_admin, plan, created_at, last_login_at, claude_link_json + FROM users ${where} ORDER BY id DESC LIMIT ? OFFSET ?`).all(...args, ADMIN_PAGE_SIZE, (p - 1) * ADMIN_PAGE_SIZE); + const accounts = []; + for (const r of rows) { + let link = null; + try { const j = r.claude_link_json ? JSON.parse(r.claude_link_json) : null; if (j?.mode) link = { mode: MODE_LABELS[j.mode] || j.mode, valid: !!j.valid }; } catch { link = null; } + const user = await getUser(db, r.id); + const usage = await usageOf(db, r.id, { at }); + 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) }, + }); + } + return { accounts, total, page: p, pages }; +} + +// Un administrateur ne touche jamais à son propre compte ni à un autre compte administrateur (leur rôle vient de ADMIN_EMAILS) +function assertManageable(actor, target, verb) { + if (!target) throw new HttpError(404, 'Compte introuvable'); + if (Number(target.id) === Number(actor.id)) throw new HttpError(400, `Tu ne peux pas ${verb} ton propre compte.`, { expose: true }); + if (target.isAdmin) throw new HttpError(400, `Ce compte est administrateur (ADMIN_EMAILS) : il ne se ${verb === 'suspendre' ? 'suspend' : 'modifie'} pas ici.`, { expose: true }); +} + +/** + * 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 + */ +export async function adminAction(app, actor, action, targetId, { plan, confirm } = {}) { + const { db } = app; + const target = await getUser(db, targetId); + if (action === 'suspend') { + assertManageable(actor, target, 'suspendre'); + await db.prepare("UPDATE users SET status = 'suspended' WHERE id = ?").run(target.id); + await destroyUserSessions(db, target.id); + app.worker?.abortUser(target.id); // le job en cours s'arrête ; les jobs en file sont refusés par le worker + await logAudit(db, { admin: actor, action: 'suspend', target }); + return `Compte suspendu : ${target.email}`; + } + if (action === 'reactivate') { + assertManageable(actor, target, 'réactiver'); + await db.prepare("UPDATE users SET status = 'active' WHERE id = ?").run(target.id); + await logAudit(db, { admin: actor, action: 'reactivate', target }); + return `Compte réactivé : ${target.email}`; + } + if (action === 'plan') { + assertManageable(actor, target, 'modifier'); + if (!PAID_PLANS.includes(plan)) throw new HttpError(400, 'Plan inconnu', { expose: true }); + await db.prepare('UPDATE users SET plan = ? WHERE id = ?').run(plan, target.id); + await logAudit(db, { admin: actor, action: plan === 'pro' ? 'plan_pro' : 'plan_free', target }); + return `Plan ${plan === 'pro' ? 'pro' : 'gratuit'} attribué à ${target.email}`; + } + if (action === 'delete') { + assertManageable(actor, target, 'supprimer'); + if (normalizeEmail(confirm) !== normalizeEmail(target.email)) throw new HttpError(400, "L'email saisi ne correspond pas à celui du compte", { expose: true }); + await logAudit(db, { admin: actor, action: 'delete', target }); // avant : la suite efface le compte + app.worker?.abortUser(target.id); + await deleteUser(app, target.id); + return 'Compte supprimé avec toutes ses données.'; + } + throw new HttpError(400, 'Action inconnue'); +} diff --git a/src/adminroutes.js b/src/adminroutes.js new file mode 100644 index 0000000..e5a211c --- /dev/null +++ b/src/adminroutes.js @@ -0,0 +1,46 @@ +// Routes du back-office. Réservées aux administrateurs : le serveur répond 404 à tous les autres (visiteurs compris), +// comme si la page n'existait pas (voir server.js, option `admin`). +import { html, redirect, readBody, HttpError } from './http.js'; +import { adminAction, listAccounts, recentAudit } from './admin.js'; +import { adminPage } from './adminviews.js'; + +const DONE = { + suspend: 'Compte suspendu : ses sessions sont fermées et ses jobs ne démarrent plus.', + reactivate: 'Compte réactivé.', + plan: 'Plan modifié.', + delete: 'Compte supprimé avec toutes ses données.', + resume_send: 'Envois rétablis.', +}; + +export function registerAdminRoutes(router, app) { + const opts = { admin: true, limit: 'admin' }; + + router.get('/admin', async ({ res, session, url }) => { + const q = (url.searchParams.get('q') || '').trim().slice(0, 100); + const done = url.searchParams.get('done'); + html(res, adminPage({ + user: session.user, q, + list: await listAccounts(app.db, { page: url.searchParams.get('page'), q }), + audit: await recentAudit(app.db), + notice: DONE[done] || null, error: url.searchParams.get('e'), + })); + }, opts); + + const act = (action, route) => router.post(`/admin/users/:id/${route}`, async ({ req, res, session, params }) => { + const b = await readBody(req); + const back = `page=${encodeURIComponent(String(b.page || '1').slice(0, 6))}${b.q ? `&q=${encodeURIComponent(String(b.q).slice(0, 100))}` : ''}`; + try { + await adminAction(app, { id: session.userId, email: session.email }, action, Number(params.id), { plan: b.plan, confirm: b.confirm }); + redirect(res, `/admin?${back}&done=${action}`); + } catch (e) { + if (!(e instanceof HttpError) || e.status >= 500) throw e; + redirect(res, `/admin?${back}&e=${encodeURIComponent(e.message)}`); + } + }, opts); + + act('suspend', 'suspend'); + act('reactivate', 'reactivate'); + act('plan', 'plan'); + act('delete', 'delete'); + act('resume_send', 'resume-send'); +} diff --git a/src/adminviews.js b/src/adminviews.js new file mode 100644 index 0000000..ac1895b --- /dev/null +++ b/src/adminviews.js @@ -0,0 +1,66 @@ +// Page /admin : comptes (identité, liaison, usage du mois) et journal d'audit. Aucune donnée métier. +import { esc } from './http.js'; +import { layout } from './views.js'; + +const fmt = (ts) => (ts ? new Date(ts * 1000).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short', timeZone: 'Europe/Paris' }) : '—'); +const PROVIDERS = { google: 'Google', apple: 'Apple' }; +const PLANS = { free: 'gratuit', pro: 'pro', admin: 'administrateur' }; + +const cap = (used, limit) => (limit == null ? `${used}` : `${used}/${limit}`); +const usageCell = (u) => `P ${cap(u.projects, u.limits.projects)} · Pr ${cap(u.prospects, u.limits.prospects)} · M ${cap(u.mails, u.limits.mails)} · IA ${cap(u.aiJobs, u.limits.aiJobs)}`; + +function actions(a, page, q, selfId) { + if (a.id === selfId) return 'Ton compte'; + if (a.isAdmin) return 'Administrateur (ADMIN_EMAILS)'; + const back = ``; + const f = (path, body) => `
${back}${body}
`; + return `
+ ${a.status === 'active' ? f('suspend', '') : f('reactivate', '')} + ${f('plan', ` `)} + ${a.sendPause ? f('resume-send', '') : ''} +
Supprimer + ${f('delete', ``)} +
+
`; +} + +export function adminPage({ user, list, audit, q = '', notice = null, error = null }) { + const nav = (p) => `/admin?page=${p}${q ? `&q=${encodeURIComponent(q)}` : ''}`; + const rows = list.accounts.map((a) => ` + ${esc(a.email)}${a.isAdmin ? ' admin' : ''} + ${esc(PROVIDERS[a.provider] || '—')} + ${esc(PLANS[a.plan] || a.plan)} + ${a.status === 'active' ? 'actif' : 'suspendu'}${a.sendPause ? '
envois en pause' : ''} + ${fmt(a.createdAt)} + ${fmt(a.lastLoginAt)} + ${a.link ? `${esc(a.link.mode)}${a.link.valid ? '' : ' invalide'}` : '—'} + ${usageCell(a.usage)} + ${actions(a, list.page, q, user.id)} + `).join(''); + const auditRows = audit.map((r) => `${fmt(r.at)}${esc(r.admin)}${esc(r.label)}${esc(r.target || '—')}${esc(r.detail || '')}`).join(''); + return layout({ + title: 'Administration', email: user.email, + body: `

Administration

+

Comptes et compteurs d'usage uniquement : aucun accès aux prospects, mails ni notes des utilisateurs.

+${notice ? `

${esc(notice)}

` : ''} +${error ? `` : ''} +
+
+

${list.total} compte(s) · page ${list.page} / ${list.pages}

+
+ + ${rows || ''} +
EmailConnexionPlanStatutCrééDernière connexionLiaisonUsage du moisActions
Aucun compte.
+

${list.page > 1 ? `Précédent` : ''} ${list.page < list.pages ? `Suivant` : ''}

+

Usage : P projets, Pr prospects, M mails du mois, IA jobs IA du mois (utilisé/plafond).

+
+
+

Journal d'audit

+

Actions d'administration et décisions automatiques. Lecture seule ; les adresses sont masquées ; conservé 12 mois.

+
+ + ${auditRows || ''} +
DateParActionCompteDétail
Rien pour le moment.
+
`, + }); +} diff --git a/src/claudelink.js b/src/claudelink.js index 143d665..58d0790 100644 --- a/src/claudelink.js +++ b/src/claudelink.js @@ -251,5 +251,6 @@ export async function lastConsent(db, userId) { export function isLinkExempt(method, pathname) { if (pathname === '/link' || pathname.startsWith('/link/')) return true; if (pathname === '/account' || pathname === '/account/delete') return true; + if (pathname === '/admin' || pathname.startsWith('/admin/')) return true; // les administrateurs gèrent les comptes même sans liaison return method === 'POST' && pathname === '/logout'; } diff --git a/src/migrations.js b/src/migrations.js index 42b1654..5d75836 100644 --- a/src/migrations.js +++ b/src/migrations.js @@ -388,6 +388,38 @@ export const MIGRATIONS = [ ) ${T}`, ], }, + { + // J5 : journal d'audit des actions d'administration et des décisions automatiques (pause d'envoi, comptes inactifs). + // Pas de clé étrangère : le journal survit à la suppression des comptes, qui n'y figurent que par un identifiant et une + // adresse masquée (minimisation). Aucune route ne le modifie ni ne l'efface ; un nettoyage périodique retire l'ancien. + name: 'journal_audit', + sqlite: [ + `CREATE TABLE admin_audit ( + id INTEGER PRIMARY KEY, + admin_id INTEGER, -- NULL = décision du système (planificateur, détection d'abus) + admin_label TEXT, + action TEXT NOT NULL, + target_id INTEGER, + target_label TEXT, -- adresse masquée + detail TEXT, + created_at INTEGER NOT NULL + )`, + 'CREATE INDEX admin_audit_at ON admin_audit(created_at)', + ], + mysql: [ + `CREATE TABLE IF NOT EXISTS admin_audit ( + id BIGINT NOT NULL AUTO_INCREMENT PRIMARY KEY, + admin_id BIGINT NULL, + admin_label VARCHAR(255), + action VARCHAR(40) NOT NULL, + target_id BIGINT NULL, + target_label VARCHAR(255), + detail VARCHAR(500), + created_at BIGINT NOT NULL, + KEY admin_audit_at (created_at) + ) ${T}`, + ], + }, ]; // ---------- Aides de la migration 2 ---------- diff --git a/src/routes.js b/src/routes.js index c9ff399..c9b9d8f 100644 --- a/src/routes.js +++ b/src/routes.js @@ -10,6 +10,7 @@ import { } from './claudelink.js'; import { loginPage } from './site/pages.js'; import { registerSiteRoutes } from './site/routes.js'; +import { registerAdminRoutes } from './adminroutes.js'; import { dashboardPage, settingsPage, unsubPage, accountPage, linkPage } from './views.js'; import { enqueue, latestJobs, cancelJob, usageSummary } from './services/jobs.js'; import { validateGitUrl, removeRepo } from './services/git.js'; @@ -49,6 +50,7 @@ export function registerRoutes(router, app) { // ---------- Public ---------- registerSiteRoutes(router, app); + registerAdminRoutes(router, app); // Déjà connecté : la page de connexion n'a rien à offrir, on va au tableau de bord router.get('/login', async ({ req, res, url }) => { if (await getSession(db, req)) return redirect(res, '/'); diff --git a/src/server.js b/src/server.js index 3ffb4bc..aab2c98 100644 --- a/src/server.js +++ b/src/server.js @@ -72,6 +72,11 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch const ip = clientIp(req, cfg.trustProxy); if (route.public && route.limit) app.limiter.enforce(route.limit, { ip }); const session = route.public ? null : await getSession(db, req); + // Back-office : 404 pour tout autre que les administrateurs (visiteurs compris), sans rien révéler + if (route.admin && !session?.user.isAdmin) { + if (url.pathname.startsWith('/api/') || !isRead || req.headers.accept?.includes('json')) throw new HttpError(404, 'Page introuvable'); + return html(res, notFoundPage({ appUrl: cfg.appUrl }), 404); + } if (!route.public) { if (!session) { // Visiteur sur la racine : le site public. Connecté, la même adresse mène au tableau de bord. diff --git a/src/site/seo.js b/src/site/seo.js index 6eeb2d4..1101e93 100644 --- a/src/site/seo.js +++ b/src/site/seo.js @@ -5,7 +5,7 @@ import { absoluteUrl } from './layout.js'; export const INDEXABLE_PATHS = ['/', '/fonctionnement', '/tarifs', '/mentions-legales', '/confidentialite', '/cgu']; // Pages d'application : jamais explorées (le noindex des pages est posé en plus, par en-tête et par balise) -export const DISALLOWED_PATHS = ['/account', '/settings', '/link', '/api/', '/auth/', '/u/', '/logout']; +export const DISALLOWED_PATHS = ['/admin', '/account', '/settings', '/link', '/api/', '/auth/', '/u/', '/logout']; export function robotsTxt(appUrl) { return [ diff --git a/src/views.js b/src/views.js index 018c7c4..25c8c81 100644 --- a/src/views.js +++ b/src/views.js @@ -109,6 +109,7 @@ export function accountPage({ user, error, link = null, consent = null, notice =
Email
${esc(user.email)}
Connexion
${esc(PROVIDER_NAMES[user.provider] || '—')}
+ ${user.isAdmin ? '

Administration

' : ''} ${notice ? `

${esc(notice.text)}

` : ''} ${usagePanel(usage)} diff --git a/test/admin.test.js b/test/admin.test.js new file mode 100644 index 0000000..afdd44b --- /dev/null +++ b/test/admin.test.js @@ -0,0 +1,255 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync, readdirSync } from 'node:fs'; +import { join } from 'node:path'; +import { now } from '../src/db.js'; +import { encrypt } from '../src/crypto.js'; +import { maskEmail, logAudit, purgeAudit, recentAudit } from '../src/admin.js'; +import { getSession } from '../src/auth.js'; +import { ADMIN_PAGE_SIZE } from '../src/limits.js'; +import { Worker, enqueue } from '../src/services/jobs.js'; +import { startApp } from './helpers/server.js'; + +// Back-office : réservé aux administrateurs (404 pour les autres), actions journalisées, garde-fous sur les administrateurs, +// aucune donnée métier. + +const html = { headers: { accept: 'text/html' } }; +const ADMIN_ROUTES = [ + ['GET', '/admin'], ['GET', '/admin?page=2&q=x'], ['POST', '/admin/users/1/suspend'], ['POST', '/admin/users/1/reactivate'], + ['POST', '/admin/users/1/plan'], ['POST', '/admin/users/1/delete'], ['POST', '/admin/users/1/resume-send'], +]; +const form = (u, path, body = {}, o = {}) => u.post(path, body, { form: true, ...o }); +const where = (r) => decodeURIComponent(r.headers.get('location') || ''); + +test('non-admin, visiteur et administrateur : 404 sauf pour l\'administrateur, pour toutes les routes', async () => { + const s = await startApp(); + try { + const user = await s.newUser({ admin: false }); + const admin = await s.newUser({ admin: true }); + for (const [method, path] of ADMIN_ROUTES) { + for (const [who, c] of [['visiteur', s.anon], ['utilisateur', user]]) { + const r = method === 'GET' ? await c.get(path, html) : await form(c, path); + assert.equal(r.status, 404, `${who} ${method} ${path}`); + const j = method === 'GET' ? await c.get(path) : await c.post(path, {}); + assert.equal(j.status, 404, `${who} ${method} ${path} (JSON)`); + assert.equal(r.headers.get('location'), null, 'aucune redirection vers la connexion (rien n\'est révélé)'); + } + } + // Aucune trace de la page dans la réponse 404, et l'administrateur la voit + const denied = await (await user.get('/admin', html)).text(); + assert.doesNotMatch(denied, /Administration|Journal d'audit/); + assert.equal((await admin.get('/admin', html)).status, 200); + // Un utilisateur sans liaison Claude mais admin y accède aussi (pas de redirection vers /link) + const bare = await s.newUser({ admin: true, link: null }); + assert.equal((await bare.get('/admin', html)).status, 200); + // Le lien « Administration » n'est visible que des administrateurs + assert.match(await (await admin.get('/account', html)).text(), /href="\/admin"/); + assert.doesNotMatch(await (await user.get('/account', html)).text(), /href="\/admin"/); + // Jamais indexé ni exploré + assert.match(await (await s.anon.get('/robots.txt')).text(), /Disallow: \/admin\n/); + } finally { await s.close(); } +}); + +test('administration : une origine étrangère est refusée (anti-CSRF) et le débit est limité', async () => { + const s = await startApp({ rateLimit: true }); + try { + const admin = await s.newUser({ admin: true }); + const target = await s.newUser({ admin: false }); + const r = await form(admin, `/admin/users/${target.id}/suspend`, {}, { origin: 'https://evil.example' }); + assert.equal(r.status, 403); + assert.equal((await s.db.prepare('SELECT status FROM users WHERE id = ?').get(target.id)).status, 'active'); + for (let i = 0; i < 120; i++) await admin.get('/admin', html); + assert.equal((await admin.get('/admin', html)).status, 429); + } finally { await s.close(); } +}); + +test('liste des comptes : identité, plan, statut, dates, mode de liaison et usage ; jamais un secret ni une donnée métier', async () => { + const s = await startApp(); + try { + const admin = await s.newUser({ admin: true, email: 'tony@x.fr' }); + const SECRET = 'sk-ant-api03-SECRETSECRETSECRETSECRET1234'; + const link = { v: 1, mode: 'api_key', valid: true, last4: '1234', secret_enc: encrypt(s.app.cfg.secretKey, SECRET) }; + const bob = await s.newUser({ admin: false, email: 'bob@exemple.fr', link }); + await s.db.prepare('UPDATE users SET last_login_at = ? WHERE id = ?').run(1_800_000_000, bob.id); + const pid = Number((await s.db.prepare("INSERT INTO projects(user_id, name, git_url, profile_json, created_at) VALUES(?, 'ProjetConfidentiel', 'https://git.test/b/secret.git', ?, ?)").run(bob.id, JSON.stringify({ resume: 'RESUMEPRIVE' }), now())).lastInsertRowid); + await s.db.prepare("INSERT INTO prospects(project_id, company, email, hook, created_at) VALUES(?, 'EntreprisePrivee', 'client@prive.fr', 'ACCROCHEPRIVEE', ?)").run(pid, now()); + const prospect = (await s.db.prepare('SELECT id FROM prospects WHERE project_id = ?').get(pid)).id; + await s.db.prepare("INSERT INTO prospect_notes(prospect_id, body, created_at) VALUES(?, 'NOTEPRIVEE', ?)").run(prospect, now()); + await s.db.prepare("INSERT INTO mail_log(project_id, prospect_id, email, sent_at, subject) VALUES(?, ?, 'client@prive.fr', ?, 'OBJETPRIVE')").run(pid, prospect, now()); + await s.db.prepare("INSERT INTO user_settings(user_id, `key`, value) VALUES(?, 'smtp_enc', 'SMTPCHIFFRE')").run(bob.id); + + const page = await (await admin.get('/admin', html)).text(); + for (const f of ['bob@exemple.fr', 'tony@x.fr', 'Google', 'gratuit', 'actif', 'Clé API Anthropic', 'P 1/1', 'Pr 1/50', 'M 0/100', 'IA 0/5', '15/01/2027']) assert.ok(page.includes(f), f); + for (const secret of [SECRET, 'SECRETSECRET', '1234 /admin/.test(r.re.source)).map((r) => r.re.source); + assert.ok(paths.length >= 6); + for (const p of paths) assert.doesNotMatch(p, /prospect|mail|note|project/i); + } finally { await s.close(); } +}); + +test('liste paginée et recherche par email (caractères spéciaux neutralisés)', async () => { + const s = await startApp(); + try { + const admin = await s.newUser({ admin: true }); + for (let i = 0; i < ADMIN_PAGE_SIZE + 5; i++) await s.newUser({ admin: false, email: `membre${String(i).padStart(2, '0')}@liste.fr` }); + await s.newUser({ admin: false, email: '100%_vrai@liste.fr' }); + const rows = (h) => (h.match(/\s*[^<]*@/g) || []).length; + const p1 = await (await admin.get('/admin', html)).text(); + assert.equal(rows(p1), ADMIN_PAGE_SIZE); + assert.match(p1, /page 1 \/ 2/); + assert.match(p1, /href="\/admin\?page=2"/); + const p2 = await (await admin.get('/admin?page=2', html)).text(); + assert.equal(rows(p2), 1 + ADMIN_PAGE_SIZE + 5 + 1 - ADMIN_PAGE_SIZE); + assert.match(p2, /Précédent/); + assert.equal(rows(await (await admin.get('/admin?page=99', html)).text()), rows(p2), 'page hors bornes ramenée à la dernière'); + assert.equal(rows(await (await admin.get('/admin?page=abc', html)).text()), ADMIN_PAGE_SIZE); + const found = await (await admin.get('/admin?q=membre07', html)).text(); + assert.equal(rows(found), 1); + assert.ok(found.includes('membre07@liste.fr')); + const special = await (await admin.get('/admin?q=' + encodeURIComponent('100%_'), html)).text(); + assert.equal(rows(special), 1, '% et _ sont cherchés littéralement'); + assert.equal(rows(await (await admin.get('/admin?q=%25', html)).text()), 1); + } finally { await s.close(); } +}); + +test('suspendre : sessions fermées, connexion refusée, jobs en file refusés, audit ; réactiver rétablit', async () => { + const s = await startApp(); + try { + const admin = await s.newUser({ admin: true, email: 'chef@x.fr' }); + const bob = await s.newUser({ admin: false, email: 'bob@x.fr', link: { v: 1, mode: 'api_key', valid: true } }); + const pid = Number((await s.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(bob.id, now())).lastInsertRowid); + const job = (await enqueue(s.db, { userId: bob.id, projectId: pid, type: 'template' })).id; + assert.ok(await getSession(s.db, { headers: { cookie: bob.cookie } })); + const r = await form(admin, `/admin/users/${bob.id}/suspend`, { page: '1' }); + assert.equal(r.status, 303); + assert.match(where(r), /^\/admin\?page=1&done=suspend$/); + assert.equal((await s.db.prepare('SELECT status FROM users WHERE id = ?').get(bob.id)).status, 'suspended'); + assert.equal(await getSession(s.db, { headers: { cookie: bob.cookie } }), null, 'sa session est fermée'); + assert.equal((await bob.get('/api/system')).status, 401); + // Son job en file ne s'exécute pas + const w = new Worker(s.db, { template: async () => { throw new Error('ne doit pas tourner'); } }, { log: { error() {} } }); + await w.tick(); + assert.equal((await s.db.prepare('SELECT status, error FROM jobs WHERE id = ?').get(job)).error, 'Compte suspendu'); + await assert.rejects(enqueue(s.db, { userId: bob.id, projectId: pid, type: 'prospect' }), { status: 403 }); + // La page le montre, puis la réactivation + assert.match(await (await admin.get('/admin?done=suspend', html)).text(), /suspendu/); + assert.equal((await form(admin, `/admin/users/${bob.id}/reactivate`)).status, 303); + assert.equal((await s.db.prepare('SELECT status FROM users WHERE id = ?').get(bob.id)).status, 'active'); + const log = await recentAudit(s.db); + assert.deepEqual(log.map((l) => l.action), ['reactivate', 'suspend']); + assert.equal(log[1].admin, 'chef@x.fr'); + assert.equal(log[1].target, 'b***@x.fr', 'adresse masquée dans le journal'); + assert.equal(log[1].targetId, bob.id); + } finally { await s.close(); } +}); + +test('un administrateur ne peut ni se suspendre, ni se supprimer, ni toucher un autre administrateur', async () => { + const s = await startApp(); + try { + const a = await s.newUser({ admin: true, email: 'a@x.fr' }); + const b = await s.newUser({ admin: true, email: 'b@x.fr' }); + await s.newUser({ admin: false, email: 'u@x.fr' }); + const refusals = [ + [a.id, 'suspend', {}, /propre compte/], [a.id, 'delete', { confirm: 'a@x.fr' }, /propre compte/], [a.id, 'plan', { plan: 'free' }, /propre compte/], + [b.id, 'suspend', {}, /administrateur/], [b.id, 'delete', { confirm: 'b@x.fr' }, /administrateur/], [b.id, 'plan', { plan: 'pro' }, /administrateur/], + ]; + for (const [id, action, body, re] of refusals) { + const r = await form(a, `/admin/users/${id}/${action}`, body); + assert.equal(r.status, 303, action); + const loc = where(r); + assert.match(loc, /[?&]e=/, `${action} sur ${id} : ${loc}`); + assert.match(loc, re, `${action} sur ${id}`); + } + for (const id of [a.id, b.id]) { + const row = await s.db.prepare('SELECT status FROM users WHERE id = ?').get(id); + assert.equal(row?.status, 'active', `compte ${id} intact`); + } + assert.deepEqual(await recentAudit(s.db), [], 'un refus n\'est pas une action : rien au journal'); + assert.equal(await getSession(s.db, { headers: { cookie: a.cookie } }) !== null, true, 'la session de l\'admin reste ouverte'); + } finally { await s.close(); } +}); + +test('plan : gratuit / pro attribuables, rien d\'autre ; le plan pro lève les plafonds', async () => { + const s = await startApp(); + try { + const admin = await s.newUser({ admin: true }); + const bob = await s.newUser({ admin: false }); + assert.equal((await form(admin, `/admin/users/${bob.id}/plan`, { plan: 'pro' })).status, 303); + assert.equal((await s.db.prepare('SELECT plan FROM users WHERE id = ?').get(bob.id)).plan, 'pro'); + for (const bad of ['admin', 'enterprise', '', 'PRO ']) { + const loc = where(await form(admin, `/admin/users/${bob.id}/plan`, { plan: bad })); + assert.match(loc, /Plan inconnu/, bad); + } + assert.equal((await s.db.prepare('SELECT plan FROM users WHERE id = ?').get(bob.id)).plan, 'pro'); + await form(admin, `/admin/users/${bob.id}/plan`, { plan: 'free' }); + assert.deepEqual((await recentAudit(s.db)).map((l) => l.action), ['plan_free', 'plan_pro']); + assert.match(await (await admin.get('/admin?done=plan', html)).text(), /Plan modifié/); + assert.equal(where(await form(admin, '/admin/users/99999/plan', { plan: 'pro' })).includes('introuvable'), true); + } finally { await s.close(); } +}); + +test('suppression : confirmation par saisie de l\'email, mêmes effets que la suppression du compte, audit conservé', async () => { + const s = await startApp(); + try { + const admin = await s.newUser({ admin: true }); + const bob = await s.newUser({ admin: false, email: 'bob@exemple.fr' }); + const pid = Number((await s.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'u', ?)").run(bob.id, now())).lastInsertRowid); + await s.db.prepare("INSERT INTO prospects(project_id, company, email, created_at) VALUES(?, 'E', 'e@x.fr', ?)").run(pid, now()); + await s.db.prepare("INSERT INTO blacklist(email, reason, created_at) VALUES('opp@x.fr', 'unsubscribe', ?)").run(now()); + for (const bad of ['', 'autre@exemple.fr', 'bob@exemple.f']) { + assert.match(where(await form(admin, `/admin/users/${bob.id}/delete`, { confirm: bad })), /ne correspond pas/, bad); + } + assert.ok(await s.db.prepare('SELECT 1 x FROM users WHERE id = ?').get(bob.id), 'toujours là sans la bonne saisie'); + const ok = await form(admin, `/admin/users/${bob.id}/delete`, { confirm: ' Bob@Exemple.fr ' }); + assert.match(where(ok), /done=delete/); + for (const [t, col] of [['users', 'id'], ['projects', 'user_id'], ['sessions', 'user_id'], ['jobs', 'user_id']]) { + assert.equal((await s.db.prepare(`SELECT COUNT(*) n FROM ${t} WHERE ${col} = ?`).get(bob.id)).n, 0, t); + } + assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM prospects WHERE project_id = ?').get(pid)).n, 0); + assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM blacklist').get()).n, 1, 'la liste d\'opposition est conservée, comme à la suppression du compte'); + const [entry] = await recentAudit(s.db); + assert.equal(entry.action, 'delete'); + assert.equal(entry.target, 'b***@exemple.fr'); + assert.ok(!JSON.stringify(entry).includes('bob@exemple.fr'), 'l\'adresse complète n\'est pas gardée'); + } finally { await s.close(); } +}); + +test('journal d\'audit : en lecture seule, aucune route ni requête ne le modifie, purge des lignes anciennes', async () => { + const s = await startApp(); + try { + const admin = await s.newUser({ admin: true }); + const target = { id: 5, email: 'jean@exemple.fr' }; + await logAudit(s.db, { admin: { id: admin.id, email: 'a@x.fr' }, action: 'suspend', target, at: now() - 400 * 86400 }); + await logAudit(s.db, { action: 'abuse_pause', target, detail: 'x'.repeat(900), at: now() }); + await assert.rejects(logAudit(s.db, { action: 'inconnue', target }), /inconnue/); + const page = await (await admin.get('/admin', html)).text(); + assert.match(page, /Journal d'audit/); + assert.match(page, /Envois mis en pause/); + assert.match(page, /système/); + assert.doesNotMatch(page, /jean@exemple\.fr/); + assert.equal((await recentAudit(s.db)).find((l) => l.action === 'abuse_pause').detail.length, 500, 'détail borné'); + // La section du journal ne propose aucun formulaire + const section = page.slice(page.indexOf("Journal d'audit")); + assert.doesNotMatch(section, / /audit/.test(r.re.source))); + // Dans le code, seule la purge ancienne supprime des lignes ; rien ne les met à jour + const files = []; + const walk = (d) => { for (const e of readdirSync(d, { withFileTypes: true })) { const p = join(d, e.name); e.isDirectory() ? walk(p) : p.endsWith('.js') && files.push(p); } }; + walk('src'); + 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); + } + 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'); + assert.equal(maskEmail('a@b.fr'), 'a***@b.fr'); + assert.equal(maskEmail('sans-arobase'), 's***'); + } finally { await s.close(); } +}); diff --git a/test/schema.test.js b/test/schema.test.js index 089a99f..345ea6a 100644 --- a/test/schema.test.js +++ b/test/schema.test.js @@ -55,7 +55,7 @@ function parseDdl(statements) { const ddl = (dialect) => parseDdl(MIGRATIONS.flatMap((m) => m[dialect])); // Tables volontairement hors du périmètre d'un utilisateur : liste d'opposition (RGPD) et états OAuth éphémères -const NOT_OWNED = new Set(['blacklist', 'oauth_states', 'users']); +const NOT_OWNED = new Set(['blacklist', 'oauth_states', 'users', 'admin_audit']); const shape = (tables) => Object.fromEntries([...tables].map(([t, v]) => [t, { columns: [...v.columns].sort(), refs: v.refs }])); test('schémas SQLite et MySQL : mêmes tables et mêmes colonnes', () => {