diff --git a/public/app.css b/public/app.css index 8fc0d94..d9e3dec 100644 --- a/public/app.css +++ b/public/app.css @@ -102,3 +102,5 @@ form.send { margin-top: 18px; padding-top: 14px; border-top: 1px solid var(--lin .followup { margin-top: 18px; padding-top: 12px; border-top: 1px solid var(--line); } .running.scheduled { background: transparent; border: 1px dashed var(--line); } .moon { width: 18px; height: 18px; border-radius: 50%; box-shadow: inset -5px -3px 0 0 var(--accent); flex: none; transform: rotate(-20deg); } +.checks { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 0 12px; margin: 4px 0 10px; } +.checks label.check { margin: 4px 0; } diff --git a/public/app.js b/public/app.js index 8f6b453..41f89ff 100644 --- a/public/app.js +++ b/public/app.js @@ -223,6 +223,12 @@ if (e.target.matches('[data-recap-refresh]')) loadRecap(e.target.closest('.project'), true); + if (e.target.closest('[data-notify-test]')) { + try { await api('/api/notify/test', {}); toast('Notification envoyée sur Discord'); } + catch (err) { toast(err.message, 'error'); } + return; + } + const inboxBtn = e.target.closest('[data-inbox-check]'); if (inboxBtn) { inboxBtn.disabled = true; diff --git a/src/routes.js b/src/routes.js index e959285..5dfe8f7 100644 --- a/src/routes.js +++ b/src/routes.js @@ -11,6 +11,7 @@ import { cpuTemp } from './services/thermal.js'; import { checkInbox } from './services/inbox.js'; import { followupPlan } from './services/followup.js'; import { nextNightSlot } from './services/paris-time.js'; +import { notify, notifyConfig, EVENTS, WEBHOOK_RE } from './services/notify.js'; import { getProject, listProjects, createProject, saveSecretConfig, publicConfig, globalSmtp, prospectStats, sentSince, repoDir, getTemplate, saveTemplate, abStats, @@ -69,6 +70,7 @@ export function registerRoutes(router, app) { send_delay_max: getSetting(db, 'send_delay_max', '60'), prospect_model: getSetting(db, 'prospect_model', 'haiku'), blacklist_count: db.prepare('SELECT COUNT(*) n FROM blacklist').get().n, + discord: { set: !!notifyConfig(app).url, events: notifyConfig(app).events, all: EVENTS }, }; html(res, settingsPage({ email: session.email, s, saved: url.searchParams.has('ok') })); }); @@ -87,6 +89,12 @@ export function registerRoutes(router, app) { setSetting(db, 'send_delay_max', String(dmax)); setSetting(db, 'prospect_model', b.prospect_model === 'sonnet' ? 'sonnet' : 'haiku'); + const hook = String(b.discord_webhook || '').trim(); + if (hook && !WEBHOOK_RE.test(hook)) throw new HttpError(400, 'URL de webhook Discord invalide (https://discord.com/api/webhooks/…)'); + if (hook) setSetting(db, 'discord_webhook_enc', encrypt(cfg.secretKey, hook)); + if (b.discord_remove === 'on') setSetting(db, 'discord_webhook_enc', null); + setSetting(db, 'discord_events', JSON.stringify(Object.keys(EVENTS).filter((k) => b[`ev_${k}`] === 'on'))); + const prev = globalSmtp(app) || {}; const smtp = { host: b.smtp_host, port: b.smtp_port, user: b.smtp_user, pass: b.smtp_pass || prev.pass, fromEmail: b.smtp_fromEmail }; setSetting(db, 'smtp_enc', smtp.host ? encryptJson(cfg.secretKey, smtp) : null); @@ -94,6 +102,13 @@ export function registerRoutes(router, app) { }); // ---------- API JSON ---------- + router.post('/api/notify/test', async ({ res }) => { + if (!notifyConfig(app).url) throw new HttpError(400, 'Aucun webhook Discord configuré'); + const ok = await notify(app, 'test', { title: 'Notification de test', description: 'Les notifications AiTools arrivent bien ici.', level: 'ok' }, { force: true }); + if (!ok) throw new HttpError(502, 'Discord a refusé la notification (webhook supprimé ?)'); + json(res, { ok: true }); + }); + router.get('/api/system', ({ res }) => { const queue = db.prepare(`SELECT COUNT(*) n FROM jobs WHERE status = 'running' OR (status = 'queued' AND (run_after IS NULL OR run_after <= ?))`).get(now()).n; diff --git a/src/server.js b/src/server.js index 08562ac..8993e20 100644 --- a/src/server.js +++ b/src/server.js @@ -10,6 +10,7 @@ import { registerRoutes } from './routes.js'; import { Worker } from './services/jobs.js'; import { makeHandlers } from './handlers.js'; import { Scheduler } from './services/scheduler.js'; +import { notify, notifyJob } from './services/notify.js'; import { layout } from './views.js'; const ROOT = join(dirname(fileURLToPath(import.meta.url)), '..'); @@ -70,7 +71,14 @@ export function createApp(cfg, { db = openDb(cfg.dataDir), worker = true, create let w = null; let scheduler = null; if (worker) { - w = new Worker(db, makeHandlers(app), { thermalMax: cfg.thermalMax }); + w = new Worker(db, makeHandlers(app), { + thermalMax: cfg.thermalMax, + onFinish: (job, r) => notifyJob(app, job, r), + onThermal: (t) => notify(app, 'thermal', { + title: 'Pause thermique', level: 'warn', + description: `CPU à ${t} °C : les jobs IA attendent que le Pi redescende sous ${cfg.thermalMax - 5} °C.`, + }), + }); w.start(); scheduler = new Scheduler(app); scheduler.start(); diff --git a/src/services/inbox.js b/src/services/inbox.js index c687861..f66db33 100644 --- a/src/services/inbox.js +++ b/src/services/inbox.js @@ -2,6 +2,7 @@ // Aucun token Claude : uniquement des en-têtes de mails. import { now } from '../db.js'; import { getProject } from '../projects.js'; +import { notify } from './notify.js'; // Webmails grand public : une réponse d'un autre @gmail.com ne dit rien sur l'entreprise const GENERIC_DOMAINS = new Set([ @@ -158,6 +159,13 @@ export async function checkInbox(app, projectId) { uidValidity: r.uidValidity, lastUid: r.lastUid, lastCheck: at, lastOk: at, lastError: null, replies: (state.replies || 0) + res.replies, bounces: (state.bounces || 0) + res.bounces, }); + if (res.replies) { + const who = db.prepare('SELECT company, email, reply_subject FROM prospects WHERE project_id = ? AND replied_at = ? LIMIT 10').all(project.id, at); + await notify(app, 'reply', { + title: `${project.name} · ${res.replies} réponse(s) de prospect`, level: 'ok', + description: who.map((p) => `**${p.company}** (${p.email}) : ${p.reply_subject || 'sans objet'}`).join('\n'), + }); + } return res; } catch (e) { const msg = String(e.responseText || e.message || e).slice(0, 300); diff --git a/src/services/jobs.js b/src/services/jobs.js index da4adcf..addb748 100644 --- a/src/services/jobs.js +++ b/src/services/jobs.js @@ -39,8 +39,10 @@ export function latestJobs(db, projectId) { } export class Worker { - constructor(db, handlers, { thermalMax = 75, pollMs = 3000, log = console, clock = now } = {}) { + constructor(db, handlers, { thermalMax = 75, pollMs = 3000, log = console, clock = now, onFinish, onThermal } = {}) { this.clock = clock; + this.onFinish = onFinish; // (job, {status, result, error}) → notifications + this.onThermal = onThermal; // (°C) → une fois par pause this.db = db; this.handlers = handlers; this.thermalMax = thermalMax; @@ -58,6 +60,12 @@ export class Worker { stop() { this.stopped = true; this.current?.abort(); } + // Les callbacks ne doivent jamais bloquer ni faire tomber le worker + emit(name, ...args) { + try { Promise.resolve(this[name]?.(...args)).catch((e) => this.log.error(`[${name}]`, e.message)); } + catch (e) { this.log.error(`[${name}]`, e.message); } + } + isCancelled(jobId) { return this.db.prepare('SELECT status FROM jobs WHERE id = ?').get(jobId)?.status === 'cancelled'; } @@ -79,7 +87,13 @@ export class Worker { return true; } - await waitCool(this.thermalMax, { onWait: (t) => setProgress(this.db, job.id, { message: `Pause thermique (${t} °C)` }) }); + let warned = false; + await waitCool(this.thermalMax, { + onWait: (t) => { + setProgress(this.db, job.id, { message: `Pause thermique (${t} °C)` }); + if (!warned) { warned = true; this.emit('onThermal', t); } + }, + }); this.db.prepare("UPDATE jobs SET status='running', started_at=? WHERE id=? AND status='queued'").run(now(), job.id); const ctrl = new AbortController(); @@ -100,12 +114,14 @@ export class Worker { if (!this.isCancelled(job.id)) { this.db.prepare("UPDATE jobs SET status='done', result_json=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?") .run(JSON.stringify(result ?? null), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id); + this.emit('onFinish', job, { status: 'done', result }); } } catch (e) { this.log.error(`[job ${job.id} ${job.type}]`, e.message); if (!this.isCancelled(job.id)) { this.db.prepare("UPDATE jobs SET status='error', error=?, finished_at=?, cost_usd=?, tokens_in=?, tokens_out=? WHERE id=?") .run(String(e.message).slice(0, 2000), now(), ctx.usage.costUsd, ctx.usage.tokensIn, ctx.usage.tokensOut, job.id); + this.emit('onFinish', job, { status: 'error', error: e.message }); } } finally { clearInterval(watch); diff --git a/src/services/notify.js b/src/services/notify.js new file mode 100644 index 0000000..7a54df2 --- /dev/null +++ b/src/services/notify.js @@ -0,0 +1,84 @@ +// Notifications Discord via webhook (pas de bot, pas de process permanent : une requête HTTP). +import { getSetting } from '../db.js'; +import { decrypt } from '../crypto.js'; + +// Uniquement de vraies URLs de webhook Discord : jamais d'envoi vers une adresse arbitraire +export const WEBHOOK_RE = /^https:\/\/(?:canary\.|ptb\.)?discord(?:app)?\.com\/api\/webhooks\/\d{5,25}\/[\w-]{20,120}$/; + +export const EVENTS = { + job_done: 'Recherche, analyse, envoi ou évolutions terminés', + job_error: 'Job en erreur', + reply: 'Réponse d\'un prospect', + followup: 'Relances envoyées', + thermal: 'Pause thermique du Pi', + budget: 'Budget IA atteint', + weekly: 'Rapport hebdo', +}; + +const COLORS = { ok: 0x15803d, info: 0x2f5bea, warn: 0xb45309, error: 0xb91c1c }; + +export function notifyConfig(app) { + let url = null; + try { url = decrypt(app.cfg.secretKey, getSetting(app.db, 'discord_webhook_enc')); } + catch { url = null; } + const raw = getSetting(app.db, 'discord_events'); + const events = raw ? JSON.parse(raw) : Object.keys(EVENTS); + return { url, events }; +} + +/** Envoie une notif si le webhook est configuré et l'événement activé. Ne lève jamais d'erreur. */ +export async function notify(app, event, { title, description = '', level = 'info', fields = [] }, { force = false } = {}) { + const { url, events } = notifyConfig(app); + if (!url || (!force && !events.includes(event))) return false; + const body = { + username: 'AiTools', + allowed_mentions: { parse: [] }, // un "@everyone" dans un nom d'entreprise ne pingera personne + embeds: [{ + title: String(title).slice(0, 256), + description: String(description).slice(0, 4000), + color: COLORS[level] ?? COLORS.info, + fields: fields.slice(0, 10).map((f) => ({ + name: String(f.name).slice(0, 256), value: String(f.value ?? '-').slice(0, 1024) || '-', inline: f.inline ?? true, + })), + url: app.cfg.appUrl || undefined, + timestamp: new Date().toISOString(), + }], + }; + try { + const r = await (app.fetch || fetch)(url, { + method: 'POST', headers: { 'Content-Type': 'application/json' }, + body: JSON.stringify(body), signal: AbortSignal.timeout(10_000), + }); + if (!r.ok) throw new Error(`HTTP ${r.status}`); + return true; + } catch (e) { + console.warn('[discord]', e.message); + return false; + } +} + +// Fin de job → notif (seulement pour les jobs longs, ceux qu'on lance et qu'on oublie) +const DONE = { + analyze: () => ({ title: 'Fiche projet à jour', level: 'ok' }), + prospect: (r) => ({ title: 'Recherche de prospects terminée', description: `${r?.found ?? 0} nouveau(x) prospect(s) sur ${r?.requested ?? '?'} demandés.`, level: 'ok' }), + send: (r) => ({ title: 'Envoi terminé', description: `${r?.sent ?? 0} mail(s) envoyé(s), ${r?.failed ?? 0} échec(s).`, level: r?.failed ? 'warn' : 'ok' }), + evolution: (r) => ({ title: 'Évolutions prêtes', description: `Envoyées à ${r?.sentTo ?? 'ta boîte'}.`, level: 'ok' }), +}; +const LABEL = { analyze: 'Analyse', prospect: 'Recherche', template: 'Modèle de mail', followup_template: 'Modèle de relance', send: 'Envoi', followup: 'Relances', evolution: 'Évolutions' }; + +export function notifyJob(app, job, { status, result, error }) { + const project = job.project_id ? app.db.prepare('SELECT name FROM projects WHERE id = ?').get(job.project_id)?.name : null; + const prefix = project ? `${project} · ` : ''; + if (status === 'error') { + return notify(app, 'job_error', { title: `${prefix}${LABEL[job.type] || job.type} en échec`, description: String(error || '').slice(0, 500), level: 'error' }); + } + if (status !== 'done') return Promise.resolve(false); + if (job.type === 'followup') { + if (!result?.sent) return Promise.resolve(false); + return notify(app, 'followup', { title: `${prefix}Relances envoyées`, description: `${result.sent} relance(s), ${result.failed} échec(s).`, level: 'info' }); + } + const make = DONE[job.type]; + if (!make) return Promise.resolve(false); + const n = make(result); + return notify(app, 'job_done', { ...n, title: `${prefix}${n.title}` }); +} diff --git a/src/views.js b/src/views.js index e8d551d..0273e9a 100644 --- a/src/views.js +++ b/src/views.js @@ -251,6 +251,15 @@ ${saved ? '

Enregistré.

' : ''} +

Notifications Discord

+

Salon Discord › Modifier › Intégrations › Webhooks › Nouveau webhook › Copier l'URL.

+ + ${s.discord.set ? '' : ''} +
+ ${Object.entries(s.discord.all).map(([k, label]) => ``).join('')} +
+ ${s.discord.set ? '' : ''} +

Garde-fous

diff --git a/test/http.test.js b/test/http.test.js index b37f721..ec19975 100644 --- a/test/http.test.js +++ b/test/http.test.js @@ -174,3 +174,21 @@ test('« Cette nuit » programme le job au prochain créneau 1h-6h', async () => const sys = await (await get('/api/system')).json(); assert.ok(job.run_after > now() ? sys.scheduled >= 1 : true); }); + +test('réglages Discord : URL validée, chiffrée, événements enregistrés', async () => { + const base = { notify_email: 'moi@x.fr', forgejo_host: 'git.tony-averty.dev', global_daily_cap: '100', send_delay_min: '20', send_delay_max: '60' }; + let r = await post('/settings', { ...base, discord_webhook: 'https://evil.com/api/webhooks/1/x' }, { form: true }); + assert.equal(r.status, 400); + const hook = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123'; + r = await post('/settings', { ...base, discord_webhook: hook, ev_reply: 'on', ev_job_error: 'on' }, { form: true }); + assert.equal(r.status, 303); + const enc = app.db.prepare("SELECT value FROM settings WHERE key = 'discord_webhook_enc'").get().value; + assert.ok(!enc.includes('abcdefghijklmnop'), 'URL chiffrée'); + assert.deepEqual(JSON.parse(app.db.prepare("SELECT value FROM settings WHERE key = 'discord_events'").get().value), ['job_error', 'reply']); + r = await get('/settings'); + const page = await r.text(); + assert.ok(!page.includes('abcdefghijklmnop'), 'URL jamais réaffichée'); + assert.match(page, /data-notify-test/); + r = await post('/settings', { ...base, discord_remove: 'on' }, { form: true }); + assert.equal(app.db.prepare("SELECT value FROM settings WHERE key = 'discord_webhook_enc'").get().value, null); +}); diff --git a/test/notify.test.js b/test/notify.test.js new file mode 100644 index 0000000..f645727 --- /dev/null +++ b/test/notify.test.js @@ -0,0 +1,104 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; +import { openDb, now, setSetting } from '../src/db.js'; +import { encrypt } from '../src/crypto.js'; +import { notify, notifyJob, WEBHOOK_RE } from '../src/services/notify.js'; +import { Worker, enqueue } from '../src/services/jobs.js'; +import { checkInbox } from '../src/services/inbox.js'; +import { createProject, saveSecretConfig } from '../src/projects.js'; + +const HOOK = 'https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyz-ABC_123'; + +function setup({ events } = {}) { + const db = openDb(':memory:'); + const sent = []; + const app = { + db, cfg: { secretKey: randomBytes(32), appUrl: 'https://ai.test' }, + fetch: async (url, opts) => { sent.push({ url, body: JSON.parse(opts.body) }); return { ok: true, status: 204 }; }, + }; + setSetting(db, 'discord_webhook_enc', encrypt(app.cfg.secretKey, HOOK)); + if (events) setSetting(db, 'discord_events', JSON.stringify(events)); + const id = createProject(app, { name: 'MonEspacePro', gitUrl: 'https://g/T/M.git' }); + return { db, app, sent, id }; +} + +test('validation stricte de l\'URL de webhook', () => { + assert.ok(WEBHOOK_RE.test(HOOK)); + assert.ok(WEBHOOK_RE.test(HOOK.replace('discord.com', 'discordapp.com'))); + for (const bad of ['http://discord.com/api/webhooks/123456789/abcdefghijklmnopqrstuvwxyz', 'https://evil.com/api/webhooks/123456789/abcdefghijklmnopqrstuvwxyz', + 'https://discord.com.evil.com/api/webhooks/123456789/abcdefghijklmnopqrstuvwxyz', `${HOOK}?wait=true`, 'https://discord.com/api/webhooks/1/a']) { + assert.ok(!WEBHOOK_RE.test(bad), bad); + } +}); + +test('notif : forme du message, aucune mention possible', async () => { + const s = setup(); + assert.equal(await notify(s.app, 'reply', { title: '@everyone Boulangerie', description: 'x', level: 'ok', fields: [{ name: 'a', value: '' }] }), true); + const b = s.sent[0].body; + assert.equal(s.sent[0].url, HOOK); + assert.deepEqual(b.allowed_mentions, { parse: [] }); + assert.equal(b.embeds[0].title, '@everyone Boulangerie'); + assert.equal(b.embeds[0].color, 0x15803d); + assert.equal(b.embeds[0].fields[0].value, '-'); +}); + +test('événement désactivé, webhook absent ou Discord en panne : rien ne casse', async () => { + const s = setup({ events: ['job_error'] }); + assert.equal(await notify(s.app, 'reply', { title: 'x' }), false); + assert.equal(s.sent.length, 0); + assert.equal(await notify(s.app, 'reply', { title: 'x' }, { force: true }), true, 'le bouton de test force l\'envoi'); + const warn = console.warn; console.warn = () => {}; + try { + s.app.fetch = async () => ({ ok: false, status: 404 }); + assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false); + s.app.fetch = async () => { throw new Error('réseau'); }; + assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false); + } finally { console.warn = warn; } + setSetting(s.db, 'discord_webhook_enc', null); + assert.equal(await notify(s.app, 'job_error', { title: 'x' }), false); +}); + +test('fin de job : succès, erreur, relances, et silence pour les jobs courts', async () => { + const s = setup(); + const job = (type) => ({ type, project_id: s.id }); + await notifyJob(s.app, job('prospect'), { status: 'done', result: { found: 7, requested: 10 } }); + await notifyJob(s.app, job('send'), { status: 'error', error: 'SMTP refusé' }); + await notifyJob(s.app, job('followup'), { status: 'done', result: { sent: 3, failed: 0 } }); + await notifyJob(s.app, job('followup'), { status: 'done', result: { sent: 0, postponed: true } }); + await notifyJob(s.app, job('template'), { status: 'done', result: {} }); + assert.deepEqual(s.sent.map((x) => x.body.embeds[0].title), [ + 'MonEspacePro · Recherche de prospects terminée', + 'MonEspacePro · Envoi en échec', + 'MonEspacePro · Relances envoyées', + ]); + assert.match(s.sent[0].body.embeds[0].description, /7 nouveau\(x\) prospect\(s\) sur 10/); +}); + +test('le worker notifie en fin de job, et un callback qui plante ne le bloque pas', async () => { + const s = setup(); + const seen = []; + const w = new Worker(s.db, { prospect: async () => ({ found: 2, requested: 5 }), evolution: async () => { throw new Error('boom'); } }, { + thermalMax: 999, log: { error() {} }, + onFinish: (job, r) => { seen.push(`${job.type}:${r.status}`); if (job.type === 'evolution') throw new Error('callback cassé'); }, + }); + enqueue(s.db, { projectId: s.id, type: 'prospect' }); + enqueue(s.db, { projectId: s.id, type: 'evolution' }); + await w.tick(); await w.tick(); + assert.deepEqual(seen, ['prospect:done', 'evolution:error']); + assert.equal(s.db.prepare("SELECT COUNT(*) n FROM jobs WHERE status IN ('done','error')").get().n, 2); +}); + +test('nouvelles réponses détectées → une notif avec les entreprises', async () => { + const s = setup(); + saveSecretConfig(s.app, s.id, 'smtp_enc', { host: 'h', user: 'u', pass: 'p', fromEmail: 'a@x.fr' }, 'pass'); + saveSecretConfig(s.app, s.id, 'imap_enc', { host: 'imap.x' }, 'pass'); + s.db.prepare("INSERT INTO prospects(project_id, company, email, status, sent_at, created_at) VALUES(?, 'Le Fournil', 'contact@fournil.fr', 'sent', ?, ?)").run(s.id, now(), now()); + s.app.fetchInbox = async () => ({ uidValidity: '1', lastUid: 1, messages: [{ uid: 1, from: 'contact@fournil.fr', subject: 'Re: idée' }] }); + await checkInbox(s.app, s.id); + assert.equal(s.sent.length, 1); + assert.equal(s.sent[0].body.embeds[0].title, 'MonEspacePro · 1 réponse(s) de prospect'); + assert.match(s.sent[0].body.embeds[0].description, /\*\*Le Fournil\*\* \(contact@fournil\.fr\) : Re: idée/); + await checkInbox(s.app, s.id); + assert.equal(s.sent.length, 1, 'pas de notif quand rien de neuf'); +});