feat(liaison): accès par utilisateur, secret chiffré, garde unique des jobs
- clé API (vérifiée sans coût) ou jeton d'abonnement avec consentement horodaté et versionné, chiffrés AES-256-GCM - mode serveur réservé aux admins ; délier efface le secret et annule les jobs en file - le secret est relu à chaque exécution depuis le user_id du job, transmis au seul processus enfant - garde appliquée dans enqueue, le worker et le wrapper d'exécution
This commit is contained in:
parent
23da49fdc7
commit
4158f6f9d6
4 changed files with 296 additions and 30 deletions
255
src/claudelink.js
Normal file
255
src/claudelink.js
Normal file
|
|
@ -0,0 +1,255 @@
|
|||
// Liaison Claude de chaque utilisateur : clé API Anthropic, jeton d'abonnement (claude setup-token) ou, pour les admins,
|
||||
// configuration du CLI du serveur. Le secret est chiffré (AES-256-GCM) dans users.claude_link_json ; il ne sort jamais
|
||||
// de ce module que sous forme d'environnement du processus enfant, et toujours à partir du user_id du job.
|
||||
import { execFile } from 'node:child_process';
|
||||
import { promisify } from 'node:util';
|
||||
import { now, getSetting, setSetting } from './db.js';
|
||||
import { encrypt, decrypt } from './crypto.js';
|
||||
import { HttpError } from './http.js';
|
||||
import { getUser } from './users.js';
|
||||
import { runClaude } from './services/claude.js';
|
||||
import { buildChildEnv } from './services/sandbox.js';
|
||||
import { AI_JOBS } from './services/budget.js';
|
||||
|
||||
const execFileP = promisify(execFile);
|
||||
|
||||
export const MODES = { api_key: 'api_key', subscription_token: 'subscription_token', server: 'server' };
|
||||
export const MODE_LABELS = {
|
||||
api_key: 'Clé API Anthropic',
|
||||
subscription_token: 'Abonnement Claude (jeton)',
|
||||
server: 'Claude du serveur',
|
||||
};
|
||||
export const LINK_REQUIRED_MESSAGE = 'Relie ton accès Claude pour utiliser cette fonction';
|
||||
export const LINK_INVALID_MESSAGE = "Ta liaison Claude n'est plus valide : teste-la ou relie-la de nouveau (Mon compte)";
|
||||
export const CLI_DISABLED_MESSAGE = "Le mode abonnement est désactivé sur ce service : relie une clé API";
|
||||
export const SERVER_MODE_MESSAGE = 'Le mode « Claude du serveur » est réservé aux administrateurs';
|
||||
|
||||
// Texte de l'avertissement affiché avant le mode abonnement. Toute modification change la version : l'acceptation
|
||||
// enregistrée en base indique à quelle version du texte l'utilisateur a consenti.
|
||||
export const CONSENT_VERSION = '2026-10-22.1';
|
||||
export const CONSENT_TEXT = [
|
||||
"Utiliser un abonnement Claude (Pro, Max) à travers une application tierce peut contrevenir aux conditions d'utilisation d'Anthropic et entraîner la suspension ou la fermeture de ton compte Claude.",
|
||||
'AiTools ne peut en être tenu responsable. Tu utilises ton abonnement à tes propres risques.',
|
||||
"La clé API Anthropic reste l'option recommandée : elle est prévue pour cet usage.",
|
||||
];
|
||||
export const CONSENT_CHECKBOX = "J'ai compris et j'accepte ce risque";
|
||||
|
||||
const API_KEY_RE = /^sk-ant-[A-Za-z0-9_-]{20,400}$/;
|
||||
const TOKEN_RE = /^[A-Za-z0-9_.-]{20,800}$/;
|
||||
const MODELS_URL = 'https://api.anthropic.com/v1/models';
|
||||
const SECRET_ENV = { api_key: 'ANTHROPIC_API_KEY', subscription_token: 'CLAUDE_CODE_OAUTH_TOKEN' };
|
||||
|
||||
const truthy = (v) => v === true || v === 'true' || v === 'on' || v === '1' || v === 1;
|
||||
|
||||
async function readLink(db, userId) {
|
||||
const row = await db.prepare('SELECT claude_link_json FROM users WHERE id = ?').get(Number(userId));
|
||||
if (!row?.claude_link_json) return null;
|
||||
try { return JSON.parse(row.claude_link_json); } catch { return null; }
|
||||
}
|
||||
|
||||
async function writeLink(db, userId, link) {
|
||||
await db.prepare('UPDATE users SET claude_link_json = ? WHERE id = ?').run(link ? JSON.stringify(link) : null, Number(userId));
|
||||
}
|
||||
|
||||
/** Forme exposée à l'interface : jamais le secret, seulement ses 4 derniers caractères pour la clé API. */
|
||||
export function publicLink(link) {
|
||||
if (!link?.mode) return null;
|
||||
return {
|
||||
mode: link.mode, label: MODE_LABELS[link.mode], valid: !!link.valid,
|
||||
linkedAt: link.linked_at ?? null, validatedAt: link.validated_at ?? null, lastTestAt: link.last_test_at ?? null,
|
||||
last4: link.mode === 'api_key' ? link.last4 ?? null : null,
|
||||
consentAt: link.consent?.at ?? null, consentVersion: link.consent?.version ?? null,
|
||||
};
|
||||
}
|
||||
|
||||
export async function getLinkState(db, userId) {
|
||||
return publicLink(await readLink(db, userId));
|
||||
}
|
||||
|
||||
// Quota d'abonnement et alertes : propres à un compte Claude, repartent de zéro quand la liaison change
|
||||
async function resetQuotaState(db, userId) {
|
||||
await setSetting(db, userId, 'claude_rate_limit_json', null);
|
||||
await setSetting(db, userId, 'claude_quota_notified_json', null);
|
||||
}
|
||||
|
||||
/**
|
||||
* Pourquoi cet utilisateur ne peut pas lancer de job IA (message destiné à l'écran), ou null s'il le peut.
|
||||
* Garde unique, appelée par les routes, enqueue, le worker et le wrapper claude().
|
||||
*/
|
||||
export async function aiRefusal(db, userId, { cliModeEnabled = true } = {}) {
|
||||
const user = await getUser(db, userId);
|
||||
if (!user) return 'Compte supprimé';
|
||||
if (user.status !== 'active') return 'Compte suspendu';
|
||||
const link = await readLink(db, userId);
|
||||
if (!link?.mode || !MODES[link.mode]) return LINK_REQUIRED_MESSAGE;
|
||||
if (!link.valid) return LINK_INVALID_MESSAGE;
|
||||
if (link.mode === MODES.server && !user.isAdmin) return SERVER_MODE_MESSAGE;
|
||||
if (link.mode === MODES.subscription_token && !cliModeEnabled) return CLI_DISABLED_MESSAGE;
|
||||
return null;
|
||||
}
|
||||
|
||||
export async function assertCanRunAi(db, userId, opts) {
|
||||
const msg = await aiRefusal(db, userId, opts);
|
||||
if (msg) throw new HttpError(403, msg);
|
||||
}
|
||||
|
||||
/** L'utilisateur a-t-il une liaison utilisable ? Sert à l'onboarding bloquant. */
|
||||
export async function hasUsableLink(db, userId, opts) {
|
||||
return (await aiRefusal(db, userId, opts)) === null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Identifiants d'exécution du job : lus dans la ligne de CET utilisateur, jamais ailleurs.
|
||||
* @returns {{mode:string, secretEnv:Record<string,string>, serverConfig:boolean}}
|
||||
*/
|
||||
export async function resolveCredentials(app, userId) {
|
||||
await assertCanRunAi(app.db, userId, { cliModeEnabled: app.cfg.cliModeEnabled !== false });
|
||||
const link = await readLink(app.db, userId);
|
||||
if (link.mode === MODES.server) return { mode: link.mode, secretEnv: {}, serverConfig: true };
|
||||
let secret;
|
||||
try { secret = decrypt(app.cfg.secretKey, link.secret_enc); }
|
||||
catch { throw new HttpError(403, 'Secret de liaison illisible : relie de nouveau ton accès Claude'); }
|
||||
if (!secret) throw new HttpError(403, LINK_REQUIRED_MESSAGE);
|
||||
return { mode: link.mode, secretEnv: { [SECRET_ENV[link.mode]]: secret }, serverConfig: false };
|
||||
}
|
||||
|
||||
// ---------- Validation ----------
|
||||
|
||||
/**
|
||||
* Valide une clé API par un appel qui ne consomme aucun token : GET /v1/models.
|
||||
* 401/403 : refusée ; erreur réseau ou réponse inattendue : message distinct (la clé n'est pas jugée).
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function validateApiKey(key, fetchFn = fetch) {
|
||||
let r;
|
||||
try {
|
||||
r = await fetchFn(MODELS_URL, {
|
||||
headers: { 'x-api-key': key, 'anthropic-version': '2023-06-01' },
|
||||
signal: AbortSignal.timeout(10_000),
|
||||
});
|
||||
} catch {
|
||||
throw new HttpError(502, "Impossible de joindre Anthropic pour vérifier la clé (réseau). Réessaie dans un instant.");
|
||||
}
|
||||
if (r.status === 401 || r.status === 403) throw new HttpError(400, 'Clé API refusée par Anthropic');
|
||||
if (!r.ok) throw new HttpError(502, `Anthropic ne répond pas normalement (HTTP ${r.status}) : la clé n'a pas pu être vérifiée. Réessaie plus tard.`);
|
||||
}
|
||||
|
||||
// Appel minimal du CLI avec le jeton (modèle le plus petit, 1 tour, aucun outil). Ce n'est PAS gratuit : quelques tokens
|
||||
// sont décomptés de l'abonnement. Aucune commande du CLI ne vérifie un jeton sans appel au modèle.
|
||||
async function validateSubscriptionToken(app, token) {
|
||||
let r;
|
||||
try {
|
||||
r = await runClaude({
|
||||
bin: app.cfg.claudeBin, prompt: 'Réponds uniquement : ok', model: 'haiku', maxTurns: 1, tools: [], timeoutMs: 90_000,
|
||||
sandbox: app.cfg.sandbox, secretEnv: { CLAUDE_CODE_OAUTH_TOKEN: token },
|
||||
});
|
||||
} catch (e) {
|
||||
throw new HttpError(502, `Le CLI Claude n'a pas pu être lancé sur le serveur : ${String(e.message).slice(0, 160)}`);
|
||||
}
|
||||
if (r.ok) return;
|
||||
if (/auth|login|token|credential|401|403|invalid|expired|unauthor/i.test(`${r.text} ${r.subtype}`)) {
|
||||
throw new HttpError(400, 'Jeton refusé par Claude (invalide ou expiré)');
|
||||
}
|
||||
throw new HttpError(502, "Le jeton n'a pas pu être vérifié (réponse inattendue du CLI). Réessaie plus tard.");
|
||||
}
|
||||
|
||||
// ---------- Liaison ----------
|
||||
|
||||
async function saveLink(app, userId, link) {
|
||||
const t = now();
|
||||
await writeLink(app.db, userId, { v: 1, valid: true, linked_at: t, validated_at: t, last_test_at: t, ...link });
|
||||
await resetQuotaState(app.db, userId);
|
||||
}
|
||||
|
||||
/** Mode A : clé API. Validée, chiffrée, jamais réaffichée. */
|
||||
export async function linkApiKey(app, userId, apiKey) {
|
||||
const key = String(apiKey ?? '').trim();
|
||||
if (!API_KEY_RE.test(key)) throw new HttpError(400, 'Clé API invalide (elle commence par sk-ant-)');
|
||||
await (app.validateApiKey || validateApiKey)(key, app.fetch || fetch);
|
||||
await saveLink(app, userId, { mode: MODES.api_key, secret_enc: encrypt(app.cfg.secretKey, key), last4: key.slice(-4) });
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode B : jeton d'abonnement (claude setup-token, généré par l'utilisateur sur sa machine).
|
||||
* Le consentement est vérifié AVANT tout (sans case cochée : 400, rien n'est stocké ni validé).
|
||||
*/
|
||||
export async function linkSubscriptionToken(app, userId, { token, accept }) {
|
||||
if (app.cfg.cliModeEnabled === false) throw new HttpError(403, CLI_DISABLED_MESSAGE);
|
||||
if (!truthy(accept)) throw new HttpError(400, `Tu dois cocher « ${CONSENT_CHECKBOX} » pour utiliser ton abonnement`);
|
||||
const tok = String(token ?? '').trim();
|
||||
if (/^sk-ant-api/.test(tok)) throw new HttpError(400, "Ceci est une clé API : utilise l'option « Clé API Anthropic »");
|
||||
if (!TOKEN_RE.test(tok)) throw new HttpError(400, 'Jeton invalide : colle le jeton affiché par « claude setup-token », en entier');
|
||||
await (app.validateToken || ((t) => validateSubscriptionToken(app, t)))(tok);
|
||||
const consent = { at: now(), version: CONSENT_VERSION };
|
||||
await saveLink(app, userId, { mode: MODES.subscription_token, secret_enc: encrypt(app.cfg.secretKey, tok), consent });
|
||||
// Trace d'acceptation conservée même si l'utilisateur délie ensuite (supprimée avec le compte)
|
||||
await setSetting(app.db, userId, 'claude_cli_consent_json', JSON.stringify(consent));
|
||||
}
|
||||
|
||||
/** Mode « Claude du serveur » : administrateurs seulement, aucun secret stocké. */
|
||||
export async function linkServer(app, userId) {
|
||||
const user = await getUser(app.db, userId);
|
||||
if (!user?.isAdmin) throw new HttpError(403, SERVER_MODE_MESSAGE);
|
||||
await saveLink(app, userId, { mode: MODES.server });
|
||||
}
|
||||
|
||||
/**
|
||||
* Délie : supprime le secret chiffré, annule les jobs IA en file ou en cours de CET utilisateur.
|
||||
* @returns {Promise<number>} jobs annulés
|
||||
*/
|
||||
export async function unlink(app, userId) {
|
||||
await writeLink(app.db, userId, null);
|
||||
await resetQuotaState(app.db, userId);
|
||||
const types = [...AI_JOBS];
|
||||
const r = await app.db.prepare(`UPDATE jobs SET status = 'cancelled', finished_at = ?
|
||||
WHERE user_id = ? AND status IN ('queued','running') AND type IN (${types.map(() => '?').join(', ')})`).run(now(), Number(userId), ...types);
|
||||
app.worker?.abortUserAi(userId);
|
||||
return r.changes || 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Teste la liaison. Une réponse d'authentification négative invalide la liaison ; une erreur réseau ou du CLI ne la touche pas.
|
||||
* @returns {Promise<{ok:boolean, message:string}>}
|
||||
*/
|
||||
export async function testLink(app, userId) {
|
||||
const link = await readLink(app.db, userId);
|
||||
if (!link?.mode) throw new HttpError(400, LINK_REQUIRED_MESSAGE);
|
||||
const mark = async (valid) => writeLink(app.db, userId, { ...link, valid, last_test_at: now(), ...(valid ? { validated_at: now() } : {}) });
|
||||
try {
|
||||
if (link.mode === MODES.server) {
|
||||
const user = await getUser(app.db, userId);
|
||||
if (!user?.isAdmin) throw new HttpError(400, SERVER_MODE_MESSAGE);
|
||||
try { await execFileP(app.cfg.claudeBin, ['--version'], { env: buildChildEnv(process.env, { home: app.cfg.sandbox?.serverHome || '/tmp' }), timeout: 15_000 }); }
|
||||
catch { throw new HttpError(502, 'Le CLI Claude du serveur est introuvable ou ne répond pas'); }
|
||||
} else {
|
||||
let secret;
|
||||
try { secret = decrypt(app.cfg.secretKey, link.secret_enc); } catch { secret = null; }
|
||||
if (!secret) { await mark(false); return { ok: false, message: 'Secret illisible : relie de nouveau ton accès Claude' }; }
|
||||
if (link.mode === MODES.api_key) await (app.validateApiKey || validateApiKey)(secret, app.fetch || fetch);
|
||||
else {
|
||||
if (app.cfg.cliModeEnabled === false) return { ok: false, message: CLI_DISABLED_MESSAGE };
|
||||
await (app.validateToken || ((t) => validateSubscriptionToken(app, t)))(secret);
|
||||
}
|
||||
}
|
||||
} catch (e) {
|
||||
if (!(e instanceof HttpError)) throw e;
|
||||
// 400 = refus d'authentification (liaison invalide) ; 502 = impossible de juger (réseau, CLI) : on ne touche à rien
|
||||
if (e.status === 400) await mark(false);
|
||||
return { ok: false, message: e.message };
|
||||
}
|
||||
await mark(true);
|
||||
return { ok: true, message: 'Liaison valide' };
|
||||
}
|
||||
|
||||
/** Dernière acceptation du risque du mode abonnement (conservée après « Délier »). */
|
||||
export async function lastConsent(db, userId) {
|
||||
const raw = await getSetting(db, userId, 'claude_cli_consent_json');
|
||||
try { return raw ? JSON.parse(raw) : null; } catch { return null; }
|
||||
}
|
||||
|
||||
/** Routes accessibles sans liaison valide : lier, Mon compte, déconnexion, suppression du compte. */
|
||||
export function isLinkExempt(method, pathname) {
|
||||
if (pathname === '/link' || pathname.startsWith('/link/')) return true;
|
||||
if (pathname === '/account' || pathname === '/account/delete') return true;
|
||||
return method === 'POST' && pathname === '/logout';
|
||||
}
|
||||
|
|
@ -7,7 +7,8 @@ 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 { resolveCredentials } from './claudelink.js';
|
||||
import { userRepoRoot } from './users.js';
|
||||
import { quotaAlerts } from './services/budget.js';
|
||||
import { notify } from './services/notify.js';
|
||||
import { evolutionMail } from './services/mailhtml.js';
|
||||
|
|
@ -53,15 +54,21 @@ export function parseProspectLine(line) {
|
|||
};
|
||||
}
|
||||
|
||||
export function makeHandlers(app) {
|
||||
/**
|
||||
* Tout appel à Claude passe par ici. Le secret est relu pour le user_id du job (jamais un autre), l'exécution se fait
|
||||
* dans le bac à sable avec un environnement assaini, et le quota remonté par le CLI est enregistré pour CET utilisateur.
|
||||
*/
|
||||
export function makeClaude(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);
|
||||
return async (userId, o) => {
|
||||
const cred = await resolveCredentials(app, userId); // refuse sans liaison valide (dernier garde-fou)
|
||||
const r = await runClaude({
|
||||
bin: cfg.claudeBin, ...o,
|
||||
sandbox: cfg.sandbox, secretEnv: cred.secretEnv, serverConfig: cred.serverConfig,
|
||||
allowedRoot: userRepoRoot(cfg, userId),
|
||||
});
|
||||
// État du quota d'abonnement (session 5h + semaine), affiché dans la barre système. Une clé API n'en a pas.
|
||||
const w = cred.mode === 'api_key' ? null : rateLimitWindows(r.rateLimit);
|
||||
if (w) {
|
||||
await setSetting(db, userId, 'claude_rate_limit_json', JSON.stringify({ at: now(), ...w }));
|
||||
for (const a of await quotaAlerts(db, userId, w)) {
|
||||
|
|
@ -75,7 +82,12 @@ export function makeHandlers(app) {
|
|||
}
|
||||
return r;
|
||||
};
|
||||
}
|
||||
|
||||
export function makeHandlers(app) {
|
||||
const { db, cfg } = app;
|
||||
const claude = makeClaude(app);
|
||||
const sync = (...a) => (app.syncRepo || syncRepo)(...a);
|
||||
const inHours = () => (app.isBusinessHours || isBusinessHours)();
|
||||
|
||||
// Premier mail ou relance : mêmes plafonds, mêmes délais, même journal
|
||||
|
|
@ -165,7 +177,7 @@ export function makeHandlers(app) {
|
|||
const project = await getProject(app, ctx.job.project_id, { userId });
|
||||
await ctx.progress({ message: 'Récupération du repo…', pct: 3 });
|
||||
const dir = repoDir(cfg, userId, project.id);
|
||||
const commit = await syncRepo(project.gitUrl, dir, await forgejoToken(app, userId));
|
||||
const commit = await sync(project.gitUrl, dir, await forgejoToken(app, userId));
|
||||
|
||||
await ctx.progress({ message: 'Analyse du code par Claude…', pct: 10 });
|
||||
const { prompt, system } = analyzePrompt(project.name);
|
||||
|
|
@ -288,7 +300,7 @@ export function makeHandlers(app) {
|
|||
|
||||
await ctx.progress({ message: 'Mise à jour du repo…', pct: 3 });
|
||||
const dir = repoDir(cfg, userId, project.id);
|
||||
await syncRepo(project.gitUrl, dir, await forgejoToken(app, userId));
|
||||
await sync(project.gitUrl, dir, await forgejoToken(app, userId));
|
||||
|
||||
await ctx.progress({ message: `Recherche de ${count} évolutions (${level})…`, pct: 10 });
|
||||
const { prompt, system } = evolutionPrompt({ projectName: project.name, profile: project.profile, count, level });
|
||||
|
|
|
|||
|
|
@ -2,17 +2,18 @@
|
|||
import { now } from '../db.js';
|
||||
import { HttpError } from '../http.js';
|
||||
import { AI_JOBS } from './budget.js';
|
||||
import { getUser, assertCanRunAi, AI_BLOCKED_MESSAGE } from '../users.js';
|
||||
import { getUser } from '../users.js';
|
||||
import { aiRefusal, assertCanRunAi } from '../claudelink.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.
|
||||
* - un job IA exige une liaison Claude valide de CET utilisateur.
|
||||
* Sans projet, `userId` est obligatoire. `opts.cliModeEnabled` : drapeau CLAUDE_CLI_MODE_ENABLED (vrai par défaut).
|
||||
*/
|
||||
export async function enqueue(db, { userId, projectId, type, params = {}, runAfter = null }) {
|
||||
export async function enqueue(db, { userId, projectId, type, params = {}, runAfter = null }, opts = {}) {
|
||||
if (projectId != null) {
|
||||
const owner = await db.prepare('SELECT user_id FROM projects WHERE id = ?').get(projectId);
|
||||
if (!owner || (userId != null && Number(owner.user_id) !== Number(userId))) throw new HttpError(404, 'Projet introuvable');
|
||||
|
|
@ -21,7 +22,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);
|
||||
if (AI_JOBS.has(type)) await assertCanRunAi(db, user.id, opts);
|
||||
// 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)
|
||||
|
|
@ -34,13 +35,13 @@ export async function enqueue(db, { userId, projectId, type, params = {}, runAft
|
|||
|
||||
/**
|
||||
* 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).
|
||||
* exécution (la file peut contenir un job mis en attente avant une suspension, un changement de rôle ou une déliaison).
|
||||
*/
|
||||
export async function jobRefusal(db, job) {
|
||||
export async function jobRefusal(db, job, opts = {}) {
|
||||
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;
|
||||
if (AI_JOBS.has(job.type)) return aiRefusal(db, job.user_id, opts);
|
||||
return null;
|
||||
}
|
||||
|
||||
|
|
@ -76,8 +77,9 @@ export async function latestJobs(db, projectId) {
|
|||
export class Worker {
|
||||
constructor(db, handlers, {
|
||||
thermalMax = 75, pollMs = 3000, log = console, clock = now, onFinish, onThermal,
|
||||
budget, isAiJob, onBudget, quota, isQuotaSensitive, onQuotaHold,
|
||||
budget, isAiJob, onBudget, quota, isQuotaSensitive, onQuotaHold, cliModeEnabled = true,
|
||||
} = {}) {
|
||||
this.cliModeEnabled = cliModeEnabled;
|
||||
this.clock = clock;
|
||||
this.budget = budget; // async (userId) => {blocked, reason} : budget de CET utilisateur
|
||||
this.isAiJob = isAiJob; // (type) => bool : jobs à mettre en attente si budget ($ équivalent) atteint
|
||||
|
|
@ -122,6 +124,11 @@ export class Worker {
|
|||
if (this.currentJob && Number(this.currentJob.user_id) === Number(userId)) this.current?.abort();
|
||||
}
|
||||
|
||||
/** Interrompt le job en cours s'il est un job IA de cet utilisateur (déliaison de son accès Claude). */
|
||||
abortUserAi(userId) {
|
||||
if (this.currentJob && Number(this.currentJob.user_id) === Number(userId) && this.isAiJob?.(this.currentJob.type)) this.current?.abort();
|
||||
}
|
||||
|
||||
/** Attend les callbacks (notifications) lancés par emit(). */
|
||||
async idle() {
|
||||
while (this.pending.size) await Promise.allSettled([...this.pending]);
|
||||
|
|
@ -174,8 +181,8 @@ 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);
|
||||
// Compte suspendu ou supprimé, job IA sans liaison Claude valide : refusé sans exécution
|
||||
const refusal = await jobRefusal(this.db, j, { cliModeEnabled: this.cliModeEnabled });
|
||||
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;
|
||||
|
|
|
|||
|
|
@ -6,7 +6,6 @@ import { HttpError } from './http.js';
|
|||
import { clearRecapCache } from './services/recap.js';
|
||||
|
||||
export const PROVIDER_LABELS = { google: 'Google', apple: 'Apple' };
|
||||
export const AI_BLOCKED_MESSAGE = 'Liaison Claude requise (bientôt disponible)';
|
||||
|
||||
export const normalizeEmail = (e) => String(e ?? '').trim().toLowerCase();
|
||||
const EMAIL_SHAPE = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
|
|
@ -26,13 +25,6 @@ export async function getUser(db, id) {
|
|||
return publicUser(await db.prepare(`SELECT ${COLUMNS} FROM users WHERE id = ?`).get(Number(id)));
|
||||
}
|
||||
|
||||
/** Un compte actif et administrateur peut lancer un job IA avec la configuration du serveur ; personne d'autre (avant le J3). */
|
||||
export const canRunAi = (user) => !!user && user.status === 'active' && user.isAdmin;
|
||||
|
||||
export function assertCanRunAi(user) {
|
||||
if (!canRunAi(user)) throw new HttpError(403, AI_BLOCKED_MESSAGE);
|
||||
}
|
||||
|
||||
/** ADMIN_EMAILS fait foi : les admins sont exactement ces adresses (au démarrage et à chaque connexion). */
|
||||
export async function syncAdmins(db, adminEmails) {
|
||||
const list = adminEmails.map(normalizeEmail).filter(Boolean);
|
||||
|
|
|
|||
Loading…
Reference in a new issue