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) => `
`; + return `Comptes et compteurs d'usage uniquement : aucun accès aux prospects, mails ni notes des utilisateurs.
+${notice ? `${esc(notice)}
` : ''} +${error ? `${esc(error)}
` : ''} +${list.total} compte(s) · page ${list.page} / ${list.pages}
+| Connexion | Plan | Statut | Créé | Dernière connexion | Liaison | Usage du mois | Actions | |
|---|---|---|---|---|---|---|---|---|
| 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).
+Actions d'administration et décisions automatiques. Lecture seule ; les adresses sont masquées ; conservé 12 mois.
+| Date | Par | Action | Compte | Détail |
|---|---|---|---|---|
| Rien pour le moment. | ||||
${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', 'secret_enc', link.secret_enc, 'SMTPCHIFFRE', 'ProjetConfidentiel', 'secret.git', 'RESUMEPRIVE', 'EntreprisePrivee', 'client@prive.fr', 'ACCROCHEPRIVEE', 'NOTEPRIVEE', 'OBJETPRIVE']) { + assert.ok(!page.includes(secret), `la page d'administration ne doit pas contenir « ${secret} »`); + } + // Les administrateurs figurent avec « Administrateur (ADMIN_EMAILS) » et sans bouton d'action sur leur propre ligne + assert.match(page, /Ton compte/); + // Seules routes /admin : aucune ne renvoie de donnée métier + const paths = s.app.router.routes.filter((r) => /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(/