/** * 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()) }