feat(onboarding): page de liaison bloquante, Mon compte (tester, changer de mode, délier), quota par compte
- toute route métier est refusée côté serveur sans liaison valide (redirection ou 403 JSON) - fenêtre d'avertissement avec case obligatoire avant le mode abonnement - pas de barre de quota d'abonnement en mode clé API
This commit is contained in:
parent
4158f6f9d6
commit
74b8d27b6c
5 changed files with 175 additions and 22 deletions
|
|
@ -31,6 +31,10 @@ a { color: var(--accent); }
|
||||||
.login-btns { display: flex; flex-direction: column; gap: 10px; margin-top: 14px; }
|
.login-btns { display: flex; flex-direction: column; gap: 10px; margin-top: 14px; }
|
||||||
.btn.apple { background: var(--text); border-color: var(--text); color: var(--bg); }
|
.btn.apple { background: var(--text); border-color: var(--text); color: var(--bg); }
|
||||||
.notice { border-color: var(--warn); color: var(--text); }
|
.notice { border-color: var(--warn); color: var(--text); }
|
||||||
|
.check { display: flex; align-items: flex-start; gap: 8px; }
|
||||||
|
.check input { margin-top: 4px; }
|
||||||
|
.row-actions { display: flex; gap: 8px; flex-wrap: wrap; align-items: center; margin-top: 12px; }
|
||||||
|
.row-actions form { margin: 0; }
|
||||||
dl.account { display: grid; grid-template-columns: max-content 1fr; gap: 6px 16px; margin: 0; }
|
dl.account { display: grid; grid-template-columns: max-content 1fr; gap: 6px 16px; margin: 0; }
|
||||||
dl.account dt { color: var(--muted); }
|
dl.account dt { color: var(--muted); }
|
||||||
dl.account dd { margin: 0; overflow-wrap: anywhere; }
|
dl.account dd { margin: 0; overflow-wrap: anywhere; }
|
||||||
|
|
|
||||||
|
|
@ -55,6 +55,14 @@
|
||||||
followup_template: 'Modèle de relance', followup: 'Relances',
|
followup_template: 'Modèle de relance', followup: 'Relances',
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// ---------- Liaison Claude : fenêtre d'avertissement du mode abonnement ----------
|
||||||
|
// Le serveur refuse de toute façon (400) une requête sans la case cochée ; ici on évite seulement l'envoi inutile.
|
||||||
|
$('[data-open-dialog]').forEach((b) => b.addEventListener('click', () => $('#' + b.dataset.openDialog)?.showModal()));
|
||||||
|
$('[data-close-dialog]').forEach((b) => b.addEventListener('click', () => b.closest('dialog')?.close()));
|
||||||
|
const consentBox = $('#consent-accept');
|
||||||
|
const consentBtn = $('#consent-submit');
|
||||||
|
if (consentBox && consentBtn) consentBox.addEventListener('change', () => { consentBtn.disabled = !consentBox.checked; });
|
||||||
|
|
||||||
// ---------- Barre système ----------
|
// ---------- Barre système ----------
|
||||||
// "IA 24 h : 0,42 $ / 2 $" : orange à 80 %, rouge une fois atteint
|
// "IA 24 h : 0,42 $ / 2 $" : orange à 80 %, rouge une fois atteint
|
||||||
function gauge(label, x) {
|
function gauge(label, x) {
|
||||||
|
|
@ -76,7 +84,9 @@
|
||||||
const reset = resetLabel(w.resetsAt);
|
const reset = resetLabel(w.resetsAt);
|
||||||
return `<span class="${cls}"${reset ? ` title="Réinitialisation ${esc(reset)}"` : ''}>Claude ${label} : ${pct(w.utilization)}</span>`;
|
return `<span class="${cls}"${reset ? ` title="Réinitialisation ${esc(reset)}"` : ''}>Claude ${label} : ${pct(w.utilization)}</span>`;
|
||||||
}
|
}
|
||||||
function claudeQuota(rl) {
|
function claudeQuota(rl, mode) {
|
||||||
|
// Clé API : pas de quota d'abonnement à afficher
|
||||||
|
if (mode === 'api_key') return '';
|
||||||
if (!rl) return '<span class="muted" title="Mesuré après le premier job IA">Claude : pas encore mesuré</span>';
|
if (!rl) return '<span class="muted" title="Mesuré après le premier job IA">Claude : pas encore mesuré</span>';
|
||||||
return `${claudeBit('session 5h', rl.fiveHour)} ${claudeBit('semaine', rl.sevenDay)}`.trim();
|
return `${claudeBit('session 5h', rl.fiveHour)} ${claudeBit('semaine', rl.sevenDay)}`.trim();
|
||||||
}
|
}
|
||||||
|
|
@ -161,7 +171,7 @@
|
||||||
const s = await api('/api/system');
|
const s = await api('/api/system');
|
||||||
const hot = s.temp !== null && s.temp >= s.thermalMax - 5;
|
const hot = s.temp !== null && s.temp >= s.thermalMax - 5;
|
||||||
el.innerHTML = `${s.temp !== null ? `<span class="${hot ? 'warn' : ''}">${s.temp} °C</span>` : ''}
|
el.innerHTML = `${s.temp !== null ? `<span class="${hot ? 'warn' : ''}">${s.temp} °C</span>` : ''}
|
||||||
${claudeQuota(s.claudeRateLimit)}
|
${claudeQuota(s.claudeRateLimit, s.linkMode)}
|
||||||
${gauge('24 h', s.budget.day)} ${gauge('30 j', s.budget.month)}
|
${gauge('24 h', s.budget.day)} ${gauge('30 j', s.budget.month)}
|
||||||
${s.budget.blocked ? '<span class="error">Budget IA atteint : jobs IA en attente</span>' : ''}`;
|
${s.budget.blocked ? '<span class="error">Budget IA atteint : jobs IA en attente</span>' : ''}`;
|
||||||
renderJobsMenu(s);
|
renderJobsMenu(s);
|
||||||
|
|
@ -430,7 +440,7 @@
|
||||||
switch (action) {
|
switch (action) {
|
||||||
case 'create': {
|
case 'create': {
|
||||||
const r = await api('/api/projects', data);
|
const r = await api('/api/projects', data);
|
||||||
toast(r.aiBlocked ? `Projet créé. ${r.aiBlocked}` : 'Projet créé, analyse lancée');
|
toast('Projet créé, analyse lancée');
|
||||||
setTimeout(() => location.reload(), 600);
|
setTimeout(() => location.reload(), 600);
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -2,8 +2,12 @@ import { now, getSetting, setSetting } from './db.js';
|
||||||
import { encrypt, encryptJson, decryptJson, verifyUnsubToken } from './crypto.js';
|
import { encrypt, encryptJson, decryptJson, verifyUnsubToken } from './crypto.js';
|
||||||
import { html, json, redirect, readBody, HttpError } from './http.js';
|
import { html, json, redirect, readBody, HttpError } from './http.js';
|
||||||
import { startLogin, finishLogin, destroySession } from './auth.js';
|
import { startLogin, finishLogin, destroySession } from './auth.js';
|
||||||
import { canRunAi, assertCanRunAi, AI_BLOCKED_MESSAGE, deleteUser, normalizeEmail } from './users.js';
|
import { deleteUser, normalizeEmail } from './users.js';
|
||||||
import { loginPage, dashboardPage, settingsPage, unsubPage, accountPage } from './views.js';
|
import {
|
||||||
|
assertCanRunAi, getLinkState, linkApiKey, linkSubscriptionToken, linkServer, unlink, testLink, lastConsent,
|
||||||
|
MODES,
|
||||||
|
} from './claudelink.js';
|
||||||
|
import { loginPage, dashboardPage, settingsPage, unsubPage, accountPage, linkPage } from './views.js';
|
||||||
import { enqueue, latestJobs, cancelJob, usageSummary } from './services/jobs.js';
|
import { enqueue, latestJobs, cancelJob, usageSummary } from './services/jobs.js';
|
||||||
import { validateGitUrl, removeRepo } from './services/git.js';
|
import { validateGitUrl, removeRepo } from './services/git.js';
|
||||||
import { fetchRecap, clearRecapCache, validateSelect } from './services/recap.js';
|
import { fetchRecap, clearRecapCache, validateSelect } from './services/recap.js';
|
||||||
|
|
@ -32,6 +36,8 @@ const pid = (params) => Number(params.id);
|
||||||
|
|
||||||
export function registerRoutes(router, app) {
|
export function registerRoutes(router, app) {
|
||||||
const { db, cfg } = app;
|
const { db, cfg } = app;
|
||||||
|
const cliModeEnabled = cfg.cliModeEnabled !== false;
|
||||||
|
const aiOpts = { cliModeEnabled };
|
||||||
|
|
||||||
// Toute ressource métier est lue AVEC l'utilisateur courant : celle d'un autre compte est « introuvable » (404)
|
// Toute ressource métier est lue AVEC l'utilisateur courant : celle d'un autre compte est « introuvable » (404)
|
||||||
const project = (ctx, opts) => getProject(app, pid(ctx.params), { userId: ctx.session.userId, ...opts });
|
const project = (ctx, opts) => getProject(app, pid(ctx.params), { userId: ctx.session.userId, ...opts });
|
||||||
|
|
@ -84,7 +90,6 @@ export function registerRoutes(router, app) {
|
||||||
}
|
}
|
||||||
html(res, dashboardPage({
|
html(res, dashboardPage({
|
||||||
email: session.email, projects, forgejoHost: await getSetting(db, userId, 'forgejo_host'),
|
email: session.email, projects, forgejoHost: await getSetting(db, userId, 'forgejo_host'),
|
||||||
aiBlocked: canRunAi(session.user) ? null : AI_BLOCKED_MESSAGE,
|
|
||||||
}));
|
}));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -145,9 +150,51 @@ export function registerRoutes(router, app) {
|
||||||
redirect(res, '/settings?ok');
|
redirect(res, '/settings?ok');
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ---------- Liaison Claude ----------
|
||||||
|
// Page d'onboarding (bloquante tant qu'aucune liaison valide n'existe). Les secrets arrivent par POST, ne sont jamais
|
||||||
|
// relus ni réaffichés ; les erreurs ne contiennent que des messages fixes.
|
||||||
|
router.get('/link', async ({ res, session, url }) => {
|
||||||
|
html(res, linkPage({
|
||||||
|
user: session.user, link: await getLinkState(db, session.userId), cliModeEnabled, error: url.searchParams.get('e'),
|
||||||
|
}));
|
||||||
|
});
|
||||||
|
|
||||||
|
const wantsJson = (req) => !!req.headers.accept?.includes('json');
|
||||||
|
// Formulaire HTML : l'erreur revient sur la page de liaison ; appel JSON : code HTTP + { error }
|
||||||
|
const linkAction = (fn, okTo = '/') => async ({ req, res, session }) => {
|
||||||
|
const b = await readBody(req);
|
||||||
|
try {
|
||||||
|
const out = (await fn(b, session)) || {};
|
||||||
|
if (wantsJson(req)) return json(res, { ok: true, ...out });
|
||||||
|
redirect(res, okTo);
|
||||||
|
} catch (e) {
|
||||||
|
if (!(e instanceof HttpError) || wantsJson(req)) throw e;
|
||||||
|
redirect(res, `/link?e=${encodeURIComponent(e.message)}`);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
router.post('/link/api-key', linkAction((b, s) => linkApiKey(app, s.userId, b.apiKey)));
|
||||||
|
router.post('/link/subscription', linkAction((b, s) => linkSubscriptionToken(app, s.userId, { token: b.token, accept: b.accept })));
|
||||||
|
router.post('/link/server', linkAction((b, s) => linkServer(app, s.userId)));
|
||||||
|
router.post('/link/test', async ({ req, res, session }) => {
|
||||||
|
const r = await testLink(app, session.userId);
|
||||||
|
if (wantsJson(req)) return json(res, r);
|
||||||
|
redirect(res, `/account?t=${r.ok ? 'ok' : 'ko'}&m=${encodeURIComponent(r.message)}`);
|
||||||
|
});
|
||||||
|
router.post('/link/unlink', async ({ req, res, session }) => {
|
||||||
|
const cancelled = await unlink(app, session.userId);
|
||||||
|
if (wantsJson(req)) return json(res, { ok: true, cancelled });
|
||||||
|
redirect(res, '/account?t=unlinked');
|
||||||
|
});
|
||||||
|
|
||||||
// ---------- Mon compte ----------
|
// ---------- Mon compte ----------
|
||||||
router.get('/account', async ({ res, session, url }) => {
|
router.get('/account', async ({ res, session, url }) => {
|
||||||
html(res, accountPage({ user: session.user, error: url.searchParams.get('e') }));
|
const t = url.searchParams.get('t');
|
||||||
|
html(res, accountPage({
|
||||||
|
user: session.user, error: url.searchParams.get('e'), link: await getLinkState(db, session.userId),
|
||||||
|
consent: await lastConsent(db, session.userId), cliModeEnabled,
|
||||||
|
notice: t === 'unlinked' ? { ok: true, text: 'Liaison supprimée : le secret a été effacé et tes jobs IA en attente ont été annulés.' }
|
||||||
|
: t === 'ok' || t === 'ko' ? { ok: t === 'ok', text: String(url.searchParams.get('m') || '').slice(0, 300) } : null,
|
||||||
|
}));
|
||||||
});
|
});
|
||||||
|
|
||||||
// Suppression du compte : confirmée en saisissant son email ; efface TOUTES les données de l'utilisateur
|
// Suppression du compte : confirmée en saisissant son email ; efface TOUTES les données de l'utilisateur
|
||||||
|
|
@ -182,7 +229,9 @@ export function registerRoutes(router, app) {
|
||||||
const queue = (await db.prepare(`SELECT COUNT(*) n FROM jobs WHERE user_id = ? AND (status = 'running'
|
const queue = (await db.prepare(`SELECT COUNT(*) n FROM jobs WHERE user_id = ? AND (status = 'running'
|
||||||
OR (status = 'queued' AND (run_after IS NULL OR run_after <= ?)))`).get(userId, now())).n;
|
OR (status = 'queued' AND (run_after IS NULL OR run_after <= ?)))`).get(userId, now())).n;
|
||||||
const scheduled = (await db.prepare("SELECT COUNT(*) n FROM jobs WHERE user_id = ? AND status = 'queued' AND run_after > ?").get(userId, now())).n;
|
const scheduled = (await db.prepare("SELECT COUNT(*) n FROM jobs WHERE user_id = ? AND status = 'queued' AND run_after > ?").get(userId, now())).n;
|
||||||
const rlRaw = await getSetting(db, userId, 'claude_rate_limit_json');
|
const link = await getLinkState(db, userId);
|
||||||
|
// Le quota d'abonnement n'existe qu'en mode abonnement ou serveur : jamais de barre en mode clé API
|
||||||
|
const rlRaw = link?.mode === MODES.api_key ? null : await getSetting(db, userId, 'claude_rate_limit_json');
|
||||||
// Détail pour le menu « jobs » de la barre du haut : en cours d'abord, puis la file, puis les programmés
|
// Détail pour le menu « jobs » de la barre du haut : en cours d'abord, puis la file, puis les programmés
|
||||||
const jobs = (await db.prepare(`SELECT j.id, j.type, j.status, j.progress_json, j.run_after, j.started_at, j.created_at, p.id pid, p.name project
|
const jobs = (await db.prepare(`SELECT j.id, j.type, j.status, j.progress_json, j.run_after, j.started_at, j.created_at, p.id pid, p.name project
|
||||||
FROM jobs j LEFT JOIN projects p ON p.id = j.project_id
|
FROM jobs j LEFT JOIN projects p ON p.id = j.project_id
|
||||||
|
|
@ -194,7 +243,7 @@ export function registerRoutes(router, app) {
|
||||||
}));
|
}));
|
||||||
json(res, {
|
json(res, {
|
||||||
temp: session.user.isAdmin ? cpuTemp() : null, queue, scheduled, jobs, usage: await usageSummary(db, userId), budget: await budgetState(db, userId), thermalMax: cfg.thermalMax,
|
temp: session.user.isAdmin ? cpuTemp() : null, queue, scheduled, jobs, usage: await usageSummary(db, userId), budget: await budgetState(db, userId), thermalMax: cfg.thermalMax,
|
||||||
claudeRateLimit: rlRaw ? JSON.parse(rlRaw) : null,
|
claudeRateLimit: rlRaw ? JSON.parse(rlRaw) : null, linkMode: link?.mode ?? null,
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -214,9 +263,7 @@ export function registerRoutes(router, app) {
|
||||||
let id;
|
let id;
|
||||||
try { id = await createProject(app, { userId, name, gitUrl }); }
|
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; }
|
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
|
await enqueue(db, { userId, projectId: id, type: 'analyze' }, aiOpts);
|
||||||
if (!canRunAi(session.user)) return json(res, { id, aiBlocked: AI_BLOCKED_MESSAGE });
|
|
||||||
await enqueue(db, { userId, projectId: id, type: 'analyze' });
|
|
||||||
json(res, { id });
|
json(res, { id });
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|
@ -271,14 +318,14 @@ export function registerRoutes(router, app) {
|
||||||
|
|
||||||
const jobRoute = (type, paramsOf = () => ({}), guard = () => {}) => async (ctx) => {
|
const jobRoute = (type, paramsOf = () => ({}), guard = () => {}) => async (ctx) => {
|
||||||
const { req, res, session } = 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)
|
// Refus côté serveur AVANT toute autre vérification : pas de job IA sans liaison Claude valide (enqueue le revérifie)
|
||||||
if (AI_JOBS.has(type)) assertCanRunAi(session.user);
|
if (AI_JOBS.has(type)) await assertCanRunAi(db, session.userId, aiOpts);
|
||||||
const p = await project(ctx);
|
const p = await project(ctx);
|
||||||
const b = req.headers['content-type']?.includes('json') ? await readBody(req) : {};
|
const b = req.headers['content-type']?.includes('json') ? await readBody(req) : {};
|
||||||
await guard(p, b);
|
await guard(p, b);
|
||||||
// "Cette nuit" : démarrage au prochain créneau 1h-6h (Pi au frais, quota Claude libre)
|
// "Cette nuit" : démarrage au prochain créneau 1h-6h (Pi au frais, quota Claude libre)
|
||||||
const runAfter = b.when === 'night' ? Math.floor(nextNightSlot().getTime() / 1000) : null;
|
const runAfter = b.when === 'night' ? Math.floor(nextNightSlot().getTime() / 1000) : null;
|
||||||
const r = await enqueue(db, { userId: session.userId, projectId: p.id, type, params: paramsOf(b), runAfter });
|
const r = await enqueue(db, { userId: session.userId, projectId: p.id, type, params: paramsOf(b), runAfter }, aiOpts);
|
||||||
const budget = AI_JOBS.has(type) ? await budgetState(db, session.userId) : null;
|
const budget = AI_JOBS.has(type) ? await budgetState(db, session.userId) : null;
|
||||||
json(res, { ...r, budgetBlocked: budget?.blocked ? budget.reason : null });
|
json(res, { ...r, budgetBlocked: budget?.blocked ? budget.reason : null });
|
||||||
};
|
};
|
||||||
|
|
|
||||||
|
|
@ -14,6 +14,8 @@ import { Scheduler } from './services/scheduler.js';
|
||||||
import { notify, notifyJob } from './services/notify.js';
|
import { notify, notifyJob } from './services/notify.js';
|
||||||
import { budgetState, AI_JOBS, quotaState, isQuotaSensitive } from './services/budget.js';
|
import { budgetState, AI_JOBS, quotaState, isQuotaSensitive } from './services/budget.js';
|
||||||
import { layout } from './views.js';
|
import { layout } from './views.js';
|
||||||
|
import { hasUsableLink, isLinkExempt, LINK_REQUIRED_MESSAGE } from './claudelink.js';
|
||||||
|
import { sandboxStartupMessages } from './services/sandbox.js';
|
||||||
|
|
||||||
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..');
|
||||||
|
|
||||||
|
|
@ -31,10 +33,11 @@ const SECURITY_HEADERS = {
|
||||||
'Strict-Transport-Security': 'max-age=31536000',
|
'Strict-Transport-Security': 'max-age=31536000',
|
||||||
};
|
};
|
||||||
|
|
||||||
export async function createApp(cfg, { db, worker = true, createTransport } = {}) {
|
// `fetch`, `validateApiKey`, `validateToken`, `syncRepo` : points d'injection pour les tests (aucun appel réseau réel)
|
||||||
|
export async function createApp(cfg, { db, worker = true, createTransport, fetch, validateApiKey, validateToken, syncRepo } = {}) {
|
||||||
db ??= await openDb(cfg.db, { adminEmails: cfg.adminEmails });
|
db ??= await openDb(cfg.db, { adminEmails: cfg.adminEmails });
|
||||||
await syncAdmins(db, cfg.adminEmails || []); // ADMIN_EMAILS fait foi pour le rôle admin
|
await syncAdmins(db, cfg.adminEmails || []); // ADMIN_EMAILS fait foi pour le rôle admin
|
||||||
const app = { db, cfg, createTransport };
|
const app = { db, cfg, createTransport, fetch, validateApiKey, validateToken, syncRepo };
|
||||||
const router = new Router();
|
const router = new Router();
|
||||||
registerRoutes(router, app);
|
registerRoutes(router, app);
|
||||||
|
|
||||||
|
|
@ -56,6 +59,13 @@ export async function createApp(cfg, { db, worker = true, createTransport } = {}
|
||||||
return redirect(res, '/login');
|
return redirect(res, '/login');
|
||||||
}
|
}
|
||||||
checkOrigin(req, cfg);
|
checkOrigin(req, cfg);
|
||||||
|
// Onboarding bloquant : sans liaison Claude valide, seules la liaison, Mon compte et la déconnexion répondent
|
||||||
|
if (!isLinkExempt(req.method, url.pathname) && !(await hasUsableLink(db, session.userId, { cliModeEnabled: cfg.cliModeEnabled !== false }))) {
|
||||||
|
if (url.pathname.startsWith('/api/') || req.headers.accept?.includes('json')) {
|
||||||
|
return json(res, { error: LINK_REQUIRED_MESSAGE, code: 'link_required' }, 403);
|
||||||
|
}
|
||||||
|
return redirect(res, '/link');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
await route.handler({ req, res, url, params: route.params, session, app });
|
await route.handler({ req, res, url, params: route.params, session, app });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|
@ -76,7 +86,7 @@ export async function createApp(cfg, { db, worker = true, createTransport } = {}
|
||||||
let scheduler = null;
|
let scheduler = null;
|
||||||
if (worker) {
|
if (worker) {
|
||||||
w = new Worker(db, makeHandlers(app), {
|
w = new Worker(db, makeHandlers(app), {
|
||||||
thermalMax: cfg.thermalMax,
|
thermalMax: cfg.thermalMax, cliModeEnabled: cfg.cliModeEnabled !== false,
|
||||||
onFinish: (job, r) => notifyJob(app, job, r),
|
onFinish: (job, r) => notifyJob(app, job, r),
|
||||||
budget: (userId) => budgetState(db, userId),
|
budget: (userId) => budgetState(db, userId),
|
||||||
isAiJob: (type) => AI_JOBS.has(type),
|
isAiJob: (type) => AI_JOBS.has(type),
|
||||||
|
|
@ -121,7 +131,8 @@ export async function createApp(cfg, { db, worker = true, createTransport } = {}
|
||||||
|
|
||||||
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
if (process.argv[1] === fileURLToPath(import.meta.url)) {
|
||||||
const cfg = loadConfig();
|
const cfg = loadConfig();
|
||||||
if (!cfg.adminEmails.length) console.warn('ADMIN_EMAILS est vide : aucun administrateur (personne ne pourra lancer de job IA).');
|
if (!cfg.adminEmails.length) console.warn('ADMIN_EMAILS est vide : aucun administrateur (personne ne pourra utiliser le mode « Claude du serveur »).');
|
||||||
|
for (const m of sandboxStartupMessages(cfg.sandbox)) console.warn(m);
|
||||||
const app = await createApp(cfg);
|
const app = await createApp(cfg);
|
||||||
app.server.listen(cfg.port, cfg.host, () => console.log(`AiTools sur http://${cfg.host}:${cfg.port} (${cfg.appUrl})`));
|
app.server.listen(cfg.port, cfg.host, () => console.log(`AiTools sur http://${cfg.host}:${cfg.port} (${cfg.appUrl})`));
|
||||||
const shutdown = () => app.close().then(() => process.exit(0), (e) => { console.error(e); process.exit(1); });
|
const shutdown = () => app.close().then(() => process.exit(0), (e) => { console.error(e); process.exit(1); });
|
||||||
|
|
|
||||||
87
src/views.js
87
src/views.js
|
|
@ -1,5 +1,6 @@
|
||||||
import { esc } from './http.js';
|
import { esc } from './http.js';
|
||||||
import { STATUSES } from './services/crm.js';
|
import { STATUSES } from './services/crm.js';
|
||||||
|
import { MODE_LABELS, CONSENT_TEXT, CONSENT_CHECKBOX, CONSENT_VERSION } from './claudelink.js';
|
||||||
|
|
||||||
const fmtDate = (ts) => (ts ? new Date(ts * 1000).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short', timeZone: 'Europe/Paris' }) : '—');
|
const fmtDate = (ts) => (ts ? new Date(ts * 1000).toLocaleString('fr-FR', { dateStyle: 'short', timeStyle: 'short', timeZone: 'Europe/Paris' }) : '—');
|
||||||
|
|
||||||
|
|
@ -74,7 +75,36 @@ export function loginPage(error, { apple = false, bye = false } = {}) {
|
||||||
|
|
||||||
const PROVIDER_NAMES = { google: 'Google', apple: 'Apple' };
|
const PROVIDER_NAMES = { google: 'Google', apple: 'Apple' };
|
||||||
|
|
||||||
export function accountPage({ user, error }) {
|
// Section « Liaison Claude » de Mon compte : état, test, changement de mode, déliaison. Jamais le secret, ni même un masque
|
||||||
|
// plus long que les 4 derniers caractères de la clé API.
|
||||||
|
function linkSection(link, consent) {
|
||||||
|
if (!link) {
|
||||||
|
return `<section class="card">
|
||||||
|
<h4>Liaison Claude</h4>
|
||||||
|
<p class="muted">Aucun accès Claude n'est relié : l'application reste bloquée sur la page de liaison.</p>
|
||||||
|
<a class="btn primary" href="/link">Relier Claude</a>
|
||||||
|
</section>`;
|
||||||
|
}
|
||||||
|
return `<section class="card">
|
||||||
|
<h4>Liaison Claude</h4>
|
||||||
|
<dl class="account">
|
||||||
|
<dt>Mode</dt><dd>${esc(link.label)}</dd>
|
||||||
|
<dt>État</dt><dd>${link.valid ? '<span class="ok">Valide</span>' : '<span class="error">À revalider (teste ou relie de nouveau)</span>'}</dd>
|
||||||
|
${link.last4 ? `<dt>Clé API</dt><dd>sk-ant-…${esc(link.last4)}</dd>` : ''}
|
||||||
|
<dt>Reliée le</dt><dd>${fmtDate(link.linkedAt)}</dd>
|
||||||
|
<dt>Dernier test</dt><dd>${fmtDate(link.lastTestAt)}</dd>
|
||||||
|
${link.consentAt ? `<dt>Risque accepté</dt><dd>${fmtDate(link.consentAt)} (texte ${esc(link.consentVersion)})</dd>` : ''}
|
||||||
|
</dl>
|
||||||
|
<div class="row-actions">
|
||||||
|
<form method="post" action="/link/test"><button class="btn">Tester</button></form>
|
||||||
|
<a class="btn" href="/link?change=1">Changer de mode</a>
|
||||||
|
<form method="post" action="/link/unlink"><button class="btn danger">Délier</button></form>
|
||||||
|
</div>
|
||||||
|
<p class="muted small">Délier efface le secret chiffré et annule tes jobs IA en attente ou en cours.${consent && !link.consentAt ? ` Dernier consentement au mode abonnement : ${fmtDate(consent.at)}.` : ''}</p>
|
||||||
|
</section>`;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function accountPage({ user, error, link = null, consent = null, notice = null }) {
|
||||||
return layout({
|
return layout({
|
||||||
title: 'Mon compte', email: user.email,
|
title: 'Mon compte', email: user.email,
|
||||||
body: `<h1>Mon compte</h1>
|
body: `<h1>Mon compte</h1>
|
||||||
|
|
@ -84,6 +114,8 @@ export function accountPage({ user, error }) {
|
||||||
<dt>Connexion</dt><dd>${esc(PROVIDER_NAMES[user.provider] || '—')}</dd>
|
<dt>Connexion</dt><dd>${esc(PROVIDER_NAMES[user.provider] || '—')}</dd>
|
||||||
</dl>
|
</dl>
|
||||||
</section>
|
</section>
|
||||||
|
${notice ? `<p class="${notice.ok ? 'ok' : 'error'}">${esc(notice.text)}</p>` : ''}
|
||||||
|
${linkSection(link, consent)}
|
||||||
<section class="card">
|
<section class="card">
|
||||||
<h4>Supprimer mon compte</h4>
|
<h4>Supprimer mon compte</h4>
|
||||||
<p class="muted small">Efface définitivement ton compte et toutes tes données : projets, prospects, notes, modèles de mail, journaux d'envoi, jobs, réglages et clones du code. Les adresses qui ont demandé à ne plus être contactées restent dans la liste d'opposition commune. Cette action est irréversible.</p>
|
<p class="muted small">Efface définitivement ton compte et toutes tes données : projets, prospects, notes, modèles de mail, journaux d'envoi, jobs, réglages et clones du code. Les adresses qui ont demandé à ne plus être contactées restent dans la liste d'opposition commune. Cette action est irréversible.</p>
|
||||||
|
|
@ -96,6 +128,56 @@ export function accountPage({ user, error }) {
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Page « Relier Claude » : onboarding bloquant. Les trois modes sont des formulaires HTML classiques (POST) ;
|
||||||
|
* la fenêtre d'avertissement du mode abonnement est un <dialog> ouvert par public/app.js.
|
||||||
|
*/
|
||||||
|
export function linkPage({ user, link, cliModeEnabled, error }) {
|
||||||
|
const intro = link
|
||||||
|
? `<p class="muted">Accès actuel : <strong>${esc(link.label)}</strong>${link.valid ? '' : ' (à revalider)'}. Relier un autre accès remplace le précédent, dont le secret est effacé.</p>`
|
||||||
|
: '<p class="muted">Pour utiliser AiTools, relie ton propre accès Claude. Les analyses, recherches et rédactions s\'exécutent avec TON accès, jamais celui d\'un autre utilisateur.</p>';
|
||||||
|
const subscription = cliModeEnabled ? `
|
||||||
|
<section class="card">
|
||||||
|
<h4>Connexion avec Claude (abonnement)</h4>
|
||||||
|
<p class="muted small">Utilise ton abonnement Claude (Pro, Max) au lieu d'une clé API. Cette option comporte un risque pour ton compte Claude : une fenêtre d'avertissement s'affiche avant de continuer.</p>
|
||||||
|
<button type="button" class="btn" data-open-dialog="consent-dialog">Connexion avec Claude (abonnement)</button>
|
||||||
|
</section>
|
||||||
|
<dialog class="prospect-dialog" id="consent-dialog" aria-labelledby="consent-title">
|
||||||
|
<form method="post" action="/link/subscription" class="cfg">
|
||||||
|
<h2 id="consent-title">Avant de continuer</h2>
|
||||||
|
<div class="notice card">${CONSENT_TEXT.map((t) => `<p>${esc(t)}</p>`).join('')}</div>
|
||||||
|
<label class="check"><input type="checkbox" name="accept" id="consent-accept" required> ${esc(CONSENT_CHECKBOX)}</label>
|
||||||
|
<p class="muted small">Sur ta propre machine, lance la commande <code>claude setup-token</code>, connecte-toi à ton compte Claude quand le navigateur s'ouvre, puis copie le jeton affiché et colle-le ci-dessous. Le jeton est chiffré, utilisé uniquement pour tes jobs, et n'est jamais réaffiché.</p>
|
||||||
|
<label>Jeton d'abonnement<input name="token" type="password" autocomplete="new-password" spellcheck="false" required></label>
|
||||||
|
<p class="muted small">La vérification lance un appel minimal du CLI : quelques tokens sont décomptés de ton abonnement. Texte d'avertissement version ${esc(CONSENT_VERSION)}.</p>
|
||||||
|
<div class="row-actions">
|
||||||
|
<button type="button" class="btn" data-close-dialog>Annuler</button>
|
||||||
|
<button class="btn primary" id="consent-submit" disabled>Relier avec mon abonnement</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</dialog>` : '';
|
||||||
|
const server = user.isAdmin ? `
|
||||||
|
<section class="card">
|
||||||
|
<h4>Claude du serveur (administrateurs)</h4>
|
||||||
|
<p class="muted small">Utilise la configuration du CLI Claude déjà connectée sur la machine qui héberge AiTools.</p>
|
||||||
|
<form method="post" action="/link/server"><button class="btn">Utiliser Claude du serveur</button></form>
|
||||||
|
</section>` : '';
|
||||||
|
return layout({
|
||||||
|
title: 'Relier Claude', email: user.email,
|
||||||
|
body: `<h1>Relier Claude</h1>
|
||||||
|
${intro}
|
||||||
|
${error ? `<p class="error">${esc(error)}</p>` : ''}
|
||||||
|
<section class="card">
|
||||||
|
<h4>Clé API Anthropic (recommandé)</h4>
|
||||||
|
<p class="muted small">Crée une clé sur console.anthropic.com puis colle-la ici. Elle est vérifiée sans consommer de tokens, chiffrée, et ne sera plus jamais affichée (seuls ses 4 derniers caractères le seront).</p>
|
||||||
|
<form method="post" action="/link/api-key" class="cfg">
|
||||||
|
<label>Clé API<input name="apiKey" type="password" autocomplete="new-password" spellcheck="false" required placeholder="sk-ant-…"></label>
|
||||||
|
<button class="btn primary">Vérifier et relier</button>
|
||||||
|
</form>
|
||||||
|
</section>${subscription}${server}`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
function targetForm(p) {
|
function targetForm(p) {
|
||||||
const t = p.target || {};
|
const t = p.target || {};
|
||||||
const list = (a) => esc((a || []).join('\n'));
|
const list = (a) => esc((a || []).join('\n'));
|
||||||
|
|
@ -273,13 +355,12 @@ function projectItem(p, smtp, dbCfg, imap) {
|
||||||
</details>`;
|
</details>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export function dashboardPage({ email, projects, forgejoHost, aiBlocked = null }) {
|
export function dashboardPage({ email, projects, forgejoHost }) {
|
||||||
return layout({
|
return layout({
|
||||||
title: 'Projets', email,
|
title: 'Projets', email,
|
||||||
body: `<div class="row head">
|
body: `<div class="row head">
|
||||||
<h1>Projets</h1>
|
<h1>Projets</h1>
|
||||||
</div>
|
</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">
|
<details class="card new anim">
|
||||||
<summary class="btn primary">+ Nouveau projet</summary>
|
<summary class="btn primary">+ Nouveau projet</summary>
|
||||||
<form data-action="create" class="cfg">
|
<form data-action="create" class="cfg">
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue