feat(acces): réserve les jobs d'analyse et de recherche aux admins en attendant la liaison de compte

Refus côté serveur avec un message explicite à quatre niveaux : route, file, worker (un job d'un non-admin déjà en base passe en erreur sans s'exécuter, de même pour un compte suspendu) et wrapper des handlers.
Un non-admin peut créer des projets (sans analyse automatique), utiliser le CRM, l'import CSV et envoyer des mails dans les plafonds existants. Bannière sur le tableau de bord.
This commit is contained in:
Tony AVERTY 2026-10-22 13:40:25 +02:00
parent 97e856189a
commit 7c9fd0be35
6 changed files with 208 additions and 4 deletions

View file

@ -429,8 +429,8 @@
try {
switch (action) {
case 'create': {
await api('/api/projects', data);
toast('Projet créé, analyse lancée');
const r = await api('/api/projects', data);
toast(r.aiBlocked ? `Projet créé. ${r.aiBlocked}` : 'Projet créé, analyse lancée');
setTimeout(() => location.reload(), 600);
break;
}

View file

@ -7,6 +7,7 @@ import { analyzePrompt, prospectPrompt, templatePrompt, followupTemplatePrompt,
import { followupCandidates, followupSubject, isBusinessHours } from './services/followup.js';
import { EMAIL_RE, createTransport, buildProspectMail, allowedToSend, makeMessageId } from './services/mailer.js';
import { unsubToken } from './crypto.js';
import { getUser, assertCanRunAi } from './users.js';
import { quotaAlerts } from './services/budget.js';
import { notify } from './services/notify.js';
import { evolutionMail } from './services/mailhtml.js';
@ -54,7 +55,10 @@ export function parseProspectLine(line) {
export function makeHandlers(app) {
const { db, cfg } = app;
// Tout appel à Claude passe par ici. Dernier garde-fou (après enqueue et le worker) : tant que la liaison
// Claude (J3) n'existe pas, seul un admin actif peut utiliser la configuration du serveur.
const claude = async (userId, o) => {
assertCanRunAi(await getUser(db, userId));
const r = await runClaude({ bin: cfg.claudeBin, ...o });
// État du quota Pro (session 5h + semaine), affiché dans la barre système
const w = rateLimitWindows(r.rateLimit);

View file

@ -2,6 +2,7 @@ import { now, getSetting, setSetting } from './db.js';
import { encrypt, encryptJson, decryptJson, verifyUnsubToken } from './crypto.js';
import { html, json, redirect, readBody, HttpError } from './http.js';
import { startLogin, finishLogin, destroySession } from './auth.js';
import { canRunAi, assertCanRunAi, AI_BLOCKED_MESSAGE } from './users.js';
import { loginPage, dashboardPage, settingsPage, unsubPage } from './views.js';
import { enqueue, latestJobs, cancelJob, usageSummary } from './services/jobs.js';
import { validateGitUrl, removeRepo } from './services/git.js';
@ -83,6 +84,7 @@ export function registerRoutes(router, app) {
}
html(res, dashboardPage({
email: session.email, projects, forgejoHost: await getSetting(db, userId, 'forgejo_host'),
aiBlocked: canRunAi(session.user) ? null : AI_BLOCKED_MESSAGE,
}));
});
@ -195,6 +197,8 @@ export function registerRoutes(router, app) {
let id;
try { id = await createProject(app, { userId, name, gitUrl }); }
catch (e) { if (await exists()) throw new HttpError(409, 'Ce dépôt est déjà un projet'); throw e; }
// L'analyse initiale utilise Claude : réservée aux admins tant que la liaison Claude n'existe pas
if (!canRunAi(session.user)) return json(res, { id, aiBlocked: AI_BLOCKED_MESSAGE });
await enqueue(db, { userId, projectId: id, type: 'analyze' });
json(res, { id });
});
@ -250,6 +254,8 @@ export function registerRoutes(router, app) {
const jobRoute = (type, paramsOf = () => ({}), guard = () => {}) => async (ctx) => {
const { req, res, session } = ctx;
// Refus côté serveur AVANT toute autre vérification : pas de job IA sans liaison Claude (enqueue le revérifie)
if (AI_JOBS.has(type)) assertCanRunAi(session.user);
const p = await project(ctx);
const b = req.headers['content-type']?.includes('json') ? await readBody(req) : {};
await guard(p, b);

View file

@ -1,13 +1,15 @@
// File de jobs en base, UN seul worker : un seul `claude` à la fois.
import { now } from '../db.js';
import { HttpError } from '../http.js';
import { getUser } from '../users.js';
import { AI_JOBS } from './budget.js';
import { getUser, assertCanRunAi, AI_BLOCKED_MESSAGE } from '../users.js';
import { waitCool } from './thermal.js';
/**
* Met un job en file pour un utilisateur. Point de passage obligé de toutes les routes et tâches de fond :
* - le projet doit appartenir à l'utilisateur (sinon 404) ;
* - un compte suspendu ne met rien en file ;
* - tant que la liaison Claude (J3) n'existe pas, seul un admin peut mettre en file un job IA.
* Sans projet, `userId` est obligatoire.
*/
export async function enqueue(db, { userId, projectId, type, params = {}, runAfter = null }) {
@ -19,6 +21,7 @@ export async function enqueue(db, { userId, projectId, type, params = {}, runAft
const user = userId == null ? null : await getUser(db, userId);
if (!user) throw new Error('enqueue : utilisateur requis');
if (user.status !== 'active') throw new HttpError(403, 'Compte suspendu');
if (AI_JOBS.has(type)) assertCanRunAi(user);
// 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)
@ -29,6 +32,22 @@ export async function enqueue(db, { userId, projectId, type, params = {}, runAft
return { id: Number(r.lastInsertRowid), existing: false };
}
/**
* Un job peut-il s'exécuter ? Renvoie la raison du refus, ou null. Revérifié par le worker à chaque
* exécution (la file peut contenir un job mis en attente avant une suspension ou un changement de rôle).
*/
export async function jobRefusal(db, job) {
const user = await getUser(db, job.user_id);
if (!user) return 'Compte supprimé';
if (user.status !== 'active') return 'Compte suspendu';
if (AI_JOBS.has(job.type) && !user.isAdmin) return AI_BLOCKED_MESSAGE;
return null;
}
export async function setProgress(db, jobId, progress) {
await db.prepare('UPDATE jobs SET progress_json = ? WHERE id = ?').run(JSON.stringify(progress), jobId);
}
/** Annule un job de l'utilisateur ; un job d'un autre compte est introuvable. */
export async function cancelJob(db, userId, jobId) {
const r = await db.prepare("UPDATE jobs SET status = 'cancelled', finished_at = ? WHERE id = ? AND user_id = ? AND status IN ('queued','running')")
@ -149,6 +168,12 @@ export class Worker {
let job = null;
const waiting = new Map(), quotaWaiting = new Map();
for (const j of due) {
// Compte suspendu ou supprimé, job IA d'un non-admin (avant la liaison Claude) : refusé sans exécution
const refusal = await jobRefusal(this.db, j);
if (refusal) {
await this.db.prepare("UPDATE jobs SET status = 'error', error = ?, finished_at = ? WHERE id = ? AND status = 'queued'").run(refusal, now(), j.id);
continue;
}
const budget = await perUser(budgets, this.budget, j.user_id);
if (budget.blocked && this.isAiJob?.(j.type)) { waiting.set(j.user_id, budget.reason); await hold(j, budget.reason); continue; }
const quota = await perUser(quotas, this.quota, j.user_id);

View file

@ -245,12 +245,13 @@ function projectItem(p, smtp, dbCfg, imap) {
</details>`;
}
export function dashboardPage({ email, projects, forgejoHost }) {
export function dashboardPage({ email, projects, forgejoHost, aiBlocked = null }) {
return layout({
title: 'Projets', email,
body: `<div class="row head">
<h1>Projets</h1>
</div>
${aiBlocked ? `<p class="card notice">${esc(aiBlocked)}. En attendant, tu peux créer des projets, gérer tes prospects (CRM, import CSV) et envoyer tes mails ; l'analyse, la recherche de prospects et les évolutions sont indisponibles.</p>` : ''}
<details class="card new anim">
<summary class="btn primary">+ Nouveau projet</summary>
<form data-action="create" class="cfg">

168
test/ai-guard.test.js Normal file
View file

@ -0,0 +1,168 @@
import { test, before, after } from 'node:test';
import assert from 'node:assert/strict';
import { resolve } from 'node:path';
import { now, setSetting } from '../src/db.js';
import { enqueue, Worker, jobRefusal, latestJobs } from '../src/services/jobs.js';
import { AI_JOBS } from '../src/services/budget.js';
import { makeHandlers } from '../src/handlers.js';
import { AI_BLOCKED_MESSAGE } from '../src/users.js';
import { startApp } from './helpers/server.js';
// Tant que la liaison Claude (J3) n'existe pas : aucun non-admin ne lance de job IA avec la configuration du serveur.
// Le refus est vérifié à chaque couche : route, file (enqueue), worker, handler.
let s, admin, user, userProject;
const AI_ROUTES = ['analyze', 'template', 'followup_template', 'prospect', 'evolution'];
before(async () => {
s = await startApp({ cfg: { claudeBin: resolve('test/fixtures/does-not-exist.js') } });
admin = await s.newUser({ email: 'admin@x.fr', admin: true });
user = await s.newUser({ email: 'simple@x.fr', admin: false });
// Projet « prêt » du non-admin : fiche, cible validée, de quoi passer toutes les gardes métier
userProject = Number((await s.db.prepare(`INSERT INTO projects(user_id, name, git_url, profile_json, target_json, target_validated, created_at)
VALUES(?, 'Mon projet', 'https://git.test/u/p.git', ?, ?, 1, ?)`).run(user.id, JSON.stringify({ resume: 'x' }), JSON.stringify({ description: 'd', secteurs: ['s'] }), now())).lastInsertRowid);
await setSetting(s.db, user.id, 'forgejo_host', 'git.test');
await setSetting(s.db, admin.id, 'forgejo_host', 'git.test');
});
after(() => s.close());
const jobCount = async (where = '1=1', ...a) => (await s.db.prepare(`SELECT COUNT(*) n FROM jobs WHERE ${where}`).get(...a)).n;
test('les jobs IA sont exactement ceux que le garde-fou connaît', () => {
assert.deepEqual([...AI_JOBS].sort(), ['analyze', 'evolution', 'followup_template', 'prospect', 'template']);
});
test('routes : un non-admin reçoit 403 « Liaison Claude requise » pour chaque job IA, sans rien créer', async () => {
for (const type of AI_ROUTES) {
const r = await user.post(`/api/projects/${userProject}/${type}`, { count: 3, level: 'rapide' });
assert.equal(r.status, 403, type);
assert.equal((await r.json()).error, AI_BLOCKED_MESSAGE, type);
}
assert.equal(await jobCount('user_id = ?', user.id), 0, 'aucun job en file');
assert.equal(AI_BLOCKED_MESSAGE, 'Liaison Claude requise (bientôt disponible)');
});
test('routes : l\'admin lance les mêmes jobs', async () => {
const pa = Number((await s.db.prepare(`INSERT INTO projects(user_id, name, git_url, profile_json, target_json, target_validated, created_at)
VALUES(?, 'Projet admin', 'https://git.test/a/p.git', ?, ?, 1, ?)`).run(admin.id, JSON.stringify({ resume: 'x' }), JSON.stringify({ description: 'd', secteurs: ['s'] }), now())).lastInsertRowid);
for (const type of AI_ROUTES) {
const r = await admin.post(`/api/projects/${pa}/${type}`, { count: 3, level: 'rapide' });
assert.equal(r.status, 200, type);
}
assert.equal(await jobCount('user_id = ?', admin.id), AI_ROUTES.length);
});
test('création de projet : permise au non-admin, sans analyse automatique', async () => {
const r = await user.post('/api/projects', { name: 'Nouveau', gitUrl: 'https://git.test/u/nouveau.git' });
assert.equal(r.status, 200);
const body = await r.json();
assert.ok(body.id);
assert.equal(body.aiBlocked, AI_BLOCKED_MESSAGE);
assert.equal(await jobCount('project_id = ?', body.id), 0, 'pas de job analyze');
// pour un admin, l'analyse part comme avant
const ra = await admin.post('/api/projects', { name: 'Nouveau admin', gitUrl: 'https://git.test/a/nouveau.git' });
const ba = await ra.json();
assert.equal(ba.aiBlocked, undefined);
assert.equal(await jobCount("project_id = ? AND type = 'analyze'", ba.id), 1);
});
test('file : enqueue refuse un job IA pour un non-admin, quel que soit l\'appelant', async () => {
for (const type of AI_JOBS) {
await assert.rejects(enqueue(s.db, { userId: user.id, projectId: userProject, type }), { status: 403, message: AI_BLOCKED_MESSAGE }, type);
}
// les jobs sans IA restent permis (envoi, relance), soumis à leurs plafonds
assert.equal((await enqueue(s.db, { userId: user.id, projectId: userProject, type: 'send', params: { count: 1 } })).existing, false);
await s.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE user_id = ?").run(user.id);
assert.equal((await enqueue(s.db, { userId: user.id, projectId: userProject, type: 'followup', params: { count: 1 } })).existing, false);
await s.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE user_id = ?").run(user.id);
});
test('CRM, import CSV et envoi : permis au non-admin', async () => {
let r = await user.post(`/api/projects/${userProject}/prospects/import`, { csv: 'email;entreprise\nclient@x.fr;Client' });
assert.equal(r.status, 200);
assert.equal((await r.json()).imported, 1);
r = await user.get(`/api/projects/${userProject}/prospects`);
assert.equal((await r.json()).total, 1);
const prospect = (await s.db.prepare('SELECT id FROM prospects WHERE project_id = ?').get(userProject)).id;
assert.equal((await user.post(`/api/prospects/${prospect}/notes`, { body: 'ok' })).status, 200);
assert.equal((await user.get(`/api/projects/${userProject}/prospects.csv`)).status, 200);
r = await user.post(`/api/projects/${userProject}/send`, { count: 1, confirm: true });
assert.equal(r.status, 200, 'l\'envoi n\'utilise pas Claude');
await s.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE user_id = ?").run(user.id);
});
test('worker : un job IA d\'un non-admin déjà en base n\'est jamais exécuté ; un envoi du même compte, si', async () => {
const ran = [];
const h = (name) => async () => { ran.push(name); return { ok: true }; };
const w = new Worker(s.db, Object.fromEntries([...AI_JOBS, 'send'].map((t) => [t, h(t)])), { thermalMax: 999, log: { error() {} } });
await s.db.prepare("UPDATE jobs SET status = 'cancelled' WHERE status = 'queued'").run(); // jobs des tests précédents
// Contournement de enqueue : insertion directe (donnée ancienne, bug, accès à la base)
for (const type of AI_JOBS) {
await s.db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, ?, ?, 'queued', ?)").run(user.id, userProject, type, now());
}
await s.db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, ?, 'send', 'queued', ?)").run(user.id, userProject, now());
while (await w.tick()) { /* vide la file */ }
assert.deepEqual(ran, ['send']);
const rows = await s.db.prepare("SELECT type, status, error FROM jobs WHERE user_id = ? AND status = 'error'").all(user.id);
assert.equal(rows.length, AI_JOBS.size);
for (const r of rows) assert.equal(r.error, AI_BLOCKED_MESSAGE);
assert.equal(await jobRefusal(s.db, { user_id: user.id, type: 'prospect' }), AI_BLOCKED_MESSAGE);
assert.equal(await jobRefusal(s.db, { user_id: user.id, type: 'send' }), null);
assert.equal(await jobRefusal(s.db, { user_id: admin.id, type: 'prospect' }), null);
assert.equal(await jobRefusal(s.db, { user_id: 999999, type: 'send' }), 'Compte supprimé');
});
test('handlers : dernier garde-fou, Claude n\'est jamais lancé pour un non-admin', async () => {
// claudeBin inexistant : si le garde-fou laissait passer, l'erreur serait un ENOENT du processus, pas ce message
const handlers = makeHandlers(s.app);
const ctx = (type) => ({ job: { id: 1, user_id: user.id, project_id: userProject, type }, params: { count: 1, level: 'rapide' }, signal: new AbortController().signal, progress: async () => {}, cancelled: async () => false, usage: { costUsd: 0, tokensIn: 0, tokensOut: 0 } });
s.app.cfg.claudeBin = resolve('test/fixtures/fake-claude.js');
await setSetting(s.db, user.id, 'notify_email', 'u@x.fr');
await setSetting(s.db, user.id, 'smtp_enc', null);
await assert.rejects(handlers.prospect(ctx('prospect')), { message: AI_BLOCKED_MESSAGE });
await assert.rejects(handlers.template(ctx('template')), { message: AI_BLOCKED_MESSAGE });
await assert.rejects(handlers.followup_template(ctx('followup_template')), { message: AI_BLOCKED_MESSAGE });
assert.equal((await s.db.prepare('SELECT COUNT(*) n FROM prospects WHERE project_id = ? AND company <> ?').get(userProject, 'Client')).n, 0, 'rien n\'a été écrit');
});
test('compte suspendu : plus aucun job, IA ou non, ni en file ni à l\'exécution', async () => {
const sus = await s.newUser({ email: 'sus@x.fr', admin: true });
const p = Number((await s.db.prepare('INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, ?, ?, ?)').run(sus.id, 'P', 'https://git.test/s/p.git', now())).lastInsertRowid);
await enqueue(s.db, { userId: sus.id, projectId: p, type: 'send', params: { count: 1 } });
await s.db.prepare("UPDATE users SET status = 'suspended' WHERE id = ?").run(sus.id);
await assert.rejects(enqueue(s.db, { userId: sus.id, projectId: p, type: 'analyze' }), { status: 403, message: 'Compte suspendu' });
await assert.rejects(enqueue(s.db, { userId: sus.id, projectId: p, type: 'send' }), { status: 403, message: 'Compte suspendu' });
const ran = [];
const w = new Worker(s.db, { send: async () => { ran.push('send'); } }, { thermalMax: 999, log: { error() {} } });
while (await w.tick()) { /* vide la file */ }
assert.deepEqual(ran, [], 'le job déjà en file d\'un compte suspendu ne part pas');
assert.equal((await latestJobs(s.db, p)).send.error, 'Compte suspendu');
});
test('interface : la bannière « liaison Claude » n\'apparaît que pour les non-admins', async () => {
const pageUser = await (await user.get('/')).text();
assert.match(pageUser, /Liaison Claude requise \(bientôt disponible\)/);
const pageAdmin = await (await admin.get('/')).text();
assert.doesNotMatch(pageAdmin, /Liaison Claude requise/);
// la température du serveur n'est pas exposée aux non-admins
assert.equal((await (await user.get('/api/system')).json()).temp, null);
});
test('serveur complet (worker et planificateur démarrés par createApp) : job admin traité, job non-admin refusé', async () => {
const full = await startApp({ worker: true, cfg: { claudeBin: resolve('test/fixtures/fake-claude.js') } });
try {
const a = await full.newUser({ email: 'adm@x.fr', admin: true });
const u = await full.newUser({ email: 'usr@x.fr', admin: false });
const mk = async (owner, url) => Number((await full.db.prepare('INSERT INTO projects(user_id, name, git_url, profile_json, target_json, created_at) VALUES(?, ?, ?, ?, ?, ?)')
.run(owner.id, 'P', url, JSON.stringify({ resume: 'x', proposition_valeur: 'y' }), JSON.stringify({ description: 'd', secteurs: ['s'] }), now())).lastInsertRowid);
const pa = await mk(a, 'https://git.test/a.git');
const pu = await mk(u, 'https://git.test/u.git');
const ja = (await enqueue(full.db, { userId: a.id, projectId: pa, type: 'template' })).id;
const ju = Number((await full.db.prepare("INSERT INTO jobs(user_id, project_id, type, status, created_at) VALUES(?, ?, 'template', 'queued', ?)").run(u.id, pu, now())).lastInsertRowid);
const status = async (id) => (await full.db.prepare('SELECT status, error FROM jobs WHERE id = ?').get(id));
for (let i = 0; i < 100 && ((await status(ja)).status === 'queued' || (await status(ju)).status === 'queued'); i++) await new Promise((r) => setTimeout(r, 100));
assert.equal((await status(ja)).status, 'done', (await status(ja)).error);
assert.deepEqual({ ...(await status(ju)) }, { status: 'error', error: AI_BLOCKED_MESSAGE });
assert.equal((await full.db.prepare('SELECT COUNT(*) n FROM templates WHERE project_id = ?').get(pu)).n, 0);
assert.equal((await full.db.prepare('SELECT COUNT(*) n FROM templates WHERE project_id = ?').get(pa)).n, 1);
} finally { await full.close(); }
});