Compare commits

..
Author SHA1 Message Date
JulesandClaude Opus 5.5 012d7079f7 fix(aep-codev): une vraie serrure pour le codev, même porte pour ses utilisateurs
- Témoin codev_session signé par le serveur (HMAC-SHA256, clé dérivée du jeton
  NocoDB et des deux mots de passe, jamais exposée) ; il porte le rôle et
  l'expiration (24 h). Un témoin « ok », modifié ou périmé est refusé ; l'ancien
  témoin codev_admin est effacé à la connexion.
- Une seule fonction décide (roleDuVisiteur, server/utils/codevAcces.ts) : toutes
  les routes /api/codev/* sauf la connexion l'appellent (401 sans session, 403 pour
  la suppression hors administrateur, rien n'est demandé à NocoDB), et le garde
  des pages /codev/fiche et /codev/carto aussi.
- Connexion en temps constant, mêmes règles de saisie (espaces, casse) ; échecs
  limités par adresse (30 par quart d'heure, 200 par jour) ; créations et
  modifications limitées (60 par dix minutes) ; identifiant de fiche : entier
  positif ou 400.
- Aucun mot de passe par défaut dans le dépôt, fermé par défaut : sans
  NUXT_CODEV_PASSWORD, pas de connexion ; sans NUXT_CODEV_ADMIN_PASSWORD, pas
  d'administrateur (le participant entre quand même).
- scripts/test-codev-serrure.mjs (147 cas, dans npm test) : fonctions sans
  serveur, puis les vraies routes et le vrai garde contre un faux NocoDB.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 11:11:18 +01:00
18 changed files with 669 additions and 379 deletions
+2 -2
View File
@@ -38,9 +38,9 @@ export default defineNuxtConfig({
resendApiKey: process.env.RESEND_API_KEY,
emailJules: process.env.EMAIL_JULES || 'jules@trans-former.fr',
codevTableId: '', // NUXT_CODEV_TABLE_ID
codevPassword: 'merci', // NUXT_CODEV_PASSWORD - défaut "merci", overridable
codevPassword: '', // NUXT_CODEV_PASSWORD — aucune valeur dans le dépôt ; vide = connexion codev refusée
codevBaseId: '', // NUXT_CODEV_BASE_ID - base NocoDB (ex: pipilvsi7dibo80)
codevAdminPassword: 'admin2026', // NUXT_CODEV_ADMIN_PASSWORD
codevAdminPassword: '', // NUXT_CODEV_ADMIN_PASSWORD — aucune valeur dans le dépôt ; vide = pas d'administrateur (suppression impossible)
ragPeUrl: process.env.RAG_PE_URL || 'http://localhost:9621',
ragEmancipationUrl: '', // NUXT_RAG_EMANCIPATION_URL — LightRAG Émancipation (127.0.0.1:9623 en prod), route 9623 (P7, 24/10) ; vide = corpus non branché (503)
ragEmancipationKey: '', // NUXT_RAG_EMANCIPATION_KEY — X-API-Key de l'instance 9623 ; jamais dans le repo
+1 -2
View File
@@ -7,8 +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\"",
"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 scripts/test-codev-serrure.mjs && node --test \"worker/test/*.test.js\"",
"postinstall": "nuxt prepare"
},
"dependencies": {
-250
View File
@@ -1,250 +0,0 @@
/**
* 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())
}
+341
View File
@@ -0,0 +1,341 @@
#!/usr/bin/env node
/**
* Lot CODEV (22/11) : la serrure du codev.
*
* 1. Les fonctions de server/utils/codevAcces.ts, sans serveur (jiti).
* 2. Les VRAIES routes /api/codev/* et le VRAI garde des pages, montés dans une application h3
* en mémoire, contre un faux NocoDB local qui compte ce qu'on lui demande. Aucune requête ne
* sort de la machine. Le banc de routes du lot SURFACE n'existait pas au départ du lot : à
* raccorder à la fusion.
*
* Mots de passe et jeton d'essai inventés ici ; aucune valeur réelle, aucune ancienne valeur.
* Usage : node scripts/test-codev-serrure.mjs
*/
import { createJiti } from 'jiti'
import { fileURLToPath } from 'node:url'
import { dirname, join } from 'node:path'
import { createServer } from 'node:http'
import * as h3 from 'h3'
import { $fetch as ofetch } from 'ofetch'
const __dirname = dirname(fileURLToPath(import.meta.url))
const racine = join(__dirname, '..')
const jiti = createJiti(import.meta.url)
let ok = 0
let ko = 0
function verifier(nom, condition, detail = '') {
if (condition) { ok++; console.log(` ok ${nom}`) }
else { ko++; console.log(` KO ${nom}${detail ? ` — ${detail}` : ''}`) }
}
const MDP = 'Essai-Participant'
const MDP_ADMIN = 'essai-administrateur'
const SECRET = 'jeton-nocodb-essai'
// Ce que Nitro fournit par import automatique, pour les routes chargées hors de Nuxt.
let config = {}
function poserConfig(sur) {
config = {
nocodbUrl: '', nocodbToken: SECRET, codevTableId: 'table_essai', codevBaseId: 'base_essai',
codevPassword: MDP, codevAdminPassword: MDP_ADMIN, ...sur,
}
}
poserConfig({})
Object.assign(globalThis, {
defineEventHandler: h3.defineEventHandler,
readBody: h3.readBody,
getRouterParam: h3.getRouterParam,
createError: h3.createError,
getRequestURL: h3.getRequestURL,
sendRedirect: h3.sendRedirect,
getCookie: h3.getCookie,
setCookie: h3.setCookie,
useRuntimeConfig: () => config,
$fetch: ofetch,
})
const A = await jiti.import(join(racine, 'server', 'utils', 'codevAcces.ts'))
const cfg = () => ({ motDePasse: config.codevPassword, motDePasseAdmin: config.codevAdminPassword, secret: config.nocodbToken })
// ─────────────────────────────────────────────────────────────────────────────
console.log('\n1. Fonctions, sans serveur')
{
const c = cfg()
verifier('mot de passe participant → participant', A.roleDuMotDePasse(MDP, c) === 'participant')
verifier('même normalisation qu’avant (espaces, casse)', A.roleDuMotDePasse(` ${MDP.toUpperCase()} `, c) === 'participant')
verifier('mot de passe administrateur → admin', A.roleDuMotDePasse(MDP_ADMIN, c) === 'admin')
verifier('mauvais mot de passe → personne', A.roleDuMotDePasse('autre', c) === null)
verifier('mot de passe vide → personne', A.roleDuMotDePasse(' ', c) === null)
verifier('fermé : participant non configuré → aucune connexion',
A.roleDuMotDePasse(MDP, { ...c, motDePasse: '' }) === null && A.roleDuMotDePasse(MDP_ADMIN, { ...c, motDePasse: undefined }) === null)
verifier('fermé : administrateur non configuré → participant marche, admin n’existe pas',
A.roleDuMotDePasse(MDP, { ...c, motDePasseAdmin: '' }) === 'participant'
&& A.roleDuMotDePasse('', { ...c, motDePasseAdmin: '' }) === null)
verifier('comparaison en temps constant : longueurs différentes sans exception', A.egalEnTempsConstant('a', 'abcdef') === false)
const cle = A.deriverCle(c)
verifier('clé de 32 octets', cle.length === 32)
verifier('clé différente si le secret change', !cle.equals(A.deriverCle({ ...c, secret: 'autre' })))
verifier('clé différente si un mot de passe change', !cle.equals(A.deriverCle({ ...c, motDePasse: 'autre' })))
const t0 = Date.UTC(2026, 10, 22, 12)
const tp = A.signerTemoin('participant', cle, t0)
const ta = A.signerTemoin('admin', cle, t0)
verifier('témoin participant vérifié', A.verifierTemoin(tp, cle, t0 + 1000) === 'participant')
verifier('témoin admin vérifié', A.verifierTemoin(ta, cle, t0 + 1000) === 'admin')
verifier('le témoin ne contient ni mot de passe ni secret', !tp.includes(MDP) && !Buffer.from(tp.split('.')[0], 'base64url').toString().includes(SECRET))
verifier('témoin « ok » à l’ancienne refusé', A.verifierTemoin('ok', cle, t0) === null)
verifier('témoin absent refusé', A.verifierTemoin(undefined, cle, t0) === null)
const [corps, sig] = tp.split('.')
const corpsAdmin = Buffer.from(JSON.stringify({ r: 'a', exp: JSON.parse(Buffer.from(corps, 'base64url')).exp })).toString('base64url')
verifier('témoin modifié (rôle changé, signature gardée) refusé', A.verifierTemoin(`${corpsAdmin}.${sig}`, cle, t0) === null)
verifier('témoin signé d’une autre clé refusé', A.verifierTemoin(A.signerTemoin('admin', A.deriverCle({ ...c, secret: 'x' }), t0), cle, t0) === null)
verifier('témoin périmé (24 h + 1 s) refusé', A.verifierTemoin(tp, cle, t0 + (A.DUREE_SESSION_S + 1) * 1000) === null)
verifier('témoin encore valide à 23 h 59', A.verifierTemoin(tp, cle, t0 + (A.DUREE_SESSION_S - 60) * 1000) === 'participant')
verifier('témoin à trois morceaux refusé', A.verifierTemoin(`${tp}.x`, cle, t0) === null)
verifier('témoin trop long refusé', A.verifierTemoin('a'.repeat(600) + '.b', cle, t0) === null)
verifier('admin signé mais administrateur retiré de la config → personne',
A.roleDuTemoin(ta, { ...c }, t0) === 'admin' && A.roleDuTemoin(A.signerTemoin('admin', A.deriverCle({ ...c, motDePasseAdmin: '' }), t0), { ...c, motDePasseAdmin: '' }, t0) === null)
verifier('participant non configuré → aucun témoin ne vaut', A.roleDuTemoin(tp, { ...c, motDePasse: '' }, t0) === null)
verifier('identifiant 12 → 12', A.idFicheCodev('12') === 12)
for (const mauvais of ['0', '-1', '1.5', '1e3', '012', ' 1', '1 ', 'abc', '1;DROP', '99999999999', '', undefined, '%31']) {
verifier(`identifiant ${JSON.stringify(mauvais)} refusé`, A.idFicheCodev(mauvais) === null)
}
const l = A.creerLimiteur(3, 1000)
l.compter('x', 0); l.compter('x', 10); l.compter('x', 20)
verifier('limiteur : 3 essais puis refus', l.autorise('x', 30) === false && l.autorise('y', 30) === true)
verifier('limiteur : la fenêtre glisse', l.autorise('x', 1011) === true)
}
// ─────────────────────────────────────────────────────────────────────────────
// Faux NocoDB : compte et garde ce qu'on lui demande.
const demandes = []
const lignes = new Map()
let prochainId = 1
const nocodb = createServer(async (req, res) => {
let corps = ''
for await (const morceau of req) corps += morceau
demandes.push({ methode: req.method, url: req.url, corps, jeton: req.headers['xc-token'] })
const json = (code, v) => { res.writeHead(code, { 'content-type': 'application/json' }); res.end(JSON.stringify(v)) }
const u = new URL(req.url, 'http://x')
const v1 = u.pathname.match(/^\/api\/v1\/db\/data\/noco\/base_essai\/table_essai(?:\/(\d+))?$/)
if (req.method === 'GET' && u.pathname === '/api/v2/tables/table_essai/records') return json(200, { list: [...lignes.values()] })
if (req.method === 'DELETE' && u.pathname === '/api/v2/tables/table_essai/records') {
const { Id } = JSON.parse(corps); lignes.delete(Id); return json(200, { Id })
}
if (v1 && req.method === 'POST' && !v1[1]) {
const l = { Id: prochainId++, ...JSON.parse(corps) }; lignes.set(l.Id, l); return json(200, l)
}
if (v1 && v1[1] && req.method === 'GET') return lignes.has(+v1[1]) ? json(200, lignes.get(+v1[1])) : json(404, {})
if (v1 && v1[1] && req.method === 'PATCH') {
if (!lignes.has(+v1[1])) return json(404, {})
Object.assign(lignes.get(+v1[1]), JSON.parse(corps)); return json(200, {})
}
json(404, {})
})
await new Promise((r) => nocodb.listen(0, '127.0.0.1', r))
const urlNocodb = `http://127.0.0.1:${nocodb.address().port}`
poserConfig({ nocodbUrl: urlNocodb })
// Les vraies routes et le vrai garde.
const route = async (f) => (await jiti.import(join(racine, 'server', f))).default
const app = h3.createApp()
app.use(await route('middleware/codev-auth.ts'))
const routeur = h3.createRouter()
.post('/api/codev/auth', await route('api/codev/auth.post.ts'))
.get('/api/codev/me', await route('api/codev/me.get.ts'))
.get('/api/codev/fiches', await route('api/codev/fiches.get.ts'))
.post('/api/codev/fiches', await route('api/codev/fiches.post.ts'))
.get('/api/codev/fiches/:id', await route('api/codev/fiches/[id].get.ts'))
.patch('/api/codev/fiches/:id', await route('api/codev/fiches/[id].patch.ts'))
.delete('/api/codev/fiches/:id', await route('api/codev/fiches/[id].delete.ts'))
.get('/codev/**', h3.defineEventHandler(() => 'page'))
.get('/codev', h3.defineEventHandler(() => 'page'))
app.use(routeur)
const site = createServer(h3.toNodeListener(app))
await new Promise((r) => site.listen(0, '127.0.0.1', r))
const base = `http://127.0.0.1:${site.address().port}`
async function appel(methode, chemin, { temoin, corps, adresse = '203.0.113.1' } = {}) {
const headers = { 'x-forwarded-for': adresse }
if (temoin) headers.cookie = temoin
if (corps) headers['content-type'] = 'application/json'
const r = await fetch(base + chemin, { method: methode, headers, body: corps ? JSON.stringify(corps) : undefined, redirect: 'manual' })
const texte = await r.text()
let json = null
try { json = JSON.parse(texte) } catch {}
return { statut: r.status, json, texte, lieu: r.headers.get('location'), cookies: r.headers.getSetCookie() }
}
function temoinDe(reponse) {
const c = reponse.cookies.find((x) => x.startsWith(`${A.NOM_TEMOIN}=`))
return c ? c.split(';')[0] : null
}
const fiche = (sur = {}) => ({ nom: 'Camille', besoin: 'Trouver un local partagé', offre: 'Je sais monter un budget', hashtags: ['local'], ...sur })
try {
console.log('\n2. Chaque route, chaque témoin (faux NocoDB)')
lignes.set(1, { Id: 1, nom: 'Essai', besoin: 'besoin essai', offre: 'offre essai', hashtags: 'a', created_at: '2026-11-22' })
prochainId = 2
const cleServeur = A.deriverCle(cfg())
const tp = `${A.NOM_TEMOIN}=${A.signerTemoin('participant', cleServeur)}`
const ta = `${A.NOM_TEMOIN}=${A.signerTemoin('admin', cleServeur)}`
const [corpsP, sigP] = tp.split('=')[1].split('.')
const exp = JSON.parse(Buffer.from(corpsP, 'base64url')).exp
const temoins = {
'sans témoin': null,
'témoin « ok » à l’ancienne': `${A.NOM_TEMOIN}=ok; codev_admin=ok`,
'témoin signé modifié': `${A.NOM_TEMOIN}=${Buffer.from(JSON.stringify({ r: 'a', exp })).toString('base64url')}.${sigP}`,
'témoin périmé': `${A.NOM_TEMOIN}=${A.signerTemoin('admin', cleServeur, Date.now() - (A.DUREE_SESSION_S + 60) * 1000)}`,
}
const routes = [
['GET', '/api/codev/me'],
['GET', '/api/codev/fiches'],
['GET', '/api/codev/fiches/1'],
['POST', '/api/codev/fiches', fiche()],
['PATCH', '/api/codev/fiches/1', fiche({ nom: 'Essai modifié' })],
['DELETE', '/api/codev/fiches/1'],
]
for (const [nomTemoin, temoin] of Object.entries(temoins)) {
for (const [m, ch, corps] of routes) {
const avant = demandes.length
const r = await appel(m, ch, { temoin, corps })
verifier(`${nomTemoin} · ${m} ${ch} → 401, rien à NocoDB`, r.statut === 401 && demandes.length === avant, `${r.statut}, ${demandes.length - avant} demande(s)`)
}
for (const page of ['/codev/fiche', '/codev/carto', '/codev/fiche?id=1']) {
const r = await appel('GET', page, { temoin })
verifier(`${nomTemoin} · page ${page} → vers /codev/acces`, r.statut === 302 && r.lieu === '/codev/acces', `${r.statut} ${r.lieu}`)
}
}
for (const page of ['/codev', '/codev/demo', '/codev/acces', '/codev/qr']) {
const r = await appel('GET', page)
verifier(`page ${page} ouverte sans témoin`, r.statut === 200)
}
// Participant : tout sauf la suppression.
for (const [m, ch, corps] of routes) {
const avant = demandes.length
const r = await appel(m, ch, { temoin: tp, corps })
if (m === 'DELETE') verifier(`participant · DELETE → 403, rien à NocoDB`, r.statut === 403 && demandes.length === avant, `${r.statut}`)
else verifier(`participant · ${m} ${ch} → 200`, r.statut === 200, `${r.statut} ${r.texte.slice(0, 120)}`)
}
for (const page of ['/codev/fiche', '/codev/carto']) {
verifier(`participant · page ${page} → 200`, (await appel('GET', page, { temoin: tp })).statut === 200)
}
verifier('participant · /me dit admin=false', (await appel('GET', '/api/codev/me', { temoin: tp })).json?.admin === false)
// Administrateur : tout.
verifier('admin · /me dit admin=true', (await appel('GET', '/api/codev/me', { temoin: ta })).json?.admin === true)
verifier('admin · GET liste → 200', (await appel('GET', '/api/codev/fiches', { temoin: ta })).statut === 200)
verifier('admin · PATCH → 200', (await appel('PATCH', '/api/codev/fiches/1', { temoin: ta, corps: fiche() })).statut === 200)
verifier('admin · DELETE 1 → 200 et la ligne part', (await appel('DELETE', '/api/codev/fiches/1', { temoin: ta })).statut === 200 && !lignes.has(1))
console.log('\n3. Identifiant de fiche : rien d’autre qu’un entier positif n’atteint NocoDB')
for (const id of ['0', '-3', 'abc', '1.5', '1%3B2', '..%2F..%2Fx', '99999999999']) {
for (const [m, corps] of [['GET'], ['PATCH', fiche()], ['DELETE']]) {
const avant = demandes.length
const r = await appel(m, `/api/codev/fiches/${id}`, { temoin: ta, corps })
verifier(`${m} /fiches/${id} → 400 ou 404, rien à NocoDB`, [400, 404, 405].includes(r.statut) && demandes.length === avant, `${r.statut}, ${demandes.length - avant}`)
}
}
console.log('\n4. Parcours entier, comme dans la salle')
lignes.clear(); prochainId = 1
{
const ip = '198.51.100.7'
const faux = await appel('POST', '/api/codev/auth', { corps: { password: 'je-me-trompe' }, adresse: ip })
verifier('participant · mauvais mot de passe → 401, aucun témoin', faux.statut === 401 && !temoinDe(faux))
const connexion = await appel('POST', '/api/codev/auth', { corps: { password: ` ${MDP.toLowerCase()} ` }, adresse: ip })
const t = temoinDe(connexion)
verifier('participant · connexion → 200, admin=false, témoin signé posé', connexion.statut === 200 && connexion.json?.admin === false && t && t !== `${A.NOM_TEMOIN}=ok`)
const brut = connexion.cookies.find((x) => x.startsWith(`${A.NOM_TEMOIN}=`)) || ''
verifier('témoin HttpOnly, SameSite=Lax, Max-Age 24 h, Path=/', /HttpOnly/i.test(brut) && /SameSite=Lax/i.test(brut) && /Max-Age=86400/.test(brut) && /Path=\//.test(brut))
verifier('l’ancien témoin administrateur est effacé à la connexion', connexion.cookies.some((x) => x.startsWith('codev_admin=;') && /Max-Age=0/.test(x)))
verifier('participant · liste vide → 200, []', (await appel('GET', '/api/codev/fiches', { temoin: t, adresse: ip })).json?.list?.length === 0)
const cree = await appel('POST', '/api/codev/fiches', { temoin: t, corps: fiche(), adresse: ip })
verifier('participant · création → 200, id 1', cree.statut === 200 && cree.json?.id === 1)
const lue = await appel('GET', '/api/codev/fiches/1', { temoin: t, adresse: ip })
verifier('participant · lecture de sa fiche', lue.statut === 200 && lue.json?.nom === 'Camille' && lue.json?.hashtags?.[0] === 'local')
const modif = await appel('PATCH', '/api/codev/fiches/1', { temoin: t, corps: fiche({ offre: 'Je sais tenir une compta' }), adresse: ip })
verifier('participant · modification → 200, écrite', modif.statut === 200 && lignes.get(1)?.offre === 'Je sais tenir une compta')
verifier('participant · la liste rend sa fiche', (await appel('GET', '/api/codev/fiches', { temoin: t, adresse: ip })).json?.list?.length === 1)
verifier('participant · suppression refusée (403), la fiche reste', (await appel('DELETE', '/api/codev/fiches/1', { temoin: t, adresse: ip })).statut === 403 && lignes.has(1))
verifier('NocoDB reçoit le jeton du serveur, jamais le témoin', demandes.every((d) => d.jeton === SECRET && !String(d.corps).includes(A.NOM_TEMOIN)))
const cadmin = await appel('POST', '/api/codev/auth', { corps: { password: MDP_ADMIN }, adresse: ip })
const tad = temoinDe(cadmin)
verifier('admin · connexion → 200, admin=true', cadmin.statut === 200 && cadmin.json?.admin === true && !!tad)
verifier('admin · un seul témoin (plus de codev_admin=ok)', !cadmin.cookies.some((x) => x.startsWith('codev_admin=ok')))
verifier('admin · suppression → 200, la fiche part', (await appel('DELETE', '/api/codev/fiches/1', { temoin: tad, adresse: ip })).statut === 200 && !lignes.has(1))
verifier('admin · liste de nouveau vide', (await appel('GET', '/api/codev/fiches', { temoin: tad, adresse: ip })).json?.list?.length === 0)
}
console.log('\n5. Fermé par défaut')
{
poserConfig({ nocodbUrl: urlNocodb, codevAdminPassword: '' })
const ip = '198.51.100.20'
const c = await appel('POST', '/api/codev/auth', { corps: { password: MDP }, adresse: ip })
const t = temoinDe(c)
verifier('sans mot de passe administrateur : le participant entre', c.statut === 200 && c.json?.admin === false)
const creee = await appel('POST', '/api/codev/fiches', { temoin: t, corps: fiche(), adresse: ip })
const id = creee.json?.id
verifier('sans mot de passe administrateur : il crée une fiche', creee.statut === 200 && lignes.has(id))
verifier('sans mot de passe administrateur : un mot de passe vide ne donne rien', (await appel('POST', '/api/codev/auth', { corps: { password: ' ' }, adresse: ip })).statut === 401)
verifier('sans mot de passe administrateur : personne ne supprime', (await appel('DELETE', `/api/codev/fiches/${id}`, { temoin: t, adresse: ip })).statut === 403 && lignes.has(id))
const tadForge = `${A.NOM_TEMOIN}=${A.signerTemoin('admin', A.deriverCle(cfg()))}`
verifier('sans mot de passe administrateur : même un témoin admin bien signé ne vaut rien', (await appel('DELETE', `/api/codev/fiches/${id}`, { temoin: tadForge, adresse: ip })).statut === 401 && lignes.has(id))
poserConfig({ nocodbUrl: urlNocodb, codevPassword: '' })
verifier('sans mot de passe participant : connexion refusée', (await appel('POST', '/api/codev/auth', { corps: { password: MDP }, adresse: ip })).statut === 401)
verifier('sans mot de passe participant : même l’administrateur n’entre pas', (await appel('POST', '/api/codev/auth', { corps: { password: MDP_ADMIN }, adresse: ip })).statut === 401)
verifier('sans mot de passe participant : la liste est fermée (401)', (await appel('GET', '/api/codev/fiches', { temoin: t, adresse: ip })).statut === 401)
verifier('sans mot de passe participant : la page carto renvoie au mot de passe', (await appel('GET', '/codev/carto', { temoin: t, adresse: ip })).statut === 302)
poserConfig({ nocodbUrl: urlNocodb })
}
console.log('\n6. Limite d’essais à la connexion (30 échecs / 15 min, 200 / jour, par adresse)')
{
A.limiteEchecsQuart.vider(); A.limiteEchecsJour.vider()
const salle = '192.0.2.50'
// Vingt personnes derrière la même connexion : chacune se trompe une fois, puis entre.
let tous = true
for (let i = 0; i < 20; i++) {
const f = await appel('POST', '/api/codev/auth', { corps: { password: `faute-${i}` }, adresse: salle })
const b = await appel('POST', '/api/codev/auth', { corps: { password: MDP }, adresse: salle })
tous = tous && f.statut === 401 && b.statut === 200
}
verifier('salle de 20 : une faute chacune puis toutes entrent', tous)
for (let i = 0; i < 10; i++) await appel('POST', '/api/codev/auth', { corps: { password: `x${i}` }, adresse: salle })
const bloque = await appel('POST', '/api/codev/auth', { corps: { password: MDP }, adresse: salle })
verifier('au 31e essai raté : 429, même avec le bon mot de passe', bloque.statut === 429, `${bloque.statut}`)
verifier('le message dit d’attendre', /réessaie/.test(bloque.json?.statusMessage || bloque.json?.message || ''))
verifier('une autre adresse n’est pas gênée', (await appel('POST', '/api/codev/auth', { corps: { password: MDP }, adresse: '192.0.2.51' })).statut === 200)
verifier('une session déjà ouverte dans la salle continue de lire', (await appel('GET', '/api/codev/fiches', { temoin: temoinDe(await appel('POST', '/api/codev/auth', { corps: { password: MDP }, adresse: '192.0.2.52' })), adresse: salle })).statut === 200)
A.limiteEchecsQuart.vider(); A.limiteEchecsJour.vider()
}
console.log('\n7. Débit des écritures (60 / 10 min, par adresse)')
{
A.limiteEcritures.vider()
const ip = '192.0.2.80'
const c = await appel('POST', '/api/codev/auth', { corps: { password: MDP }, adresse: ip })
const t = temoinDe(c)
let passes = 0
for (let i = 0; i < 60; i++) if ((await appel('POST', '/api/codev/fiches', { temoin: t, corps: fiche({ nom: `Nom ${i}` }), adresse: ip })).statut === 200) passes++
verifier('60 créations passent', passes === 60, `${passes}`)
const avant = demandes.length
const r = await appel('POST', '/api/codev/fiches', { temoin: t, corps: fiche(), adresse: ip })
verifier('la 61e → 429, rien à NocoDB', r.statut === 429 && demandes.length === avant, `${r.statut}`)
verifier('la modification compte aussi', (await appel('PATCH', '/api/codev/fiches/2', { temoin: t, corps: fiche(), adresse: ip })).statut === 429)
verifier('la lecture reste permise', (await appel('GET', '/api/codev/fiches', { temoin: t, adresse: ip })).statut === 200)
A.limiteEcritures.vider()
}
} finally {
site.close()
nocodb.close()
}
console.log(`\n${ok} ok, ${ko} KO`)
process.exit(ko ? 1 : 0)
-57
View File
@@ -1,57 +0,0 @@
#!/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)
+16 -27
View File
@@ -1,10 +1,19 @@
import { z } from 'zod'
import {
adresseCodev, configCodev, limiteEchecsJour, limiteEchecsQuart, poserSession, roleDuMotDePasse,
} from '../../utils/codevAcces'
const AuthSchema = z.object({
password: z.string().min(1).max(100),
})
export default defineEventHandler(async (event) => {
const adresse = adresseCodev(event)
// Seuls les échecs comptent : une salle derrière la même connexion n'est pas gênée.
if (!limiteEchecsQuart.autorise(adresse) || !limiteEchecsJour.autorise(adresse)) {
throw createError({ statusCode: 429, statusMessage: "Trop d'essais, réessaie dans quelques minutes" })
}
const body = await readBody(event)
const parsed = AuthSchema.safeParse(body)
@@ -12,35 +21,15 @@ export default defineEventHandler(async (event) => {
throw createError({ statusCode: 422, statusMessage: 'Mot de passe invalide' })
}
const config = useRuntimeConfig()
const expected = config.codevPassword || 'merci'
const config = configCodev()
const role = roleDuMotDePasse(parsed.data.password, config)
const isAdmin = parsed.data.password.trim().toLowerCase() === (config.codevAdminPassword || 'admin2026').trim().toLowerCase()
const isUser = parsed.data.password.trim().toLowerCase() === expected.trim().toLowerCase()
if (!isAdmin && !isUser) {
if (!role) {
limiteEchecsQuart.compter(adresse)
limiteEchecsJour.compter(adresse)
throw createError({ statusCode: 401, statusMessage: 'Mauvais mot de passe' })
}
// Cookie session (user + admin)
setCookie(event, 'codev_session', 'ok', {
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60 * 24, // 24h
path: '/',
})
// Cookie admin si mot de passe admin
if (isAdmin) {
setCookie(event, 'codev_admin', 'ok', {
httpOnly: true,
sameSite: 'lax',
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60 * 24, // 24h
path: '/',
})
}
return { status: 200, ok: true, admin: isAdmin }
poserSession(event, role, config)
return { status: 200, ok: true, admin: role === 'admin' }
})
+2
View File
@@ -1,6 +1,8 @@
import type { CodevFiche } from '~/types/codev'
import { exigerRole } from '../../utils/codevAcces'
export default defineEventHandler(async (event): Promise<{ list: CodevFiche[] }> => {
exigerRole(event, 'participant')
const config = useRuntimeConfig()
const tableId = config.codevTableId
+3
View File
@@ -1,4 +1,5 @@
import { z } from 'zod'
import { exigerRole, limiterEcriture } from '../../utils/codevAcces'
const FicheSchema = z.object({
nom: z.string().min(2).max(50).trim(),
@@ -8,6 +9,8 @@ const FicheSchema = z.object({
})
export default defineEventHandler(async (event) => {
exigerRole(event, 'participant')
limiterEcriture(event)
const body = await readBody(event)
const parsed = FicheSchema.safeParse(body)
+6 -8
View File
@@ -1,22 +1,20 @@
import { exigerIdFiche, exigerRole } from '../../../utils/codevAcces'
export default defineEventHandler(async (event) => {
// Vérif cookie admin
const adminCookie = getCookie(event, 'codev_admin')
if (adminCookie !== 'ok') {
throw createError({ statusCode: 403, statusMessage: 'Accès refusé' })
}
exigerRole(event, 'admin')
const id = exigerIdFiche(getRouterParam(event, 'id'))
const config = useRuntimeConfig()
const tableId = config.codevTableId
const id = getRouterParam(event, 'id')
if (!tableId || !id) {
if (!tableId) {
throw createError({ statusCode: 400, message: 'Parametre manquant' })
}
await $fetch(`${config.nocodbUrl}/api/v2/tables/${tableId}/records`, {
method: 'DELETE',
headers: { 'xc-token': config.nocodbToken, 'Content-Type': 'application/json' },
body: JSON.stringify({ Id: Number(id) }),
body: JSON.stringify({ Id: id }),
}).catch(() => {
throw createError({ statusCode: 502, statusMessage: 'Erreur suppression' })
})
+4 -2
View File
@@ -1,12 +1,14 @@
import type { CodevFiche } from '~/types/codev'
import { exigerIdFiche, exigerRole } from '../../../utils/codevAcces'
export default defineEventHandler(async (event): Promise<CodevFiche> => {
exigerRole(event, 'participant')
const id = exigerIdFiche(getRouterParam(event, 'id'))
const config = useRuntimeConfig()
const tableId = config.codevTableId
const baseId = config.codevBaseId || 'pipilvsi7dibo80'
const id = getRouterParam(event, 'id')
if (!tableId || !id) {
if (!tableId) {
throw createError({ statusCode: 400, message: 'Parametre manquant' })
}
+5 -2
View File
@@ -1,4 +1,5 @@
import { z } from 'zod'
import { exigerIdFiche, exigerRole, limiterEcriture } from '../../../utils/codevAcces'
const PatchSchema = z.object({
nom: z.string().min(2).max(50).trim(),
@@ -8,13 +9,15 @@ const PatchSchema = z.object({
})
export default defineEventHandler(async (event) => {
exigerRole(event, 'participant')
const id = exigerIdFiche(getRouterParam(event, 'id'))
limiterEcriture(event)
const config = useRuntimeConfig()
const tableId = config.codevTableId
const baseId = config.codevBaseId || 'pipilvsi7dibo80'
const id = getRouterParam(event, 'id')
const body = await readBody(event)
if (!tableId || !id) {
if (!tableId) {
throw createError({ statusCode: 400, message: 'Parametre manquant' })
}
+4 -3
View File
@@ -1,5 +1,6 @@
import { exigerRole } from '../../utils/codevAcces'
export default defineEventHandler((event) => {
const admin = getCookie(event, 'codev_admin') === 'ok'
const session = getCookie(event, 'codev_session') === 'ok'
return { admin, session }
const role = exigerRole(event, 'participant')
return { admin: role === 'admin', session: true }
})
+1 -4
View File
@@ -15,9 +15,6 @@
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
@@ -39,7 +36,7 @@ async function filtreEthique(
const timeout = setTimeout(() => controller.abort(), 2000)
try {
const response: any = await $fetch(`${MISTRAL_API_URL}/v1/chat/completions`, {
const response: any = await $fetch('https://api.mistral.ai/v1/chat/completions', {
method: 'POST',
headers: {
Authorization: `Bearer ${mistralKey}`,
+1 -3
View File
@@ -11,8 +11,6 @@
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
@@ -62,7 +60,7 @@ export default defineEventHandler(async (event) => {
const submittedAt = new Date().toLocaleString('fr-FR', { timeZone: 'Europe/Paris' })
try {
await $fetch(`${RESEND_API_URL}/emails`, {
await $fetch('https://api.resend.com/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${resendApiKey}`,
+1 -3
View File
@@ -12,8 +12,6 @@
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
@@ -59,7 +57,7 @@ export default defineEventHandler(async (event) => {
const submittedAt = new Date().toLocaleString('fr-FR', { timeZone: 'Europe/Paris' })
try {
await $fetch(`${RESEND_API_URL}/emails`, {
await $fetch('https://api.resend.com/emails', {
method: 'POST',
headers: {
Authorization: `Bearer ${resendApiKey}`,
+14 -14
View File
@@ -1,23 +1,23 @@
// Middleware server Nuxt — protection des routes /codev/fiche et /codev/carto
// Laisse passer /codev (la recette, publique depuis le lot Y), /codev/acces (écran du mot de passe),
// /codev/demo, /codev/qr et toutes les routes /api/*
// Middleware server Nuxt : garde des pages /codev/fiche et /codev/carto (lot CODEV, 22/11).
// Ouvertes : /codev (la recette, publique depuis le lot Y), /codev/acces (écran du mot de passe),
// /codev/demo et /codev/qr. Les routes /api/codev/* se gardent elles-mêmes (exigerRole) :
// ce middleware ne regarde que les pages.
// La décision vient de la seule fonction roleDuVisiteur (server/utils/codevAcces.ts).
import { roleDuVisiteur } from '../utils/codevAcces'
const OUVERTES = ['/codev/demo', '/codev/qr', '/codev/acces']
export default defineEventHandler((event) => {
const url = getRequestURL(event)
const path = url.pathname
const path = getRequestURL(event).pathname
// Seulement les routes sous /codev/
// Seulement les pages sous /codev/
if (!path.startsWith('/codev/')) return
// Routes publiques : /codev/demo et /codev/qr (et sous-routes éventuelles)
if (path === '/codev/demo' || path.startsWith('/codev/demo/')) return
if (path === '/codev/qr' || path.startsWith('/codev/qr/')) return
if (path === '/codev/acces' || path.startsWith('/codev/acces/')) return
if (OUVERTES.some((p) => path === p || path.startsWith(`${p}/`))) return
// Vérification cookie
const session = getCookie(event, 'codev_session')
if (session === 'ok') return
if (roleDuVisiteur(event)) return
// Non authentifié -> redirect vers l'écran du mot de passe
// Pas de session valide -> l'écran du mot de passe
return sendRedirect(event, '/codev/acces', 302)
})
+267
View File
@@ -0,0 +1,267 @@
/**
* Codev : la serrure (lot CODEV, 22/11).
*
* Une seule fonction décide qui est le visiteur : `roleDuVisiteur(event)` rend
* 'participant', 'admin' ou null. Les routes /api/codev/* et le garde des pages
* /codev/fiche et /codev/carto l'appellent, rien d'autre ne lit le témoin.
*
* Le témoin `codev_session` est signé par le serveur (HMAC-SHA256) et porte le rôle
* et sa date d'expiration. La clé est dérivée du jeton NocoDB que le serveur a déjà
* (et des deux mots de passe : en changer un fait tomber les sessions ouvertes) ;
* elle n'est jamais rendue, jamais écrite. Sans jeton NocoDB (essai local), la clé
* est tirée au hasard au démarrage : les sessions tombent au redémarrage.
*
* Fermé par défaut : aucun mot de passe n'a de valeur dans le dépôt. Mot de passe
* participant absent → aucune connexion. Mot de passe administrateur absent → le rôle
* administrateur n'existe pas, le parcours participant marche quand même.
*
* Les fonctions pures (signer, vérifier, comparer, limiter, lire un identifiant) se
* testent sans serveur : scripts/test-codev-serrure.mjs.
*/
import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto'
import { createError, deleteCookie, getCookie, getHeader, setCookie, type H3Event } from 'h3'
export type RoleCodev = 'participant' | 'admin'
export const NOM_TEMOIN = 'codev_session'
/** Ancien témoin administrateur (valait la chaîne « ok ») : effacé à la connexion, jamais lu. */
export const ANCIEN_TEMOIN_ADMIN = 'codev_admin'
/** Durée d'une session : 24 h, comme avant. */
export const DUREE_SESSION_S = 60 * 60 * 24
export interface ConfigCodev {
/** Mot de passe participant ; vide ou absent = connexion refusée. */
motDePasse?: string
/** Mot de passe administrateur ; vide ou absent = rôle administrateur inexistant. */
motDePasseAdmin?: string
/** Secret que le serveur a déjà (jeton NocoDB) : matière de la clé de signature. */
secret?: string
}
// ── Mots de passe ──────────────────────────────────────────────────────────────
/** Même normalisation qu'avant le lot : espaces de bord retirés, casse ignorée. */
export function normaliserMotDePasse(motDePasse: unknown): string {
return typeof motDePasse === 'string' ? motDePasse.trim().toLowerCase() : ''
}
/** Comparaison en temps constant (les deux côtés sont ramenés à une empreinte de même longueur). */
export function egalEnTempsConstant(a: string, b: string): boolean {
const ea = createHash('sha256').update(a, 'utf8').digest()
const eb = createHash('sha256').update(b, 'utf8').digest()
return timingSafeEqual(ea, eb)
}
/** Le rôle que donne ce mot de passe, ou null. Les deux comparaisons sont toujours faites. */
export function roleDuMotDePasse(saisi: unknown, config: ConfigCodev): RoleCodev | null {
const participant = normaliserMotDePasse(config.motDePasse)
if (!participant) return null // fermé par défaut : aucune connexion sans mot de passe participant
const admin = normaliserMotDePasse(config.motDePasseAdmin)
const s = normaliserMotDePasse(saisi)
if (!s) return null
const estParticipant = egalEnTempsConstant(s, participant)
const estAdmin = admin ? egalEnTempsConstant(s, admin) : false
if (estAdmin) return 'admin'
if (estParticipant) return 'participant'
return null
}
// ── Clé et témoin signé ────────────────────────────────────────────────────────
const cleDeSecours = randomBytes(32)
const clesDerivees = new Map<string, Buffer>()
/** Clé de signature, dérivée ; jamais rendue au client, jamais journalisée. */
export function deriverCle(config: ConfigCodev): Buffer {
const matiere = [
'aep-codev-session-v1',
normaliserMotDePasse(config.motDePasse),
normaliserMotDePasse(config.motDePasseAdmin),
].join('\u0000')
const secret = config.secret || ''
const memo = createHash('sha256').update(secret).update('\u0000').update(matiere).digest('hex')
let cle = clesDerivees.get(memo)
if (!cle) {
cle = createHmac('sha256', secret ? Buffer.from(secret, 'utf8') : cleDeSecours).update(matiere).digest()
clesDerivees.clear() // une seule configuration vit à la fois
clesDerivees.set(memo, cle)
}
return cle
}
function b64url(buf: Buffer): string {
return buf.toString('base64url')
}
function signature(corps: string, cle: Buffer): Buffer {
return createHmac('sha256', cle).update(corps).digest()
}
/** Témoin = base64url({"r":"p"|"a","exp":secondes}) + "." + base64url(HMAC). */
export function signerTemoin(role: RoleCodev, cle: Buffer, maintenantMs = Date.now(), dureeS = DUREE_SESSION_S): string {
const corps = b64url(Buffer.from(JSON.stringify({
r: role === 'admin' ? 'a' : 'p',
exp: Math.floor(maintenantMs / 1000) + dureeS,
}), 'utf8'))
return `${corps}.${b64url(signature(corps, cle))}`
}
/** Rend le rôle porté par un témoin valide, ou null (absent, à l'ancienne, modifié, périmé, illisible). */
export function verifierTemoin(valeur: unknown, cle: Buffer, maintenantMs = Date.now()): RoleCodev | null {
if (typeof valeur !== 'string' || valeur.length > 512) return null
const parties = valeur.split('.')
if (parties.length !== 2) return null
const [corps, sig] = parties
if (!/^[A-Za-z0-9_-]+$/.test(corps) || !/^[A-Za-z0-9_-]+$/.test(sig)) return null
const attendue = signature(corps, cle)
const recue = Buffer.from(sig, 'base64url')
if (recue.length !== attendue.length || !timingSafeEqual(recue, attendue)) return null
let charge: any
try {
charge = JSON.parse(Buffer.from(corps, 'base64url').toString('utf8'))
} catch {
return null
}
if (!charge || typeof charge.exp !== 'number' || !Number.isFinite(charge.exp)) return null
if (charge.exp * 1000 <= maintenantMs) return null
if (charge.r === 'a') return 'admin'
if (charge.r === 'p') return 'participant'
return null
}
/** Le rôle porté par un témoin, compte tenu de la configuration du moment. */
export function roleDuTemoin(valeur: unknown, config: ConfigCodev, maintenantMs = Date.now()): RoleCodev | null {
if (!normaliserMotDePasse(config.motDePasse)) return null // codev fermé : aucune session ne vaut
const role = verifierTemoin(valeur, deriverCle(config), maintenantMs)
if (role === 'admin' && !normaliserMotDePasse(config.motDePasseAdmin)) return null
return role
}
// ── Identifiant de fiche ───────────────────────────────────────────────────────
/** Un entier positif écrit en chiffres, et rien d'autre ; sinon null. */
export function idFicheCodev(brut: unknown): number | null {
if (typeof brut !== 'string' || !/^[1-9][0-9]{0,9}$/.test(brut)) return null
const n = Number(brut)
return Number.isSafeInteger(n) && n <= 2147483647 ? n : null
}
// ── Limites de débit (en mémoire : le site tourne en un seul processus) ────────
export interface Limiteur {
/** Vrai si l'adresse a encore droit à un essai ; ne compte rien. */
autorise(cle: string, maintenantMs?: number): boolean
/** Compte un essai pour cette adresse. */
compter(cle: string, maintenantMs?: number): void
/** Compte et dit si c'était permis (pour les écritures : chaque appel compte). */
prendre(cle: string, maintenantMs?: number): boolean
vider(): void
}
/** Fenêtre glissante : au plus `max` essais par `fenetreMs` et par clé. */
export function creerLimiteur(max: number, fenetreMs: number): Limiteur {
const essais = new Map<string, number[]>()
function recents(cle: string, maintenant: number): number[] {
const liste = (essais.get(cle) || []).filter((t) => t > maintenant - fenetreMs)
if (liste.length) essais.set(cle, liste)
else essais.delete(cle)
return liste
}
function menage(maintenant: number) {
if (essais.size < 5000) return
for (const cle of [...essais.keys()]) recents(cle, maintenant)
}
return {
autorise(cle, maintenant = Date.now()) {
return recents(cle, maintenant).length < max
},
compter(cle, maintenant = Date.now()) {
menage(maintenant)
const liste = recents(cle, maintenant)
liste.push(maintenant)
essais.set(cle, liste)
},
prendre(cle, maintenant = Date.now()) {
if (!this.autorise(cle, maintenant)) return false
this.compter(cle, maintenant)
return true
},
vider() {
essais.clear()
},
}
}
/**
* Connexion : seuls les ÉCHECS comptent, 30 par quart d'heure et 200 par jour, par adresse.
* Une salle de vingt personnes derrière la même connexion qui se trompe chacune une fois
* ou deux reste dessous ; une bonne connexion ne consomme rien.
*/
export const LIMITE_ECHECS_QUART = { max: 30, fenetreMs: 15 * 60 * 1000 }
export const LIMITE_ECHECS_JOUR = { max: 200, fenetreMs: 24 * 60 * 60 * 1000 }
/** Création et modification : 60 écritures par dix minutes, par adresse (vingt personnes, trois chacune). */
export const LIMITE_ECRITURES = { max: 60, fenetreMs: 10 * 60 * 1000 }
export const limiteEchecsQuart = creerLimiteur(LIMITE_ECHECS_QUART.max, LIMITE_ECHECS_QUART.fenetreMs)
export const limiteEchecsJour = creerLimiteur(LIMITE_ECHECS_JOUR.max, LIMITE_ECHECS_JOUR.fenetreMs)
export const limiteEcritures = creerLimiteur(LIMITE_ECRITURES.max, LIMITE_ECRITURES.fenetreMs)
// ── Côté requête ───────────────────────────────────────────────────────────────
/** La configuration codev du serveur (Nitro). */
export function configCodev(): ConfigCodev {
// useRuntimeConfig est fourni par Nitro (import automatique) ; les tests passent leur propre config.
const c: any = useRuntimeConfig()
return { motDePasse: c.codevPassword, motDePasseAdmin: c.codevAdminPassword, secret: c.nocodbToken }
}
/**
* L'adresse du visiteur, lue comme les autres routes du site la lisent aujourd'hui.
* À raccorder à la fonction unique du lot SURFACE quand il sera fusionné.
*/
export function adresseCodev(event: H3Event): string {
return getHeader(event, 'x-forwarded-for')?.split(',')[0].trim()
|| event.node.req.socket?.remoteAddress
|| '0.0.0.0'
}
/** LA fonction qui décide : participant, administrateur, ou personne. */
export function roleDuVisiteur(event: H3Event, config: ConfigCodev = configCodev()): RoleCodev | null {
return roleDuTemoin(getCookie(event, NOM_TEMOIN), config)
}
/** Exige un rôle ; 401 sans session valide, 403 si la session n'a pas le droit. */
export function exigerRole(event: H3Event, attendu: RoleCodev, config: ConfigCodev = configCodev()): RoleCodev {
const role = roleDuVisiteur(event, config)
if (!role) throw createError({ statusCode: 401, statusMessage: 'Session requise' })
if (attendu === 'admin' && role !== 'admin') throw createError({ statusCode: 403, statusMessage: 'Accès refusé' })
return role
}
/** Exige un identifiant de fiche valide dans la route ; 400 sinon. */
export function exigerIdFiche(brut: unknown): number {
const id = idFicheCodev(brut)
if (id === null) throw createError({ statusCode: 400, statusMessage: 'Identifiant invalide' })
return id
}
/** Limite les écritures (création, modification) ; 429 au-delà. */
export function limiterEcriture(event: H3Event): void {
if (!limiteEcritures.prendre(adresseCodev(event))) {
throw createError({ statusCode: 429, statusMessage: 'Trop de modifications, réessaie dans quelques minutes' })
}
}
/** Pose le témoin signé et efface l'ancien témoin administrateur. */
export function poserSession(event: H3Event, role: RoleCodev, config: ConfigCodev = configCodev()): void {
const options = {
httpOnly: true,
sameSite: 'lax' as const,
secure: process.env.NODE_ENV === 'production',
maxAge: DUREE_SESSION_S,
path: '/',
}
setCookie(event, NOM_TEMOIN, signerTemoin(role, deriverCle(config)), options)
deleteCookie(event, ANCIEN_TEMOIN_ADMIN, { path: '/' })
}
+1 -2
View File
@@ -15,8 +15,7 @@ import { createHash } from 'crypto'
import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'fs'
import { join } from 'path'
// Réglable pour le banc de routes (un dossier jetable par passage).
const RATELIMIT_DIR = process.env.NAV_RATELIMIT_DIR || '/tmp/nav-ratelimit'
const RATELIMIT_DIR = '/tmp/nav-ratelimit'
type RateLimitFile = {
[action: string]: { count: number; date: string }