From a3188356dd885cfefd834a7e2819c407fe1c3bea Mon Sep 17 00:00:00 2001 From: Tony AVERTY Date: Thu, 22 Oct 2026 14:34:03 +0200 Subject: [PATCH] =?UTF-8?q?feat(security):=20limitation=20de=20d=C3=A9bit?= =?UTF-8?q?=20en=20m=C3=A9moire=20par=20IP=20et=20par=20compte?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Fenêtre glissante sans dépendance, seuils réunis dans src/limits.js. Appliquée aux démarrages et retours de connexion, aux routes /link, à l'export et l'import CSV, aux envois, à la création de projet, à la suppression de compte et aux tests de connexion. Réponse 429 avec Retry-After. TRUST_PROXY (désactivé par défaut) autorise la lecture de X-Forwarded-For uniquement depuis un proxy de confiance, de droite à gauche. --- src/config.js | 3 + src/http.js | 11 ++- src/ip.js | 87 +++++++++++++++++ src/limits.js | 78 +++++++++++++++ src/ratelimit.js | 111 +++++++++++++++++++++ src/routes.js | 39 ++++---- src/server.js | 15 ++- test/helpers/server.js | 17 +++- test/ratelimit.test.js | 212 +++++++++++++++++++++++++++++++++++++++++ 9 files changed, 543 insertions(+), 30 deletions(-) create mode 100644 src/ip.js create mode 100644 src/limits.js create mode 100644 src/ratelimit.js create mode 100644 test/ratelimit.test.js diff --git a/src/config.js b/src/config.js index a95e502..e4b2f2f 100644 --- a/src/config.js +++ b/src/config.js @@ -1,6 +1,7 @@ import { resolve } from 'node:path'; import { homedir } from 'node:os'; import { dbConfigFromEnv } from './db.js'; +import { parseTrustProxy } from './ratelimit.js'; const env = process.env; @@ -68,5 +69,7 @@ export function loadConfig() { cliModeEnabled: flag(env.CLAUDE_CLI_MODE_ENABLED, true), sandbox: sandboxConfig(), thermalMax: Number(env.THERMAL_MAX || 75), + // Derrière Nginx/CloudPanel : lire X-Forwarded-For, mais seulement depuis un proxy de confiance (voir ratelimit.js) + trustProxy: parseTrustProxy(env.TRUST_PROXY), }; } diff --git a/src/http.js b/src/http.js index acb7ab7..9cd12c1 100644 --- a/src/http.js +++ b/src/http.js @@ -5,7 +5,7 @@ export class Router { 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 }); + this.routes.push({ method, re, keys, handler, public: !!opts.public, limit: opts.limit || null, admin: !!opts.admin }); } get(p, h, o) { this.add('GET', p, h, o); } post(p, h, o) { this.add('POST', p, h, o); } @@ -65,9 +65,14 @@ 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(); } -// `expose` : message sûr destiné à l'utilisateur même pour un 5xx (ex. impossible de joindre un service tiers) +// `expose` : message sûr destiné à l'utilisateur même pour un 5xx (ex. impossible de joindre un service tiers). +// `headers` : en-têtes ajoutés à la réponse d'erreur (Retry-After d'un 429). `code` et `data` : champs ajoutés au JSON +// d'erreur, pour que le front distingue un plafond de plan (plan_limit) d'une erreur ordinaire. export class HttpError extends Error { - constructor(status, message, { expose = false } = {}) { super(message); this.status = status; this.expose = expose; } + constructor(status, message, { expose = false, headers = null, code = null, data = null } = {}) { + super(message); + this.status = status; this.expose = expose; this.headers = headers; this.code = code; this.data = data; + } } // Échappement HTML pour les templates diff --git a/src/ip.js b/src/ip.js new file mode 100644 index 0000000..1381e65 --- /dev/null +++ b/src/ip.js @@ -0,0 +1,87 @@ +// Analyse des adresses IP : lecture IPv4/IPv6, adresses privées ou réservées, forme canonique. +// Sert au filtrage des hôtes saisis par l'utilisateur (netguard.js) et à la lecture de l'IP du client (ratelimit.js). +import { isIP } from 'node:net'; + +/** @returns {{family: 4|6, bytes: number[]} | null} */ +export function parseIp(input) { + let s = String(input ?? '').trim().replace(/^\[|\]$/g, ''); + const zone = s.indexOf('%'); + if (zone >= 0) s = s.slice(0, zone); + const family = isIP(s); + if (family === 4) return { family, bytes: s.split('.').map(Number) }; + if (family !== 6) return null; + let head = s; + const quad = /^(.*:)(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(s); // ::ffff:127.0.0.1 + if (quad) head = `${quad[1]}${((+quad[2] << 8) | +quad[3]).toString(16)}:${((+quad[4] << 8) | +quad[5]).toString(16)}`; + const [a, b] = head.split('::'); + const left = a ? a.split(':') : []; + const right = b ? b.split(':') : []; + const groups = b === undefined ? left : [...left, ...Array(8 - left.length - right.length).fill('0'), ...right]; + return { family, bytes: groups.flatMap((g) => { const v = parseInt(g, 16); return [v >> 8, v & 255]; }) }; +} + +const inV4 = (b, base, bits) => { + let rest = bits; + for (let i = 0; i < 4 && rest > 0; i++, rest -= 8) { + const mask = rest >= 8 ? 0xff : (0xff << (8 - rest)) & 0xff; + if ((b[i] & mask) !== (base[i] & mask)) return false; + } + return true; +}; + +const V4_BLOCKED = [ + [[0, 0, 0, 0], 8, 'adresse non routable'], + [[10, 0, 0, 0], 8, 'réseau privé'], + [[100, 64, 0, 0], 10, 'réseau partagé (CGNAT)'], + [[127, 0, 0, 0], 8, 'boucle locale'], + [[169, 254, 0, 0], 16, 'adresse locale (dont les métadonnées cloud)'], + [[172, 16, 0, 0], 12, 'réseau privé'], + [[192, 0, 0, 0], 24, 'adresse réservée'], + [[192, 0, 2, 0], 24, 'adresse de documentation'], + [[192, 168, 0, 0], 16, 'réseau privé'], + [[198, 18, 0, 0], 15, 'adresse de test réseau'], + [[198, 51, 100, 0], 24, 'adresse de documentation'], + [[203, 0, 113, 0], 24, 'adresse de documentation'], + [[224, 0, 0, 0], 4, 'multicast'], + [[240, 0, 0, 0], 4, 'adresse réservée'], +]; + +function blockedV4(b) { + for (const [base, bits, why] of V4_BLOCKED) if (inV4(b, base, bits)) return why; + return null; +} + +/** Raison du refus d'une adresse IP (texte pour l'utilisateur), ou null si elle est publique. Texte non IP : refusé. */ +export function blockedReason(ip) { + const p = parseIp(ip); + if (!p) return 'adresse invalide'; + if (p.family === 4) return blockedV4(p.bytes); + const b = p.bytes; + const zeros = (from, to) => b.slice(from, to).every((x) => x === 0); + if (zeros(0, 10) && b[10] === 0xff && b[11] === 0xff) return blockedV4(b.slice(12)); // IPv4 mappée (::ffff:a.b.c.d) + if (zeros(0, 12)) return 'boucle locale'; // ::, ::1 et ::a.b.c.d (IPv4 « compatible ») + if (b[0] === 0 && b[1] === 0x64 && b[2] === 0xff && b[3] === 0x9b) { // NAT64 : l'IPv4 est dans les 4 derniers octets + return zeros(4, 12) ? blockedV4(b.slice(12)) : 'adresse réservée (NAT64)'; + } + if (b[0] === 0x20 && b[1] === 0x02) return blockedV4(b.slice(2, 6)); // 6to4 : l'IPv4 est dans les octets 2 à 5 + if (b[0] === 0x20 && b[1] === 0x01 && b[2] === 0 && b[3] === 0) return 'adresse de tunnel (Teredo)'; + if (b[0] === 0x20 && b[1] === 0x01 && b[2] === 0x0d && b[3] === 0xb8) return 'adresse de documentation'; + if (b[0] === 0x01 && zeros(1, 8)) return 'adresse réservée'; // 100::/64 + if ((b[0] & 0xfe) === 0xfc) return 'réseau privé (fc00::/7)'; + if (b[0] === 0xfe && (b[1] & 0xc0) === 0x80) return 'adresse locale (fe80::/10)'; + if (b[0] === 0xfe && (b[1] & 0xc0) === 0xc0) return 'adresse locale (fec0::/10)'; + if (b[0] === 0xff) return 'multicast'; + return null; +} + +/** Forme canonique d'une adresse client : une IPv4 mappée (::ffff:1.2.3.4) redevient 1.2.3.4. */ +export function normalizeIp(input) { + const p = parseIp(input); + if (!p) return String(input ?? '').trim(); + if (p.family === 4) return p.bytes.join('.'); + const b = p.bytes; + if (b.slice(0, 10).every((x) => x === 0) && b[10] === 0xff && b[11] === 0xff) return b.slice(12).join('.'); + const g = []; for (let i = 0; i < 16; i += 2) g.push(((b[i] << 8) | b[i + 1]).toString(16)); + return g.join(':'); +} + diff --git a/src/limits.js b/src/limits.js new file mode 100644 index 0000000..b70a61c --- /dev/null +++ b/src/limits.js @@ -0,0 +1,78 @@ +// Configuration unique des seuils : débit, plafonds des plans, détection d'abus, ports autorisés. +// Tout ce qui se règle (fenêtre, nombre de requêtes, plafond d'un plan) se règle ICI et nulle part ailleurs ; +// les pages Tarifs et Fonctionnement lisent aussi ces valeurs, pour ne jamais annoncer un chiffre différent du code. + +const MIN = 60_000; +const HOUR = 60 * MIN; + +/** + * Limitation de débit, en mémoire. Chaque règle donne, par portée, un nombre maximal de requêtes sur une fenêtre glissante. + * - `ip` : adresse du client (voir TRUST_PROXY dans la configuration) ; + * - `user` : compte connecté. + * Une requête passe seulement si toutes les portées de la règle l'acceptent. + */ +export const RATE_LIMITS = { + // Connexion : démarrage (Google, Apple) et retours des fournisseurs + auth_start: { ip: { max: 20, windowMs: 10 * MIN } }, + auth_callback: { ip: { max: 40, windowMs: 10 * MIN } }, + // Liaison Claude : chaque essai de clé ou de jeton coûte un appel réseau chez Anthropic + link: { user: { max: 10, windowMs: 10 * MIN }, ip: { max: 30, windowMs: 10 * MIN } }, + // Export / import CSV + csv: { user: { max: 10, windowMs: 10 * MIN } }, + // Envois : lancement d'un lot, rapport par mail, notification de test + mail_send: { user: { max: 30, windowMs: HOUR } }, + // Création de projet (clone du dépôt, analyse) + project_create: { user: { max: 10, windowMs: HOUR } }, + // Suppression de compte + account_delete: { user: { max: 5, windowMs: HOUR }, ip: { max: 10, windowMs: HOUR } }, + // Tests de connexion vers les services de l'utilisateur (IMAP, base du récap, SMTP) + conn_test: { user: { max: 20, windowMs: 10 * MIN } }, + // Back-office + admin: { user: { max: 120, windowMs: MIN } }, +}; + +/** + * Plafonds par plan. `null` = illimité. + * - `projects` et `prospects` : totaux du compte ; + * - `mails` et `aiJobs` : par mois calendaire, heure de Paris. + * Le plan « pro » n'est pas encore défini commercialement : illimité en attendant (voir docs/JOURNAL.md). + */ +export const PLAN_LIMITS = { + free: { projects: 1, prospects: 50, mails: 100, aiJobs: 5 }, + pro: { projects: null, prospects: null, mails: null, aiJobs: null }, + admin: { projects: null, prospects: null, mails: null, aiJobs: null }, +}; +export const PLAN_LABELS = { free: 'gratuit', pro: 'pro', admin: 'administrateur' }; +export const PAID_PLANS = ['free', 'pro']; // plans qu'un administrateur peut attribuer depuis le back-office + +/** Détection d'abus à l'envoi : pause du compte quand trop de mails sont rejetés. */ +export const ABUSE = { + minSent: 50, // pas de décision avant ce nombre de prospects contactés + maxBounceRate: 0.10, // pause au-dessus de 10 % de rejets + windowDays: 30, // fenêtre d'observation +}; + +/** Comptes inactifs : avertissement avant suppression, durée de conservation du journal d'administration. */ +export const INACTIVITY = { + defaultMonths: 24, + warningDays: 30, + auditRetentionMonths: 12, +}; + +/** Pagination du back-office. */ +export const ADMIN_PAGE_SIZE = 25; + +/** + * Ports autorisés pour les hôtes saisis par l'utilisateur. Les ports de services managés connus (DigitalOcean, par exemple) + * sont inclus ; tout autre port est refusé, sauf pour un administrateur avec ALLOW_PRIVATE_HOSTS. + */ +export const ALLOWED_PORTS = { + smtp: [25, 465, 587, 2525], + imap: [143, 993], + mysql: [3306, 3307, 25060], + pg: [5432, 5433, 25061], + git: [443, 8443], +}; + +/** Charge serveur : au-delà de ce rapport charge/cœurs, les nouveaux jobs IA attendent (reprise 0,1 plus bas). */ +export const LOAD = { defaultMax: 0.9, resumeGap: 0.1 }; diff --git a/src/ratelimit.js b/src/ratelimit.js new file mode 100644 index 0000000..e208d8c --- /dev/null +++ b/src/ratelimit.js @@ -0,0 +1,111 @@ +// Limitation de débit en mémoire (fenêtre glissante), sans dépendance. Une règle de src/limits.js donne, par portée +// (adresse IP, compte), un nombre maximal de requêtes par fenêtre. Les compteurs vivent dans le processus : un redémarrage +// les remet à zéro, et plusieurs instances ne les partagent pas (une seule instance en production, voir le cadrage). +import { BlockList, isIP } from 'node:net'; +import { RATE_LIMITS } from './limits.js'; +import { parseIp, normalizeIp } from './ip.js'; +import { HttpError } from './http.js'; + +// ---------- Adresse du client ---------- + +/** + * TRUST_PROXY : vide, `false` ou `0` (défaut) = on ne lit jamais X-Forwarded-For ; `true`, `1` ou `loopback` = on le lit + * seulement si la connexion arrive d'un proxy local (Nginx sur la même machine) ; sinon une liste d'adresses ou de + * plages CIDR séparées par des virgules (`127.0.0.1,10.0.0.0/8`) : les proxys de confiance. + * @returns {{trusts: (ip: string) => boolean} | null} + */ +export function parseTrustProxy(value) { + if (value && typeof value === 'object' && typeof value.trusts === 'function') return value; + const v = String(value ?? '').trim(); + if (!v || /^(0|false|off|no|non)$/i.test(v)) return null; + const entries = /^(1|true|on|yes|oui|loopback)$/i.test(v) ? ['127.0.0.0/8', '::1'] : v.split(',').map((x) => x.trim()).filter(Boolean); + const list = new BlockList(); + for (const e of entries) { + const [addr, bits] = e.split('/'); + const family = isIP(addr); + if (!family || (bits !== undefined && !/^\d{1,3}$/.test(bits))) throw new Error(`TRUST_PROXY : entrée invalide « ${e} » (adresse IP ou plage CIDR attendue)`); + const kind = family === 4 ? 'ipv4' : 'ipv6'; + if (bits === undefined) list.addAddress(addr, kind); else list.addSubnet(addr, Number(bits), kind); + } + return { trusts: (ip) => { const f = isIP(ip); return f ? list.check(ip, f === 4 ? 'ipv4' : 'ipv6') : false; } }; +} + +/** + * Adresse du client. Sans proxy de confiance, c'est celle de la connexion : un en-tête X-Forwarded-For forgé ne change + * rien. Avec TRUST_PROXY, et seulement si la connexion vient d'un proxy de confiance, on lit X-Forwarded-For de droite à + * gauche et on garde la première adresse qui n'est pas un proxy de confiance (les entrées de gauche, que le client peut + * inventer, ne sont jamais crues). + */ +export function clientIp(req, trust = null) { + const peer = normalizeIp(req.socket?.remoteAddress || '') || 'inconnue'; + if (!trust || !trust.trusts(peer)) return peer; + const raw = [].concat(req.headers['x-forwarded-for'] || []).join(','); + const chain = raw.split(',').map((x) => x.trim()).filter(Boolean); + for (let i = chain.length - 1; i >= 0; i--) { + if (!parseIp(chain[i])) return peer; // entrée illisible : on ne devine pas + const ip = normalizeIp(chain[i]); + if (!trust.trusts(ip)) return ip; + } + return peer; +} + +// ---------- Limiteur ---------- + +const human = (s) => (s < 90 ? `${s} seconde${s > 1 ? 's' : ''}` : s < 5400 ? `${Math.ceil(s / 60)} minutes` : `${Math.ceil(s / 3600)} heures`); + +export class RateLimiter { + /** `clock` (ms) est injectable pour les tests. */ + constructor({ rules = RATE_LIMITS, clock = Date.now, maxKeys = 100_000 } = {}) { + this.rules = rules; + this.clock = clock; + this.maxKeys = maxKeys; + this.hits = new Map(); // clé → { times: number[], windowMs } + this.calls = 0; + } + + /** + * Compte une requête si la règle l'accepte. Une requête refusée n'est PAS comptée : insister ne prolonge pas l'attente. + * @returns {{ok: true} | {ok: false, retryAfter: number, scope: string, rule: string}} retryAfter en secondes + */ + check(rule, { ip, userId } = {}) { + const spec = this.rules[rule]; + if (!spec) throw new Error(`Règle de débit inconnue : ${rule}`); + const t = this.clock(); + if (++this.calls % 500 === 0 || this.hits.size > this.maxKeys) this.sweep(t); + const pending = []; + for (const [scope, conf] of Object.entries(spec)) { + const id = scope === 'ip' ? ip : userId; + if (id == null) continue; + const key = `${rule}|${scope}|${id}`; + let e = this.hits.get(key); + if (!e) e = { times: [], windowMs: conf.windowMs }; + while (e.times.length && e.times[0] <= t - conf.windowMs) e.times.shift(); + if (e.times.length >= conf.max) { + return { ok: false, rule, scope, retryAfter: Math.max(1, Math.ceil((e.times[0] + conf.windowMs - t) / 1000)) }; + } + pending.push([key, e]); + } + for (const [key, e] of pending) { e.times.push(t); this.hits.set(key, e); } + return { ok: true }; + } + + /** Refuse (429 avec Retry-After) si la règle est dépassée. */ + enforce(rule, who) { + const r = this.check(rule, who); + if (r.ok) return; + throw new HttpError(429, `Trop de requêtes : réessaie dans ${human(r.retryAfter)}.`, { + expose: true, code: 'rate_limited', headers: { 'Retry-After': String(r.retryAfter) }, data: { retryAfter: r.retryAfter }, + }); + } + + /** Efface les compteurs expirés ; si la table reste trop grande, les plus anciens sont oubliés (garde-fou mémoire). */ + sweep(t = this.clock()) { + for (const [key, e] of this.hits) { + if (!e.times.length || e.times[e.times.length - 1] <= t - e.windowMs) this.hits.delete(key); + } + for (const key of this.hits.keys()) { + if (this.hits.size <= this.maxKeys) break; + this.hits.delete(key); + } + } +} diff --git a/src/routes.js b/src/routes.js index 7a34a83..24a9580 100644 --- a/src/routes.js +++ b/src/routes.js @@ -56,18 +56,18 @@ export function registerRoutes(router, app) { if (!e.status || e.status >= 500) console.error('[connexion]', e); redirect(res, `/login?e=${encodeURIComponent(e.status && e.status < 500 ? e.message : 'Connexion impossible, réessaie dans un instant')}`); }; - router.get('/auth/google', async ({ res }) => startLogin(app, 'google', res), { public: true }); + router.get('/auth/google', async ({ res }) => startLogin(app, 'google', res), { public: true, limit: 'auth_start' }); router.get('/auth/google/callback', async ({ req, res, url }) => { try { await finishLogin(app, 'google', url.searchParams, req, res); } catch (e) { loginFailed(res, e); } - }, { public: true }); + }, { public: true, limit: 'auth_callback' }); // Apple : le retour est un POST cross-site (response_mode=form_post), donc public et sans contrôle d'origine ; // la protection repose sur state + nonce + cookie de liaison (voir auth.js) - router.get('/auth/apple', async ({ res }) => startLogin(app, 'apple', res), { public: true }); + router.get('/auth/apple', async ({ res }) => startLogin(app, 'apple', res), { public: true, limit: 'auth_start' }); router.post('/auth/apple/callback', async ({ req, res }) => { try { await finishLogin(app, 'apple', await readBody(req), req, res); } catch (e) { loginFailed(res, e); } - }, { public: true }); + }, { public: true, limit: 'auth_callback' }); // Désinscription (RGPD). GET = page de confirmation (évite les désinscriptions par les scanners de liens), // POST = désinscription effective, compatible "one-click" (RFC 8058). @@ -166,6 +166,7 @@ export function registerRoutes(router, app) { })); }); + const LINK_LIMIT = { limit: 'link' }; 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 }) => { @@ -179,19 +180,19 @@ export function registerRoutes(router, app) { 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/api-key', linkAction((b, s) => linkApiKey(app, s.userId, b.apiKey)), LINK_LIMIT); + router.post('/link/subscription', linkAction((b, s) => linkSubscriptionToken(app, s.userId, { token: b.token, accept: b.accept })), LINK_LIMIT); + router.post('/link/server', linkAction((b, s) => linkServer(app, s.userId)), LINK_LIMIT); 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)}`); - }); + }, LINK_LIMIT); 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'); - }); + }, LINK_LIMIT); // ---------- Mon compte ---------- router.get('/account', async ({ res, session, url }) => { @@ -214,21 +215,21 @@ export function registerRoutes(router, app) { await deleteUser(app, session.userId); await destroySession(db, req, res); redirect(res, '/login?bye=1'); - }); + }, { limit: 'account_delete' }); // ---------- API JSON ---------- router.post('/api/report/send', async ({ res, session }) => { const r = await sendWeeklyReport(app, session.userId); if (!r.channels.length) throw new HttpError(400, 'Configure le SMTP global + l\'email de réception, ou un webhook Discord'); json(res, { ok: true, channels: r.channels }); - }); + }, { limit: 'mail_send' }); router.post('/api/notify/test', async ({ res, session }) => { if (!(await notifyConfig(app, session.userId)).url) throw new HttpError(400, 'Aucun webhook Discord configuré'); const ok = await notify(app, session.userId, '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 }); - }); + }, { limit: 'mail_send' }); // Barre du haut : uniquement les jobs, l'usage et les quotas de l'utilisateur courant (la température du serveur, réservée aux admins) router.get('/api/system', async ({ res, session }) => { @@ -272,7 +273,7 @@ export function registerRoutes(router, app) { catch (e) { if (await exists()) throw new HttpError(409, 'Ce dépôt est déjà un projet'); throw e; } await enqueue(db, { userId, projectId: id, type: 'analyze' }, aiOpts); json(res, { id }); - }); + }, { limit: 'project_create' }); router.post('/api/projects/:id/delete', async (ctx) => { const p = await project(ctx); @@ -363,7 +364,7 @@ export function registerRoutes(router, app) { if (!b.confirm) throw new HttpError(400, 'Confirmation requise'); const running = await db.prepare("SELECT 1 FROM jobs WHERE project_id = ? AND type = 'prospect' AND status IN ('queued','running')").get(p.id); if (running) throw new HttpError(409, 'La recherche de prospects est encore en cours'); - })); + }), { limit: 'mail_send' }); router.post('/api/projects/:id/template/save', async (ctx) => { const { req, res } = ctx; @@ -408,14 +409,14 @@ export function registerRoutes(router, app) { }, 'pass'); try { json(res, { ok: true, check: await checkInbox(app, session.userId, p.id) }); } catch (e) { json(res, { ok: false, error: e.message }); } - }); + }, { limit: 'conn_test' }); router.post('/api/projects/:id/inbox/check', async (ctx) => { const { res, session } = ctx; const p = await project(ctx); try { json(res, { ok: true, check: await checkInbox(app, session.userId, p.id) }); } catch (e) { throw new HttpError(502, e.message); } - }); + }, { limit: 'conn_test' }); router.post('/api/projects/:id/db', async (ctx) => { const { req, res } = ctx; @@ -445,7 +446,7 @@ export function registerRoutes(router, app) { await saveSnapshot(db, p.id, business); // la consultation alimente aussi la courbe du jour } catch (e) { error = e.message; } json(res, { business, error, stats, aiCostUsd: cost }); - }); + }, { limit: 'conn_test' }); router.get('/api/projects/:id/prospects\\.csv', async (ctx) => { const { res, url } = ctx; @@ -458,7 +459,7 @@ export function registerRoutes(router, app) { 'Cache-Control': 'no-store', }); res.end(await exportProspects(db, p.id, parseFilters(url.searchParams))); - }); + }, { limit: 'csv' }); router.post('/api/projects/:id/prospects/import', async (ctx) => { const { req, res } = ctx; @@ -466,7 +467,7 @@ export function registerRoutes(router, app) { const b = await readBody(req, { max: 1024 * 1024 }); try { json(res, await importProspects(db, p.id, String(b.csv || ''))); } catch (e) { throw new HttpError(400, e.message); } - }); + }, { limit: 'csv' }); router.get('/api/projects/:id/history', async (ctx) => { const { res, url } = ctx; diff --git a/src/server.js b/src/server.js index 39bb379..b027c35 100644 --- a/src/server.js +++ b/src/server.js @@ -6,6 +6,7 @@ import { fileURLToPath } from 'node:url'; import { loadConfig } from './config.js'; import { openDb } from './db.js'; import { Router, json, redirect, html, HttpError } from './http.js'; +import { RateLimiter, clientIp } from './ratelimit.js'; import { getSession, checkOrigin, purgeExpired } from './auth.js'; import { syncAdmins } from './users.js'; import { registerRoutes } from './routes.js'; @@ -35,11 +36,11 @@ const STATIC = { '/static/favicon.svg': asset('favicon.svg', 'image/svg+xml', 86400), }; -// `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 } = {}) { +// `fetch`, `validateApiKey`, `validateToken`, `syncRepo`, `limiter` : 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, limiter } = {}) { db ??= await openDb(cfg.db, { adminEmails: cfg.adminEmails }); await syncAdmins(db, cfg.adminEmails || []); // ADMIN_EMAILS fait foi pour le rôle admin - const app = { db, cfg, createTransport, fetch, validateApiKey, validateToken, syncRepo }; + const app = { db, cfg, createTransport, fetch, validateApiKey, validateToken, syncRepo, limiter: limiter || new RateLimiter() }; const secHeaders = securityHeaders(cfg.appUrl); const router = new Router(); registerRoutes(router, app); @@ -66,6 +67,8 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch if (wantsJson || !isRead) throw new HttpError(404, 'Page introuvable'); return html(res, notFoundPage({ appUrl: cfg.appUrl }), 404); } + const ip = clientIp(req, cfg.trustProxy); + if (route.public && route.limit) app.limiter.enforce(route.limit, { ip }); const session = route.public ? null : await getSession(db, req); if (!route.public) { if (!session) { @@ -78,6 +81,7 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch return redirect(res, '/login'); } checkOrigin(req, cfg); + if (route.limit) app.limiter.enforce(route.limit, { ip, userId: session.userId }); // 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')) { @@ -92,7 +96,8 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch if (status >= 500 && !e.expose) console.error(`[${req.method} ${url.pathname}]`, e); if (res.headersSent) return res.end(); const msg = status >= 500 && !e.expose ? 'Erreur interne' : e.message; - if (url.pathname.startsWith('/api/') || req.headers.accept?.includes('json')) json(res, { error: msg }, status); + for (const [k, v] of Object.entries(e.headers || {})) res.setHeader(k, v); + if (url.pathname.startsWith('/api/') || req.headers.accept?.includes('json')) json(res, { error: msg, ...(e.code ? { code: e.code } : {}), ...(e.data || {}) }, status); else html(res, layout({ title: 'Erreur', body: `

${status}

${msg.replace(/Retour

` }), status); } }); @@ -131,6 +136,7 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch } let purging = null; const purge = setInterval(() => { + app.limiter.sweep(); purging = purgeExpired(db).catch((e) => console.error('[purge]', e.message)); }, 3600_000); purge.unref(); @@ -145,6 +151,7 @@ export async function createApp(cfg, { db, worker = true, createTransport, fetch await db.close(); }; app.server = server; + app.router = router; return app; } diff --git a/test/helpers/server.js b/test/helpers/server.js index 7c32870..2c93152 100644 --- a/test/helpers/server.js +++ b/test/helpers/server.js @@ -7,28 +7,37 @@ import { now } from '../../src/db.js'; import { createApp } from '../../src/server.js'; import { testDb } from './db.js'; import { addUser } from './users.js'; +import { RateLimiter } from '../../src/ratelimit.js'; +import { RATE_LIMITS } from '../../src/limits.js'; export const APP_URL = 'https://ai.tony-averty.dev'; -export async function startApp({ cfg = {}, worker = false } = {}) { +// Limiteur sans plafond réaliste : les tests qui répètent des requêtes ne butent pas sur le débit. `rateLimit: true` rétablit +// les seuils réels de src/limits.js ; un objet { clock } les garde avec une horloge injectée. +const unlimited = () => new RateLimiter({ + rules: Object.fromEntries(Object.entries(RATE_LIMITS).map(([k, v]) => [k, Object.fromEntries(Object.entries(v).map(([sc, c]) => [sc, { ...c, max: 1e9 }]))])), +}); + +export async function startApp({ cfg = {}, worker = false, rateLimit = false, createTransport, resolveHost } = {}) { const tmp = mkdtempSync(join(tmpdir(), 'aitools-srv-')); const config = { appUrl: APP_URL, google: { clientId: 'gid', clientSecret: 'gsecret' }, apple: null, adminEmails: [], secretKey: randomBytes(32), dataDir: tmp, claudeBin: 'claude', thermalMax: 75, cliModeEnabled: true, sandbox: { enabled: false, production: false, roBinds: [], serverHome: tmp }, ...cfg, }; - const app = await createApp(config, { db: await testDb(), worker }); + const limiter = rateLimit ? new RateLimiter(rateLimit === true ? {} : rateLimit) : unlimited(); + const app = await createApp(config, { db: await testDb(), worker, limiter, createTransport, resolveHost }); await new Promise((r) => app.server.listen(0, '127.0.0.1', r)); const base = `http://127.0.0.1:${app.server.address().port}`; /** Requêtes avec la session d'un cookie (ou sans). */ const client = (cookie) => ({ get: (p, opts = {}) => fetch(base + p, { redirect: 'manual', headers: { ...(cookie ? { cookie } : {}), accept: 'application/json', ...opts.headers } }), - post: (p, body = {}, { origin = APP_URL, form = false } = {}) => fetch(base + p, { + post: (p, body = {}, { origin = APP_URL, form = false, headers = {} } = {}) => fetch(base + p, { method: 'POST', redirect: 'manual', headers: { ...(cookie ? { cookie } : {}), ...(origin ? { origin } : {}), accept: 'application/json', - 'content-type': form ? 'application/x-www-form-urlencoded' : 'application/json', + 'content-type': form ? 'application/x-www-form-urlencoded' : 'application/json', ...headers, }, body: form ? new URLSearchParams(body).toString() : JSON.stringify(body), }), diff --git a/test/ratelimit.test.js b/test/ratelimit.test.js new file mode 100644 index 0000000..5c36f05 --- /dev/null +++ b/test/ratelimit.test.js @@ -0,0 +1,212 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { RateLimiter, parseTrustProxy, clientIp } from '../src/ratelimit.js'; +import { RATE_LIMITS } from '../src/limits.js'; +import { loadConfig } from '../src/config.js'; +import { startApp } from './helpers/server.js'; + +// Limitation de débit : le limiteur, la lecture de l'adresse du client, et son effet sur les vraies routes. + +const RULES = { demo: { ip: { max: 3, windowMs: 10_000 }, user: { max: 2, windowMs: 60_000 } } }; + +test('limiteur : fenêtre glissante, Retry-After exact, une requête refusée n\'est pas comptée', () => { + let t = 1_000_000; + const rl = new RateLimiter({ rules: { r: { ip: { max: 2, windowMs: 10_000 } } }, clock: () => t }); + assert.ok(rl.check('r', { ip: 'a' }).ok); + t += 4000; + assert.ok(rl.check('r', { ip: 'a' }).ok); + const blocked = rl.check('r', { ip: 'a' }); + assert.equal(blocked.ok, false); + assert.equal(blocked.retryAfter, 6, 'la 1re requête sort de la fenêtre dans 6 s'); + t += 3000; + assert.equal(rl.check('r', { ip: 'a' }).retryAfter, 3, 'insister ne prolonge pas l\'attente'); + t += 3000; // 10 s après la 1re requête + assert.ok(rl.check('r', { ip: 'a' }).ok, 'la fenêtre a glissé'); + assert.ok(rl.check('r', { ip: 'b' }).ok, 'une autre adresse a son propre compteur'); + assert.throws(() => rl.check('inconnue', {}), /Règle de débit inconnue/); +}); + +test('limiteur : portées IP et compte indépendantes, refus dès qu\'une portée est dépassée', () => { + const rl = new RateLimiter({ rules: RULES, clock: () => 1000 }); + assert.ok(rl.check('demo', { ip: '1.1.1.1', userId: 7 }).ok); + assert.ok(rl.check('demo', { ip: '2.2.2.2', userId: 7 }).ok); + const r = rl.check('demo', { ip: '3.3.3.3', userId: 7 }); + assert.equal(r.ok, false); + assert.equal(r.scope, 'user', 'changer d\'adresse ne contourne pas la limite du compte'); + assert.ok(rl.check('demo', { ip: '3.3.3.3', userId: 8 }).ok, 'un autre compte n\'est pas touché'); + // Le refus par le compte n'a pas consommé le quota de l'adresse 4.4.4.4 + assert.equal([1, 2, 3].filter(() => rl.check('demo', { ip: '4.4.4.4' }).ok).length, 3); +}); + +test('limiteur : les compteurs expirés sont libérés, la table reste bornée', () => { + let t = 0; + const rl = new RateLimiter({ rules: { r: { ip: { max: 1, windowMs: 1000 } } }, clock: () => t, maxKeys: 50 }); + for (let i = 0; i < 40; i++) rl.check('r', { ip: `10.0.0.${i}` }); + assert.equal(rl.hits.size, 40); + t = 5000; + rl.sweep(); + assert.equal(rl.hits.size, 0, 'tout a expiré'); + for (let i = 0; i < 200; i++) rl.check('r', { ip: `10.1.0.${i}` }); + rl.sweep(); + assert.ok(rl.hits.size <= 50, 'plafond mémoire'); +}); + +// ---------- Adresse du client ---------- + +const req = (remote, xff) => ({ socket: { remoteAddress: remote }, headers: xff === undefined ? {} : { 'x-forwarded-for': xff } }); + +test('adresse du client : sans TRUST_PROXY, X-Forwarded-For forgé est ignoré', () => { + assert.equal(clientIp(req('203.0.113.9', '1.2.3.4')), '203.0.113.9'); + assert.equal(clientIp(req('::ffff:203.0.113.9', '1.2.3.4'), parseTrustProxy('false')), '203.0.113.9'); + assert.equal(clientIp(req('127.0.0.1', '1.2.3.4'), null), '127.0.0.1', 'même venu d\'un proxy local, sans TRUST_PROXY on ne lit rien'); +}); + +test('adresse du client : avec TRUST_PROXY, lecture de droite à gauche, seulement depuis un proxy de confiance', () => { + const trust = parseTrustProxy('true'); + assert.equal(clientIp(req('127.0.0.1', '198.51.100.7'), trust), '198.51.100.7'); + assert.equal(clientIp(req('::1', '198.51.100.7'), trust), '198.51.100.7'); + assert.equal(clientIp(req('::ffff:127.0.0.1', '198.51.100.7'), trust), '198.51.100.7'); + // Le client écrit « 9.9.9.9 » à gauche ; Nginx ajoute SON adresse à droite : seule celle-ci compte + assert.equal(clientIp(req('127.0.0.1', '9.9.9.9, 198.51.100.7'), trust), '198.51.100.7'); + assert.equal(clientIp(req('127.0.0.1', '9.9.9.9, 198.51.100.7, 127.0.0.1'), trust), '198.51.100.7', 'un 2e proxy local est sauté'); + // Une connexion directe (pas du proxy) qui envoie l'en-tête n'est pas crue + assert.equal(clientIp(req('203.0.113.9', '1.2.3.4'), trust), '203.0.113.9'); + assert.equal(clientIp(req('127.0.0.1', undefined), trust), '127.0.0.1'); + assert.equal(clientIp(req('127.0.0.1', 'pas-une-ip'), trust), '127.0.0.1'); +}); + +test('adresse du client : liste de proxys et plages CIDR, entrée invalide refusée', () => { + const trust = parseTrustProxy('10.0.0.0/8, 192.0.2.1'); + assert.equal(clientIp(req('10.4.5.6', '198.51.100.7'), trust), '198.51.100.7'); + assert.equal(clientIp(req('192.0.2.1', '198.51.100.7'), trust), '198.51.100.7'); + assert.equal(clientIp(req('127.0.0.1', '198.51.100.7'), trust), '127.0.0.1', 'le loopback n\'est pas dans cette liste'); + assert.throws(() => parseTrustProxy('10.0.0.0/8, nimporte'), /TRUST_PROXY/); + assert.throws(() => parseTrustProxy('10.0.0.0/x'), /TRUST_PROXY/); + assert.equal(parseTrustProxy(''), null); + assert.equal(parseTrustProxy(undefined), null); +}); + +test('TRUST_PROXY : désactivé par défaut dans la configuration', () => { + const env = { APP_URL: 'https://x.fr', SECRET_KEY: 'a'.repeat(64), GOOGLE_CLIENT_ID: 'g', GOOGLE_CLIENT_SECRET: 's', DB_DRIVER: 'sqlite' }; + const keep = { ...process.env }; + try { + Object.assign(process.env, env); delete process.env.TRUST_PROXY; + assert.equal(loadConfig().trustProxy, null); + process.env.TRUST_PROXY = 'true'; + assert.ok(loadConfig().trustProxy.trusts('127.0.0.1')); + } finally { + for (const k of Object.keys(process.env)) if (!(k in keep)) delete process.env[k]; + Object.assign(process.env, keep); + } +}); + +// ---------- Sur les vraies routes ---------- + +test('connexion : au-delà du seuil, 429 avec Retry-After ; un X-Forwarded-For forgé ne donne pas un compteur neuf', async () => { + const s = await startApp({ rateLimit: true }); + try { + const max = RATE_LIMITS.auth_start.ip.max; + for (let i = 0; i < max; i++) { + const r = await fetch(`${s.base}/auth/google`, { redirect: 'manual', headers: { 'x-forwarded-for': `203.0.113.${i + 1}` } }); + assert.equal(r.status, 303, `requête ${i + 1}`); + } + // L'essai suivant arrive avec une adresse « neuve » dans X-Forwarded-For : sans TRUST_PROXY, c'est le même client + const r = await fetch(`${s.base}/auth/google`, { redirect: 'manual', headers: { 'x-forwarded-for': '198.51.100.99' } }); + assert.equal(r.status, 429); + const wait = Number(r.headers.get('retry-after')); + assert.ok(wait >= 1 && wait <= RATE_LIMITS.auth_start.ip.windowMs / 1000, `Retry-After = ${wait}`); + assert.match(await r.text(), /Trop de requêtes/); + // Les pages publiques restent libres + assert.equal((await fetch(`${s.base}/tarifs`)).status, 200); + const json = await fetch(`${s.base}/auth/google`, { headers: { accept: 'application/json', 'x-forwarded-for': '198.51.100.100' }, redirect: 'manual' }); + assert.equal(json.status, 429); + const body = await json.json(); + assert.equal(body.code, 'rate_limited'); + assert.ok(body.retryAfter >= 1); + } finally { await s.close(); } +}); + +test('connexion : avec TRUST_PROXY, l\'adresse lue dans X-Forwarded-For (proxy local) sépare les compteurs', async () => { + const s = await startApp({ rateLimit: true, cfg: { trustProxy: parseTrustProxy('true') } }); + try { + const max = RATE_LIMITS.auth_start.ip.max; + const go = (ip) => fetch(`${s.base}/auth/google`, { redirect: 'manual', headers: { 'x-forwarded-for': ip } }); + for (let i = 0; i < max; i++) assert.equal((await go('198.51.100.1')).status, 303); + assert.equal((await go('198.51.100.1')).status, 429, 'ce client est limité'); + assert.equal((await go('198.51.100.2')).status, 303, 'un autre client derrière le même proxy ne l\'est pas'); + // L'attaquant qui ajoute des adresses à GAUCHE reste sur le même compteur : seule l'entrée du proxy (à droite) compte + assert.equal((await go('7.7.7.7, 198.51.100.1')).status, 429); + } finally { await s.close(); } +}); + +test('retours des fournisseurs (Google, Apple) : limités par adresse', async () => { + const s = await startApp({ rateLimit: true, cfg: { apple: { teamId: 't', keyId: 'k', clientId: 'c', privateKey: 'p' } } }); + try { + const max = RATE_LIMITS.auth_callback.ip.max; + for (let i = 0; i < max; i++) { + const r = await fetch(`${s.base}/auth/google/callback?state=x&code=y`, { redirect: 'manual' }); + assert.equal(r.status, 303, 'refus de connexion ordinaire (redirection vers /login)'); + } + assert.equal((await fetch(`${s.base}/auth/google/callback?state=x&code=y`, { redirect: 'manual' })).status, 429); + // La règle est commune aux deux retours + const apple = await fetch(`${s.base}/auth/apple/callback`, { method: 'POST', redirect: 'manual', headers: { 'content-type': 'application/x-www-form-urlencoded' }, body: 'state=x' }); + assert.equal(apple.status, 429); + } finally { await s.close(); } +}); + +test('liaison : essais de clé limités par compte, un autre compte n\'est pas pénalisé', async () => { + const s = await startApp({ rateLimit: true }); + try { + const a = await s.newUser({ admin: false, link: null }); + const b = await s.newUser({ admin: false, link: null }); + const max = RATE_LIMITS.link.user.max; + for (let i = 0; i < max; i++) { + const r = await a.post('/link/api-key', { apiKey: 'pas-une-cle' }); + assert.equal(r.status, 400, `essai ${i + 1}`); + } + const blocked = await a.post('/link/api-key', { apiKey: 'pas-une-cle' }); + assert.equal(blocked.status, 429); + assert.ok(Number(blocked.headers.get('retry-after')) >= 1); + for (const p of ['/link/subscription', '/link/test', '/link/unlink', '/link/server']) assert.equal((await a.post(p, {})).status, 429, p); + assert.equal((await b.post('/link/api-key', { apiKey: 'pas-une-cle' })).status, 400); + } finally { await s.close(); } +}); + +test('export, import, création de projet, suppression de compte, tests de connexion : tous limités', async () => { + const s = await startApp({ rateLimit: true }); + try { + const u = await s.newUser({ admin: true }); + const pid = Number((await s.db.prepare("INSERT INTO projects(user_id, name, git_url, created_at) VALUES(?, 'p', 'https://git.test/a/b.git', 1)").run(u.id)).lastInsertRowid); + const hit = async (rule, call) => { + const conf = RATE_LIMITS[rule].user; + for (let i = 0; i < conf.max; i++) assert.notEqual((await call()).status, 429, `${rule} #${i + 1}`); + assert.equal((await call()).status, 429, `${rule} au-delà du seuil`); + }; + await hit('csv', () => u.get(`/api/projects/${pid}/prospects.csv`)); + await hit('conn_test', () => u.get(`/api/projects/${pid}/recap`)); + await hit('project_create', () => u.post('/api/projects', {})); + await hit('account_delete', () => u.post('/account/delete', { confirm: 'autre@x.fr' }, { form: true })); + await hit('mail_send', () => u.post('/api/report/send', {})); + // L'import CSV partage la règle « csv » de l'export : déjà épuisée ci-dessus + assert.equal((await u.post(`/api/projects/${pid}/prospects/import`, { csv: 'email\na@b.fr' })).status, 429); + } finally { await s.close(); } +}); + +test('chaque règle citée par une route existe, et les points sensibles sont tous couverts', async () => { + const s = await startApp(); + try { + const routes = s.app.router.routes; + const used = new Set(routes.map((r) => r.limit).filter(Boolean)); + for (const rule of used) assert.ok(RATE_LIMITS[rule], `règle ${rule} absente de src/limits.js`); + // « admin » n'est branchée qu'avec le back-office + for (const rule of Object.keys(RATE_LIMITS).filter((r) => r !== 'admin')) assert.ok(used.has(rule), `règle ${rule} sans route`); + const find = (method, path) => routes.find((r) => r.method === method && r.re.test(path)); + for (const [m, p] of [ + ['GET', '/auth/google'], ['GET', '/auth/apple'], ['GET', '/auth/google/callback'], ['POST', '/auth/apple/callback'], + ['POST', '/link/api-key'], ['POST', '/link/subscription'], ['POST', '/link/server'], ['POST', '/link/test'], ['POST', '/link/unlink'], + ['GET', '/api/projects/1/prospects.csv'], ['POST', '/api/projects/1/prospects/import'], ['POST', '/api/projects/1/send'], + ['POST', '/api/report/send'], ['POST', '/api/notify/test'], ['POST', '/api/projects'], ['POST', '/account/delete'], + ['POST', '/api/projects/1/imap'], ['POST', '/api/projects/1/inbox/check'], ['GET', '/api/projects/1/recap'], + ]) assert.ok(find(m, p)?.limit, `${m} ${p} sans limite`); + } finally { await s.close(); } +});