#!/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)