diff --git a/src/config.js b/src/config.js new file mode 100644 index 0000000..c9e4f83 --- /dev/null +++ b/src/config.js @@ -0,0 +1,30 @@ +import { resolve } from 'node:path'; + +const env = process.env; + +function required(name) { + const v = env[name]; + if (!v) throw new Error(`Variable d'environnement manquante : ${name}`); + return v; +} + +export function loadConfig() { + const secretKey = required('SECRET_KEY'); + if (!/^[0-9a-f]{64}$/i.test(secretKey)) { + throw new Error('SECRET_KEY doit faire 32 octets en hexadécimal (64 caractères)'); + } + return { + appUrl: required('APP_URL').replace(/\/$/, ''), + port: Number(env.PORT || 3100), + host: env.HOST || '127.0.0.1', + google: { + clientId: required('GOOGLE_CLIENT_ID'), + clientSecret: required('GOOGLE_CLIENT_SECRET'), + }, + allowedEmails: required('ALLOWED_EMAILS').split(',').map((e) => e.trim().toLowerCase()).filter(Boolean), + secretKey: Buffer.from(secretKey, 'hex'), + dataDir: resolve(env.DATA_DIR || './data'), + claudeBin: env.CLAUDE_BIN || 'claude', + thermalMax: Number(env.THERMAL_MAX || 75), + }; +} diff --git a/src/crypto.js b/src/crypto.js new file mode 100644 index 0000000..40a19ff --- /dev/null +++ b/src/crypto.js @@ -0,0 +1,35 @@ +// Chiffrement AES-256-GCM des secrets stockés en BDD (mdp SMTP/BDD, token Forgejo). +import { createCipheriv, createDecipheriv, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'; + +export function encrypt(key, plain) { + if (plain == null || plain === '') return null; + const iv = randomBytes(12); + const c = createCipheriv('aes-256-gcm', key, iv); + const data = Buffer.concat([c.update(String(plain), 'utf8'), c.final()]); + return `v1:${iv.toString('base64')}:${c.getAuthTag().toString('base64')}:${data.toString('base64')}`; +} + +export function decrypt(key, payload) { + if (!payload) return null; + const [v, iv, tag, data] = payload.split(':'); + if (v !== 'v1') throw new Error('Format de secret inconnu'); + const d = createDecipheriv('aes-256-gcm', key, Buffer.from(iv, 'base64')); + d.setAuthTag(Buffer.from(tag, 'base64')); + return Buffer.concat([d.update(Buffer.from(data, 'base64')), d.final()]).toString('utf8'); +} + +export function encryptJson(key, obj) { return obj ? encrypt(key, JSON.stringify(obj)) : null; } +export function decryptJson(key, payload) { const s = decrypt(key, payload); return s ? JSON.parse(s) : null; } + +// Token de désinscription sans état : HMAC de l'email +export function unsubToken(key, email) { + return createHmac('sha256', key).update(`unsub:${email.toLowerCase()}`).digest('base64url').slice(0, 32); +} + +export function verifyUnsubToken(key, email, token) { + const expected = Buffer.from(unsubToken(key, email)); + const got = Buffer.from(String(token || '')); + return expected.length === got.length && timingSafeEqual(expected, got); +} + +export const randomId = (bytes = 32) => randomBytes(bytes).toString('base64url'); diff --git a/src/db.js b/src/db.js new file mode 100644 index 0000000..40d2d88 --- /dev/null +++ b/src/db.js @@ -0,0 +1,106 @@ +import { DatabaseSync } from 'node:sqlite'; +import { mkdirSync } from 'node:fs'; +import { join } from 'node:path'; + +// Chaque entrée = une migration. Ne jamais modifier une migration déjà livrée, en ajouter une. +const MIGRATIONS = [ + ` + CREATE TABLE sessions ( + id TEXT PRIMARY KEY, email TEXT NOT NULL, + created_at INTEGER NOT NULL, expires_at INTEGER NOT NULL + ); + CREATE TABLE oauth_states ( + state TEXT PRIMARY KEY, verifier TEXT NOT NULL, nonce TEXT NOT NULL, created_at INTEGER NOT NULL + ); + CREATE TABLE settings (key TEXT PRIMARY KEY, value TEXT); + CREATE TABLE projects ( + id INTEGER PRIMARY KEY, + name TEXT NOT NULL, + git_url TEXT NOT NULL UNIQUE, + profile_json TEXT, -- fiche projet générée par Claude + profile_commit TEXT, -- commit analysé + profile_at INTEGER, + target_json TEXT, -- cible déduite (modifiable) + target_validated INTEGER NOT NULL DEFAULT 0, + smtp_enc TEXT, -- config SMTP chiffrée + db_enc TEXT, -- accès BDD chiffré (récap) + daily_mail_cap INTEGER NOT NULL DEFAULT 30, + created_at INTEGER NOT NULL + ); + CREATE TABLE mail_templates ( + project_id INTEGER PRIMARY KEY REFERENCES projects(id) ON DELETE CASCADE, + subject TEXT NOT NULL, body TEXT NOT NULL, + status TEXT NOT NULL DEFAULT 'draft', -- draft | validated + updated_at INTEGER NOT NULL + ); + CREATE TABLE prospects ( + id INTEGER PRIMARY KEY, + project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + company TEXT NOT NULL, email TEXT NOT NULL, website TEXT, city TEXT, sector TEXT, + hook TEXT, -- accroche perso (1 phrase) + source TEXT, -- page où l'email a été trouvé (RGPD : origine des données) + score INTEGER, + status TEXT NOT NULL DEFAULT 'new', -- new | sent | replied | client | refused | bounced + sent_at INTEGER, created_at INTEGER NOT NULL, + UNIQUE(project_id, email) + ); + CREATE INDEX prospects_project ON prospects(project_id, status); + CREATE TABLE blacklist (email TEXT PRIMARY KEY, reason TEXT, created_at INTEGER NOT NULL); + CREATE TABLE jobs ( + id INTEGER PRIMARY KEY, + project_id INTEGER REFERENCES projects(id) ON DELETE CASCADE, + type TEXT NOT NULL, -- analyze | prospect | template | send | evolution + status TEXT NOT NULL DEFAULT 'queued', -- queued | running | done | error | cancelled + params_json TEXT, progress_json TEXT, result_json TEXT, error TEXT, + cost_usd REAL, tokens_in INTEGER, tokens_out INTEGER, + created_at INTEGER NOT NULL, started_at INTEGER, finished_at INTEGER + ); + CREATE INDEX jobs_status ON jobs(status, id); + CREATE TABLE mail_log ( + id INTEGER PRIMARY KEY, + project_id INTEGER NOT NULL REFERENCES projects(id) ON DELETE CASCADE, + prospect_id INTEGER, email TEXT NOT NULL, sent_at INTEGER NOT NULL, error TEXT + ); + CREATE INDEX mail_log_day ON mail_log(project_id, sent_at); + `, +]; + +export function openDb(dataDir) { + let db; + if (dataDir === ':memory:') db = new DatabaseSync(':memory:'); + else { + mkdirSync(dataDir, { recursive: true }); + db = new DatabaseSync(join(dataDir, 'aitools.sqlite')); + } + // WAL + synchronous NORMAL : moins d'écritures sur la carte SD / SSD + db.exec('PRAGMA journal_mode = WAL; PRAGMA synchronous = NORMAL; PRAGMA foreign_keys = ON; PRAGMA busy_timeout = 5000;'); + migrate(db); + return db; +} + +function migrate(db) { + const { user_version: current } = db.prepare('PRAGMA user_version').get(); + for (let i = current; i < MIGRATIONS.length; i++) { + db.exec('BEGIN'); + try { + db.exec(MIGRATIONS[i]); + db.exec(`PRAGMA user_version = ${i + 1}`); + db.exec('COMMIT'); + } catch (e) { + db.exec('ROLLBACK'); + throw e; + } + } +} + +export const now = () => Math.floor(Date.now() / 1000); + +export function getSetting(db, key, fallback = null) { + const row = db.prepare('SELECT value FROM settings WHERE key = ?').get(key); + return row ? row.value : fallback; +} + +export function setSetting(db, key, value) { + db.prepare('INSERT INTO settings(key, value) VALUES(?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value') + .run(key, value); +} diff --git a/src/http.js b/src/http.js new file mode 100644 index 0000000..c3b61c0 --- /dev/null +++ b/src/http.js @@ -0,0 +1,75 @@ +// Mini-routeur + helpers HTTP. Pas de framework : moins de RAM, moins de surface. + +export class Router { + constructor() { this.routes = []; } + add(method, path, handler, opts = {}) { + const keys = []; + const re = new RegExp('^' + path.replace(/:(\w+)/g, (_, k) => { keys.push(k); return '([^/]+)'; }) + '/?$'); + this.routes.push({ method, re, keys, handler, public: !!opts.public }); + } + get(p, h, o) { this.add('GET', p, h, o); } + post(p, h, o) { this.add('POST', p, h, o); } + match(method, pathname) { + for (const r of this.routes) { + if (r.method !== method) continue; + const m = r.re.exec(pathname); + if (m) { + const params = {}; + r.keys.forEach((k, i) => { params[k] = decodeURIComponent(m[i + 1]); }); + return { ...r, params }; + } + } + return null; + } +} + +export function parseCookies(req) { + const out = {}; + for (const part of (req.headers.cookie || '').split(';')) { + const i = part.indexOf('='); + if (i > 0) out[part.slice(0, i).trim()] = decodeURIComponent(part.slice(i + 1).trim()); + } + return out; +} + +export function setCookie(res, name, value, { maxAge, httpOnly = true } = {}) { + const parts = [`${name}=${encodeURIComponent(value)}`, 'Path=/', 'SameSite=Lax', 'Secure']; + if (httpOnly) parts.push('HttpOnly'); + if (maxAge !== undefined) parts.push(`Max-Age=${maxAge}`); + const prev = res.getHeader('Set-Cookie'); + res.setHeader('Set-Cookie', [...(Array.isArray(prev) ? prev : prev ? [prev] : []), parts.join('; ')]); +} + +const MAX_BODY = 256 * 1024; + +export async function readBody(req) { + const chunks = []; + let size = 0; + for await (const c of req) { + size += c.length; + if (size > MAX_BODY) throw Object.assign(new Error('Requête trop volumineuse'), { status: 413 }); + chunks.push(c); + } + const raw = Buffer.concat(chunks).toString('utf8'); + const type = req.headers['content-type'] || ''; + if (type.includes('application/json')) return raw ? JSON.parse(raw) : {}; + return Object.fromEntries(new URLSearchParams(raw)); +} + +export function send(res, status, body, type = 'text/html; charset=utf-8') { + res.writeHead(status, { 'Content-Type': type }); + res.end(body); +} + +export const html = (res, body, status = 200) => send(res, status, body); +export const json = (res, data, status = 200) => send(res, status, JSON.stringify(data), 'application/json; charset=utf-8'); +export function redirect(res, location) { res.writeHead(303, { Location: location }); res.end(); } + +export class HttpError extends Error { + constructor(status, message) { super(message); this.status = status; } +} + +// Échappement HTML pour les templates +export function esc(v) { + return String(v ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c])); +} diff --git a/test/core.test.js b/test/core.test.js new file mode 100644 index 0000000..2d9b48e --- /dev/null +++ b/test/core.test.js @@ -0,0 +1,65 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { randomBytes } from 'node:crypto'; +import { encrypt, decrypt, encryptJson, decryptJson, unsubToken, verifyUnsubToken } from '../src/crypto.js'; +import { openDb, getSetting, setSetting } from '../src/db.js'; +import { Router, esc } from '../src/http.js'; +import { checkIdTokenClaims, checkOrigin } from '../src/auth.js'; + +const key = randomBytes(32); + +test('chiffrement aller-retour et altération détectée', () => { + const enc = encrypt(key, 'mot de passe é'); + assert.equal(decrypt(key, enc), 'mot de passe é'); + assert.deepEqual(decryptJson(key, encryptJson(key, { a: 1 })), { a: 1 }); + const parts = enc.split(':'); + parts[3] = Buffer.from('autre').toString('base64'); + assert.throws(() => decrypt(key, parts.join(':'))); + assert.equal(encrypt(key, ''), null); +}); + +test('token de désinscription', () => { + const t = unsubToken(key, 'Foo@Bar.fr'); + assert.ok(verifyUnsubToken(key, 'foo@bar.fr', t)); + assert.ok(!verifyUnsubToken(key, 'autre@bar.fr', t)); + assert.ok(!verifyUnsubToken(key, 'foo@bar.fr', 'x')); +}); + +test('migrations et settings', () => { + const db = openDb(':memory:'); + assert.equal(db.prepare('PRAGMA user_version').get().user_version, 1); + setSetting(db, 'a', '1'); setSetting(db, 'a', '2'); + assert.equal(getSetting(db, 'a'), '2'); + assert.equal(getSetting(db, 'nope', 'x'), 'x'); +}); + +test('router avec paramètres', () => { + const r = new Router(); + r.get('/projects/:id', () => 'ok'); + assert.deepEqual(r.match('GET', '/projects/42').params, { id: '42' }); + assert.equal(r.match('POST', '/projects/42'), null); + assert.equal(r.match('GET', '/projects/42/x'), null); +}); + +test('échappement HTML', () => { + assert.equal(esc('\'&'), '<a href="x">'&'); +}); + +test('claims id_token Google', () => { + const base = { iss: 'https://accounts.google.com', aud: 'cid', exp: 2e9, nonce: 'n', email_verified: true, email: 'Me@Gmail.com' }; + const opts = { clientId: 'cid', nonce: 'n', allowedEmails: ['me@gmail.com'], at: 1e9 }; + assert.equal(checkIdTokenClaims(base, opts), 'me@gmail.com'); + assert.throws(() => checkIdTokenClaims({ ...base, email: 'pirate@gmail.com' }, opts), /non autorisé/); + assert.throws(() => checkIdTokenClaims({ ...base, aud: 'x' }, opts), /Audience/); + assert.throws(() => checkIdTokenClaims({ ...base, nonce: 'z' }, opts), /Nonce/); + assert.throws(() => checkIdTokenClaims({ ...base, email_verified: false }, opts), /vérifié/); + assert.throws(() => checkIdTokenClaims({ ...base, exp: 1 }, opts), /expiré/); +}); + +test('contrôle d\'origine', () => { + const cfg = { appUrl: 'https://ai.tony-averty.dev' }; + assert.doesNotThrow(() => checkOrigin({ method: 'GET', headers: {} }, cfg)); + assert.doesNotThrow(() => checkOrigin({ method: 'POST', headers: { origin: cfg.appUrl } }, cfg)); + assert.throws(() => checkOrigin({ method: 'POST', headers: { origin: 'https://evil.com' } }, cfg)); + assert.throws(() => checkOrigin({ method: 'POST', headers: {} }, cfg)); +});