diff --git a/package.json b/package.json index 343831c..2fc770f 100644 --- a/package.json +++ b/package.json @@ -7,6 +7,7 @@ "dev": "nuxt dev", "generate": "nuxt generate", "preview": "nuxt preview", + "test:routes": "node scripts/test-routes.mjs", "test": "node scripts/test-echelles-nav.mjs && node scripts/test-figures.mjs && node scripts/test-vue-fiches.mjs && node scripts/test-submit-libre.mjs && node scripts/test-circuit-breaker.mjs && node scripts/test-bandeau.mjs && node scripts/test-outils-data.mjs && node scripts/test-citations.mjs && node scripts/test-seo.mjs && node scripts/test-y.mjs && node scripts/test-connaissances.mjs && node scripts/test-bibliotheque.mjs && node scripts/test-media-data.mjs && node scripts/test-taxonomie.mjs && node scripts/test-geocodage.mjs && node scripts/test-migrer-taxonomie.mjs && node scripts/test-fiche-publique.mjs && node --test \"worker/test/*.test.js\"", "postinstall": "nuxt prepare" }, diff --git a/scripts/banc-routes.mjs b/scripts/banc-routes.mjs new file mode 100644 index 0000000..0f629bf --- /dev/null +++ b/scripts/banc-routes.mjs @@ -0,0 +1,250 @@ +/** + * Banc de routes (lot SURFACE, étape A) : le serveur Nuxt BÂTI (`.output/server/index.mjs`) + * démarré sur un port local, tous ses services externes remplacés par UN faux serveur local + * qui enregistre ce qu'il reçoit et répond ce qu'on lui dit. + * + * Aucun appel réel : l'application démarre avec un environnement VIDE (pas celui du shell, + * pas de .env), où chaque adresse de service pointe le faux serveur et chaque clé vaut « faux ». + * + * Usage (voir scripts/test-routes.mjs) : + * import { demarrerBanc } from './banc-routes.mjs' + * const banc = await demarrerBanc() // bâtit si besoin, démarre faux + appli + * banc.faux.repondre.bifrost = (req) => ({ json: { … } }) + * const r = await banc.requete('/api/chatbot', { method: 'POST', json: { question: '…' }, ip: '10.0.0.1' }) + * banc.faux.recu('resend') // requêtes reçues par le faux Resend + * await banc.arreter() + * + * Services simulés (préfixe d'URL sur le faux serveur → variable d'environnement de l'appli) : + * /nocodb → NUXT_NOCODB_URL GET/POST /api/v2/tables/:table/records + * /bifrost → NUXT_BIFROST_URL POST /v1/chat/completions + * /mistral → MISTRAL_API_URL POST /v1/chat/completions (filtre des commentaires) + * /resend → RESEND_API_URL POST /emails (signalements) + * /rag → NUXT_RAG_PE_URL GET /health, POST /query (LightRAG Pensées) + * /rag-emancipation → NUXT_RAG_EMANCIPATION_URL + * Redis pointe un port fermé : la limite de débit Redis retombe sur son compteur en mémoire. + */ + +import { spawn, spawnSync } from 'node:child_process' +import { createServer } from 'node:http' +import { existsSync, mkdtempSync, rmSync } from 'node:fs' +import { tmpdir } from 'node:os' +import { join, dirname } from 'node:path' +import { fileURLToPath } from 'node:url' + +const RACINE = join(dirname(fileURLToPath(import.meta.url)), '..') + +const TABLES = { orgs: 'tbl_orgs', stats: 'tbl_stats', comments: 'tbl_comments', avis: 'tbl_avis' } + +function lireCorps(req) { + return new Promise((resolve) => { + const morceaux = [] + req.on('data', (c) => morceaux.push(c)) + req.on('end', () => { + const brut = Buffer.concat(morceaux).toString('utf-8') + let json = null + try { json = brut ? JSON.parse(brut) : null } catch { /* corps non JSON */ } + resolve({ brut, json }) + }) + }) +} + +/** Réponse Bifrost par défaut : un JSON valide, servi par un fournisseur gratuit. */ +export function reponseBifrost(contenu = { reponse_texte: 'Réponse du faux modèle.', fiches_recommandees: [] }, extra = {}) { + return { + json: { + choices: [{ message: { content: typeof contenu === 'string' ? contenu : JSON.stringify(contenu) }, finish_reason: 'stop' }], + usage: { prompt_tokens: 1000, completion_tokens: 200 }, + extra_fields: { provider: 'groq', resolved_model_used: 'groq/openai/gpt-oss-20b' }, + ...extra, + }, + } +} + +/** Réponse Mistral (filtre des commentaires) dont le `content` vaut `contenu` tel quel. */ +export function reponseMistral(contenu) { + return { json: { choices: [{ message: { content: contenu } }] } } +} + +function fauxParDefaut() { + return { + nocodb: (req) => { + const m = req.chemin.match(/^\/api\/v2\/tables\/([^/]+)\/records/) + if (!m) return { status: 404, json: { msg: 'faux NocoDB : chemin inconnu' } } + if (req.methode === 'GET') { + const lignes = m[1] === TABLES.orgs ? [{ Id: 1, nom: 'Organisation témoin', description_enrichie: 'architecture paille', tags_fonction: 'Conseil', echelle: 'Locale', localisation_ville: 'Lyon' }] : [] + return { json: { list: lignes, pageInfo: { isLastPage: true } } } + } + return { json: { Id: 42 } } + }, + bifrost: () => reponseBifrost(), + mistral: () => reponseMistral('{"safe": true, "category": null, "reason": null}'), + resend: () => ({ json: { id: 'faux-courriel' } }), + rag: (req) => (req.chemin === '/health' ? { json: { status: 'healthy' } } : { json: { response: 'Réponse du faux RAG.', references: [] } }), + 'rag-emancipation': (req) => (req.chemin === '/health' ? { json: { status: 'healthy' } } : { json: { response: 'Réponse du faux RAG Émancipation.', references: [] } }), + } +} + +/** Faux serveur unique : enregistre chaque requête reçue, répond par `repondre[service]`. */ +export async function demarrerFaux() { + const journal = [] + const repondre = fauxParDefaut() + const serveur = createServer(async (req, res) => { + const url = new URL(req.url, 'http://faux') + const [, service, ...reste] = url.pathname.split('/') + const { brut, json } = await lireCorps(req) + const entree = { + service, + methode: req.method, + chemin: '/' + reste.join('/'), + query: Object.fromEntries(url.searchParams), + entetes: req.headers, + brut, + json, + } + journal.push(entree) + const fn = repondre[service] + let r = fn ? await fn(entree) : { status: 404, json: { msg: `faux serveur : service inconnu « ${service} »` } } + if (r?.delaiMs) await new Promise((ok) => setTimeout(ok, r.delaiMs)) + if (res.destroyed) return + res.writeHead(r?.status ?? 200, { 'Content-Type': 'application/json' }) + res.end(r?.json !== undefined ? JSON.stringify(r.json) : (r?.texte ?? '')) + }) + await new Promise((ok) => serveur.listen(0, '127.0.0.1', ok)) + const url = `http://127.0.0.1:${serveur.address().port}` + return { + url, + journal, + repondre, + /** Requêtes reçues par un service (toutes si `service` absent). */ + recu: (service) => (service ? journal.filter((e) => e.service === service) : journal.slice()), + /** Vide le journal et remet les réponses par défaut. */ + reinitialiser() { + journal.length = 0 + Object.assign(repondre, fauxParDefaut()) + }, + arreter: () => new Promise((ok) => { serveur.closeAllConnections?.(); serveur.close(() => ok()) }), + } +} + +/** Bâtit l'application (`nuxt build`) sauf si BANC_SANS_BUILD=1 et qu'un `.output` existe. */ +export function batir() { + const sortie = join(RACINE, '.output', 'server', 'index.mjs') + if (process.env.BANC_SANS_BUILD === '1' && existsSync(sortie)) { + console.log('[banc] BANC_SANS_BUILD=1 : build existant réutilisé') + return + } + console.log('[banc] nuxt build… (environ une minute)') + const t0 = Date.now() + const r = spawnSync('npx', ['nuxt', 'build'], { cwd: RACINE, stdio: ['ignore', 'pipe', 'pipe'], encoding: 'utf-8' }) + if (r.status !== 0) { + console.error(r.stdout?.slice(-4000), r.stderr?.slice(-4000)) + throw new Error('[banc] nuxt build a échoué') + } + console.log(`[banc] build fait en ${Math.round((Date.now() - t0) / 1000)} s`) +} + +function portLibre() { + return new Promise((ok) => { + const s = createServer() + s.listen(0, '127.0.0.1', () => { const p = s.address().port; s.close(() => ok(p)) }) + }) +} + +/** + * Démarre le faux serveur puis l'application bâtie. `envSup` ajoute ou remplace des variables + * d'environnement de l'application. + */ +export async function demarrerBanc({ envSup = {}, build = true } = {}) { + if (build) batir() + const faux = await demarrerFaux() + const port = await portLibre() + const dossierLimites = mkdtempSync(join(tmpdir(), 'banc-limites-')) + const env = { + PATH: process.env.PATH, + NODE_ENV: 'production', + HOST: '127.0.0.1', + PORT: String(port), + NUXT_NOCODB_URL: `${faux.url}/nocodb`, + NUXT_NOCODB_TOKEN: 'faux', + NUXT_ORG_TABLE_ID: TABLES.orgs, + NUXT_STATS_TABLE_ID: TABLES.stats, + STATS_TABLE_ID: TABLES.stats, + NUXT_COMMENT_TABLE_ID: TABLES.comments, + NUXT_AVIS_TABLE_ID: TABLES.avis, + NUXT_BIFROST_URL: `${faux.url}/bifrost`, + NUXT_BIFROST_VK: 'faux', + NUXT_MISTRAL_API_KEY: 'faux', + MISTRAL_API_URL: `${faux.url}/mistral`, + RESEND_API_KEY: 'faux', + RESEND_API_URL: `${faux.url}/resend`, + NUXT_RESEND_API_KEY: 'faux', + EMAIL_JULES: 'jules@exemple.invalid', + NUXT_EMAIL_JULES: 'jules@exemple.invalid', + NUXT_RAG_PE_URL: `${faux.url}/rag`, + NUXT_RAG_EMANCIPATION_URL: `${faux.url}/rag-emancipation`, + NUXT_RAG_EMANCIPATION_KEY: 'faux', + NUXT_REDIS_URL: 'redis://127.0.0.1:1', + NAV_RATELIMIT_DIR: dossierLimites, + ...envSup, + } + const appli = spawn(process.execPath, [join(RACINE, '.output', 'server', 'index.mjs')], { cwd: RACINE, env, stdio: ['ignore', 'pipe', 'pipe'] }) + const journalAppli = [] + appli.stdout.on('data', (d) => journalAppli.push(String(d))) + appli.stderr.on('data', (d) => journalAppli.push(String(d))) + const base = `http://127.0.0.1:${port}` + + let pret = false + for (let i = 0; i < 100 && !pret; i++) { + if (appli.exitCode !== null) break + try { await fetch(`${base}/robots.txt`); pret = true } catch { await new Promise((ok) => setTimeout(ok, 100)) } + } + if (!pret) { + appli.kill('SIGKILL') + await faux.arreter() + throw new Error(`[banc] l'application n'a pas démarré :\n${journalAppli.join('')}`) + } + + let ipSuivante = 1 + return { + base, + faux, + tables: TABLES, + /** Journal (stdout + stderr) de l'application. */ + journalAppli: () => journalAppli.join(''), + /** Une adresse de visiteur neuve à chaque appel (les limites de débit sont par adresse). */ + ipNeuve: () => `10.${(ipSuivante >> 16) & 255}.${(ipSuivante >> 8) & 255}.${ipSuivante++ & 255}`, + /** + * Requête HTTP contre l'application. `json` : corps JSON ; `brut` : corps tel quel ; + * `ip` : valeur de X-Forwarded-For (sinon une adresse neuve). Rend { status, json, texte }. + */ + async requete(chemin, { method = 'GET', json, brut, ip, entetes = {} } = {}) { + const headers = { 'x-forwarded-for': ip ?? this.ipNeuve(), ...entetes } + let body + if (json !== undefined) { body = JSON.stringify(json); headers['content-type'] = 'application/json' } + if (brut !== undefined) { body = brut; headers['content-type'] ??= 'application/json' } + const res = await fetch(`${base}${chemin}`, { method, headers, body }) + const texte = await res.text() + let j = null + try { j = JSON.parse(texte) } catch { /* HTML ou vide */ } + return { status: res.status, json: j, texte } + }, + async arreter() { + if (appli.exitCode === null) { + appli.kill('SIGTERM') + await new Promise((ok) => { const t = setTimeout(() => { appli.kill('SIGKILL'); ok() }, 3000); appli.once('exit', () => { clearTimeout(t); ok() }) }) + } + await faux.arreter() + rmSync(dossierLimites, { recursive: true, force: true }) + }, + } +} + +/** Attend qu'une condition devienne vraie (écritures non attendues par la route, ex. stats_usage). */ +export async function attendre(cond, { delaiMs = 3000, pasMs = 50 } = {}) { + const fin = Date.now() + delaiMs + while (Date.now() < fin) { + if (await cond()) return true + await new Promise((ok) => setTimeout(ok, pasMs)) + } + return Boolean(await cond()) +} diff --git a/scripts/test-routes.mjs b/scripts/test-routes.mjs new file mode 100644 index 0000000..187f936 --- /dev/null +++ b/scripts/test-routes.mjs @@ -0,0 +1,57 @@ +#!/usr/bin/env node +/** + * Banc de routes (lot SURFACE) : bâtit l'application une fois, la démarre sur un port local + * et joue des requêtes HTTP contre elle. Les services externes sont remplacés par le faux + * serveur de scripts/banc-routes.mjs, qui enregistre ce qu'il reçoit. Aucun appel réel. + * + * Usage : npm run test:routes (bâtit, ~1 min) + * BANC_SANS_BUILD=1 npm run test:routes (réutilise .output) + */ + +import { demarrerBanc } from './banc-routes.mjs' + +let ok = 0 +let ko = 0 +const echecs = [] +function check(nom, cond, detail = '') { + if (cond) { ok++; console.log(` ✓ ${nom}`) } + else { ko++; echecs.push(nom); console.log(` ✗ ${nom}${detail ? ` — ${detail}` : ''}`) } +} + +const banc = await demarrerBanc() +const { faux } = banc + +async function groupe(titre, fn) { + console.log(`\n${titre}`) + faux.reinitialiser() + try { await fn() } catch (e) { ko++; echecs.push(`${titre} : exception`); console.log(` ✗ exception : ${e?.stack ?? e}`) } +} + +try { + await groupe('A. Le banc joue les routes', async () => { + const r = await banc.requete('/robots.txt') + check('GET /robots.txt → 200', r.status === 200, `status ${r.status}`) + + for (const chemin of ['/evenements/ruetz', '/evenements/ruetz/codev', '/evenements/ruetz/foret']) { + const p = await banc.requete(chemin) + check(`témoin Ruetz ${chemin} → 200`, p.status === 200, `status ${p.status}`) + } + + const c = await banc.requete('/api/chatbot', { method: 'POST', json: { question: 'Qui fait de la paille à Lyon ?' } }) + check('POST /api/chatbot nominal → 200', c.status === 200, `status ${c.status} ${c.texte.slice(0, 200)}`) + check('… la réponse vient du faux Bifrost', c.json?.reponse_texte === 'Réponse du faux modèle.') + check('… le faux Bifrost a reçu un appel', faux.recu('bifrost').length === 1) + + const s = await banc.requete('/api/report', { method: 'POST', json: { fiche_id: 1, message: 'Le lien est mort.', email: 'a@b.fr' } }) + check('POST /api/report nominal → 200', s.status === 200, `status ${s.status} ${s.texte.slice(0, 200)}`) + check('… le faux Resend a reçu le courriel', faux.recu('resend').length === 1) + + const inconnus = faux.recu().filter((e) => !['nocodb', 'bifrost', 'mistral', 'resend', 'rag', 'rag-emancipation'].includes(e.service)) + check('aucun appel vers un service non simulé', inconnus.length === 0, inconnus.map((e) => e.service).join(', ')) + }) +} finally { + await banc.arreter() +} + +console.log(`\ntest-routes : ${ok} sur ${ok + ko}${ko ? ` — échecs : ${echecs.join(' · ')}` : ''}`) +process.exit(ko ? 1 : 0) diff --git a/server/api/comment/index.post.ts b/server/api/comment/index.post.ts index 217464c..9b99e46 100644 --- a/server/api/comment/index.post.ts +++ b/server/api/comment/index.post.ts @@ -15,6 +15,9 @@ import { checkRateLimit } from '~/server/utils/rateLimit' +// Adresse de l'API Mistral, réglable pour le banc de routes (scripts/banc-routes.mjs). +const MISTRAL_API_URL = process.env.MISTRAL_API_URL || 'https://api.mistral.ai' + interface CommentBody { orga_id: number contenu: string @@ -36,7 +39,7 @@ async function filtreEthique( const timeout = setTimeout(() => controller.abort(), 2000) try { - const response: any = await $fetch('https://api.mistral.ai/v1/chat/completions', { + const response: any = await $fetch(`${MISTRAL_API_URL}/v1/chat/completions`, { method: 'POST', headers: { Authorization: `Bearer ${mistralKey}`, diff --git a/server/api/report-general.post.ts b/server/api/report-general.post.ts index 3abcd56..66d7766 100644 --- a/server/api/report-general.post.ts +++ b/server/api/report-general.post.ts @@ -11,6 +11,8 @@ import { checkRateLimitJson } from '~/server/utils/rateLimitJson' const EMAIL_JULES = process.env.EMAIL_JULES || 'jules@trans-former.fr' +// Adresse de l'API Resend, réglable pour le banc de routes (scripts/banc-routes.mjs). +const RESEND_API_URL = process.env.RESEND_API_URL || 'https://api.resend.com' const VALID_CATEGORIES = ['Une fiche', 'Le chatbot', 'La carte', 'Autre'] as const @@ -60,7 +62,7 @@ export default defineEventHandler(async (event) => { const submittedAt = new Date().toLocaleString('fr-FR', { timeZone: 'Europe/Paris' }) try { - await $fetch('https://api.resend.com/emails', { + await $fetch(`${RESEND_API_URL}/emails`, { method: 'POST', headers: { Authorization: `Bearer ${resendApiKey}`, diff --git a/server/api/report.post.ts b/server/api/report.post.ts index 1cfe7a5..f396727 100644 --- a/server/api/report.post.ts +++ b/server/api/report.post.ts @@ -12,6 +12,8 @@ import { checkRateLimitJson } from '~/server/utils/rateLimitJson' const EMAIL_JULES = process.env.EMAIL_JULES || 'jules@trans-former.fr' +// Adresse de l'API Resend, réglable pour le banc de routes (scripts/banc-routes.mjs). +const RESEND_API_URL = process.env.RESEND_API_URL || 'https://api.resend.com' export default defineEventHandler(async (event) => { // 1. IP @@ -57,7 +59,7 @@ export default defineEventHandler(async (event) => { const submittedAt = new Date().toLocaleString('fr-FR', { timeZone: 'Europe/Paris' }) try { - await $fetch('https://api.resend.com/emails', { + await $fetch(`${RESEND_API_URL}/emails`, { method: 'POST', headers: { Authorization: `Bearer ${resendApiKey}`, diff --git a/server/utils/rateLimitJson.ts b/server/utils/rateLimitJson.ts index 1b84b65..6babc9d 100644 --- a/server/utils/rateLimitJson.ts +++ b/server/utils/rateLimitJson.ts @@ -15,7 +15,8 @@ import { createHash } from 'crypto' import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs' import { join } from 'path' -const RATELIMIT_DIR = '/tmp/nav-ratelimit' +// Réglable pour le banc de routes (un dossier jetable par passage). +const RATELIMIT_DIR = process.env.NAV_RATELIMIT_DIR || '/tmp/nav-ratelimit' type RateLimitFile = { [action: string]: { count: number; date: string }