Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
ff22377619 | ||
|
|
f40fcd8747 | ||
|
|
de2af750c8 |
@@ -23,7 +23,8 @@ ssh vps
|
||||
mkdir -p /opt/aep-worker
|
||||
exit
|
||||
# depuis le poste de dev, après avoir buildé/vérifié la branche :
|
||||
scp -r worker/enrich.js worker/package.json worker/fixtures vps:/opt/aep-worker/
|
||||
scp -r worker/enrich.js worker/lib worker/package.json worker/fixtures vps:/opt/aep-worker/
|
||||
# worker/lib est requis : enrich.js importe ./lib/messageNtfy.js (lot 15a)
|
||||
ssh vps "cd /opt/aep-worker && npm install --omit=dev"
|
||||
```
|
||||
|
||||
|
||||
@@ -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"
|
||||
},
|
||||
|
||||
@@ -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())
|
||||
}
|
||||
@@ -65,7 +65,9 @@ for (const c of interdits) verifier(`« ${c} » absent de la liste publique`, !C
|
||||
verifier('la garde CHAMPS_JAMAIS_PUBLICS couvre les huit champs du brief', interdits.every((c) => CHAMPS_JAMAIS_PUBLICS.includes(c)))
|
||||
verifier('aucun champ de la garde dans la liste', CHAMPS_JAMAIS_PUBLICS.every((c) => !CHAMPS_PUBLICS_FICHE.includes(c)))
|
||||
for (const c of ['moderation_status', 'projet_adresse', 'CreatedAt', 'submission_type', 'type_principal', 'projet_lien', 'status', 'categorie', 'type_plateforme']) {
|
||||
verifier(`« ${c} » (lu par aucune page) hors de la liste`, !CHAMPS_PUBLICS_FICHE.includes(c))
|
||||
// Aucun n'est lu par une page depuis ces routes ; CreatedAt seulement en dernier repli du sitemap
|
||||
// (utils/seo.ts, après UpdatedAt, toujours rempli) : non rendu par choix.
|
||||
verifier(`« ${c} » hors de la liste`, !CHAMPS_PUBLICS_FICHE.includes(c))
|
||||
}
|
||||
verifier('pas de doublon dans la liste', new Set(CHAMPS_PUBLICS_FICHE).size === CHAMPS_PUBLICS_FICHE.length)
|
||||
// Ce que FicheDetail et la page de la fiche affichent doit rester dans la liste (rien ne casse à l'écran)
|
||||
@@ -130,6 +132,19 @@ console.log('\n4. Ligne approuvée : champs publics seulement')
|
||||
verifier('colonne inconnue → non rendue (liste fermée par défaut)', !('nouvelle_colonne_privee' in r) && !('telephone' in r))
|
||||
}
|
||||
|
||||
{
|
||||
// url : http(s) seulement (FicheDetail en fait un lien cliquable)
|
||||
const urlDe = async (url) => (await lireFichePublique('7', base(ligne({ url })).charger))
|
||||
for (const u of ['javascript:alert(1)', 'JavaScript:alert(1)', ' javascript:alert(1)', 'mailto:essai@exemple.invalid', 'data:text/html,x', 'ftp://exemple.invalid', 'exemple.invalid', '', 42]) {
|
||||
const r = await urlDe(u)
|
||||
verifier(`url ${JSON.stringify(u)} → champ absent, fiche rendue`, !!r && !('url' in r) && r.nom === 'Atelier d essai')
|
||||
}
|
||||
verifier('url https → rendue', (await urlDe('https://exemple.invalid/a')).url === 'https://exemple.invalid/a')
|
||||
verifier('url http → rendue', (await urlDe('http://exemple.invalid')).url === 'http://exemple.invalid')
|
||||
verifier('url null → null (pas de lien)', (await urlDe(null)).url === null)
|
||||
verifier('liste de la carte : url javascript: absente aussi', !('url' in fichesPubliques([ligne({ url: 'javascript:alert(1)' })])[0]))
|
||||
}
|
||||
|
||||
// ── 5. La liste de la carte (/api/organisations) ───────────────────────────
|
||||
console.log('\n5. Liste de la carte')
|
||||
{
|
||||
@@ -148,7 +163,7 @@ const lire = (p) => readFileSync(join(racine, p), 'utf-8')
|
||||
for (const p of ['server/api/fiche/[id].get.ts', 'server/routes/api/organisations/[id].get.ts']) {
|
||||
const s = lire(p)
|
||||
verifier(`${p} : lit la fiche par lireFichePublique`, /lireFichePublique\(getRouterParam\(event, 'id'\)/.test(s))
|
||||
verifier(`${p} : ne rend jamais la ligne brute`, !/return record/.test(s) && !/return data\s*$/m.test(s) && /return fiche\n\}\)/.test(s))
|
||||
verifier(`${p} : ne rend jamais la ligne brute`, !/return record/.test(s) && !/return data\s*$/m.test(s) && /return fiche\r?\n\}\)/.test(s))
|
||||
verifier(`${p} : le filtre NocoDB ne prend que le numéro validé`, /where=\(Id,eq,\$\{id\}\)/.test(s) && /async \(id\) =>/.test(s))
|
||||
verifier(`${p} : une seule réponse d'erreur, 404`, (s.match(/createError/g) ?? []).length === 1 && /statusCode: 404/.test(s))
|
||||
}
|
||||
@@ -159,5 +174,101 @@ for (const p of ['server/api/fiche/[id].get.ts', 'server/routes/api/organisation
|
||||
verifier('organisations.get.ts : filtre approved conservé côté base', /where=\(moderation_status,eq,approved\)/.test(s))
|
||||
}
|
||||
|
||||
// ── 7. Ce que le public écrit et relit hors des fiches (checkpoint du 21/11) ──
|
||||
console.log('\n7. Proposer une fiche, un avis ; relire commentaires et avis')
|
||||
const {
|
||||
ligneOrganisationProposee, ligneAvisPropose, reponseInsertion, commentairesPublics, avisPublics,
|
||||
CHAMPS_PUBLICS_COMMENTAIRE, CHAMPS_PUBLICS_AVIS,
|
||||
} = await jiti.import(join(racine, 'utils', 'contributionsPubliques.ts'))
|
||||
|
||||
const corpsPage = { nom: 'Atelier d essai', type_org: 'association', description: 'Une description d essai.', lien: 'https://exemple.invalid', tags: 'formation, essai', status: 'pending' }
|
||||
{
|
||||
const r = ligneOrganisationProposee(corpsPage)
|
||||
verifier('corps de pages/ajouter.vue accepté', r.ok === true)
|
||||
verifier('… ligne pending, ai_processed false', r.ok && r.ligne.moderation_status === 'pending' && r.ligne.ai_processed === false && r.ligne.status === 'pending')
|
||||
verifier('… exactement les champs de la page + statuts serveur', r.ok && Object.keys(r.ligne).sort().join(',') === 'ai_processed,description,lien,moderation_status,nom,status,tags,type_org')
|
||||
}
|
||||
{
|
||||
const r = ligneOrganisationProposee({
|
||||
...corpsPage, moderation_status: 'approved', ai_processed: true, status: 'approved', Id: 1, moderator_note: 'x',
|
||||
submitted_at: '2020-01-01', submitted_by_email: COURRIEL, colonne_inconnue: 'x', latitude: 1, prioritaire: true,
|
||||
})
|
||||
verifier('moderation_status « approved » du client → ligne pending', r.ok && r.ligne.moderation_status === 'pending' && r.ligne.status === 'pending' && r.ligne.ai_processed === false)
|
||||
for (const k of ['Id', 'moderator_note', 'submitted_at', 'submitted_by_email', 'colonne_inconnue', 'latitude', 'prioritaire']) {
|
||||
verifier(`clé « ${k} » du client ignorée`, r.ok && !(k in r.ligne))
|
||||
}
|
||||
}
|
||||
{
|
||||
const lien = (v) => ligneOrganisationProposee({ ...corpsPage, lien: v })
|
||||
verifier('lien vide → null', lien('').ok && lien('').ligne.lien === null)
|
||||
verifier('lien null → null', lien(null).ok && lien(null).ligne.lien === null)
|
||||
verifier('sans lien ni tags → null', (() => { const r = ligneOrganisationProposee({ nom: 'Atelier', type_org: 'media', description: 'x' }); return r.ok && r.ligne.lien === null && r.ligne.tags === null })())
|
||||
const refus = [
|
||||
['nom de 151 caractères', { nom: 'a'.repeat(151) }],
|
||||
['nom de 2 caractères', { nom: 'ab' }],
|
||||
['nom de 3 espaces + 2 lettres', { nom: ' ab ' }],
|
||||
['nom nombre', { nom: 12345 }],
|
||||
['nom tableau', { nom: ['Atelier'] }],
|
||||
['type_org hors du <select>', { type_org: 'entreprise' }],
|
||||
['type_org vide', { type_org: '' }],
|
||||
['description vide', { description: ' ' }],
|
||||
['description de 2001 caractères', { description: 'a'.repeat(2001) }],
|
||||
['description objet', { description: { texte: 'x' } }],
|
||||
['lien javascript:', { lien: 'javascript:alert(1)' }],
|
||||
['lien sans protocole', { lien: 'exemple.invalid' }],
|
||||
['lien de 501 caractères', { lien: 'https://exemple.invalid/' + 'a'.repeat(477) }],
|
||||
['tags de 201 caractères', { tags: 'a'.repeat(201) }],
|
||||
['tags nombre', { tags: 3 }],
|
||||
]
|
||||
for (const [nom, sur] of refus) verifier(`${nom} → refusé`, ligneOrganisationProposee({ ...corpsPage, ...sur }).ok === false)
|
||||
verifier('nom de 150 caractères → accepté (borne)', ligneOrganisationProposee({ ...corpsPage, nom: 'a'.repeat(150) }).ok === true)
|
||||
verifier('description de 2000 caractères → acceptée (borne)', ligneOrganisationProposee({ ...corpsPage, description: 'a'.repeat(2000) }).ok === true)
|
||||
for (const c of [null, undefined, 'texte', 42, []]) verifier(`corps ${JSON.stringify(c) ?? 'undefined'} → refusé`, ligneOrganisationProposee(c).ok === false)
|
||||
}
|
||||
{
|
||||
const corpsAvis = { organisation_id: 12, auteur: 'Prénom', texte: 'Un avis d essai.', status: 'approved', published: true, Id: 3 }
|
||||
const r = ligneAvisPropose(corpsAvis)
|
||||
verifier('avis avec status « approved » du client → pending', r.ok && r.ligne.status === 'pending')
|
||||
verifier('… clés inconnues ignorées', r.ok && Object.keys(r.ligne).sort().join(',') === 'auteur,organisation_id,status,texte')
|
||||
for (const [nom, sur] of [['organisation_id chaîne', { organisation_id: '12' }], ['organisation_id négatif', { organisation_id: -1 }],
|
||||
['organisation_id flottant', { organisation_id: 1.5 }], ['auteur de 101 caractères', { auteur: 'a'.repeat(101) }],
|
||||
['texte vide', { texte: ' ' }], ['texte de 2001 caractères', { texte: 'a'.repeat(2001) }]]) {
|
||||
verifier(`avis : ${nom} → refusé`, ligneAvisPropose({ ...corpsAvis, ...sur }).ok === false)
|
||||
}
|
||||
}
|
||||
verifier('réponse d’insertion réduite au numéro', JSON.stringify(reponseInsertion({ Id: 5, nom: 'x', moderation_status: 'pending' })) === '{"Id":5}')
|
||||
verifier('réponse d’insertion sans numéro entier → {}', JSON.stringify(reponseInsertion({ Id: '5' })) === '{}' && JSON.stringify(reponseInsertion(null)) === '{}')
|
||||
{
|
||||
const lignes = [
|
||||
{ Id: 1, orga_id: 7, contenu: 'Publié.', auteur_pseudo: 'Pseudo', auteur_email: COURRIEL, published: true, safe_check: 'safe', safe_reason: null, submitted_at: '2026-11-01T10:00:00.000Z' },
|
||||
{ Id: 2, orga_id: 7, contenu: 'En attente.', auteur_email: COURRIEL, published: false, safe_check: 'flagged', safe_reason: 'raison d essai' },
|
||||
{ Id: 3, orga_id: 8, contenu: 'Autre fiche.', published: true },
|
||||
null,
|
||||
]
|
||||
const l = commentairesPublics(lignes, 7)
|
||||
verifier('commentaire avec courriel → courriel non rendu', l.length === 1 && !JSON.stringify(l).includes(COURRIEL))
|
||||
verifier('commentaire : ni safe_check ni safe_reason ni published', l.every((c) => !('safe_check' in c) && !('safe_reason' in c) && !('published' in c)))
|
||||
verifier('commentaire non publié ou d’une autre fiche → absent', l[0].Id === 1)
|
||||
verifier('commentaire : champs lus par CommentSection seulement', l.every((c) => Object.keys(c).every((k) => CHAMPS_PUBLICS_COMMENTAIRE.includes(k))))
|
||||
verifier('auteur_email jamais dans les champs publics d’un commentaire', !CHAMPS_PUBLICS_COMMENTAIRE.includes('auteur_email'))
|
||||
}
|
||||
{
|
||||
const l = avisPublics([
|
||||
{ Id: 1, organisation_id: 7, auteur: 'Prénom d essai', texte: 'Avis approuvé.', status: 'approved' },
|
||||
{ Id: 2, organisation_id: 7, auteur: 'Prénom d essai', texte: 'Avis en attente.', status: 'pending' },
|
||||
], 7)
|
||||
verifier('avis : approuvés seulement, sans prénom ni statut', l.length === 1 && !('auteur' in l[0]) && !('status' in l[0]) && Object.keys(l[0]).every((k) => CHAMPS_PUBLICS_AVIS.includes(k)))
|
||||
}
|
||||
{
|
||||
const post = lire('server/routes/api/organisations.post.ts')
|
||||
verifier('organisations.post.ts : limite de débit de /api/submit', /checkRateLimit\(ip, 'submit', 3\)/.test(post))
|
||||
verifier('organisations.post.ts : n’envoie que r.ligne, ne rend que reponseInsertion', /body: JSON\.stringify\(r\.ligne\)/.test(post) && /return reponseInsertion\(data\)/.test(post) && !/JSON\.stringify\(body\)/.test(post))
|
||||
const avis = lire('server/routes/api/avis.post.ts')
|
||||
verifier('avis.post.ts : limite de débit, r.ligne, reponseInsertion', /checkRateLimit\(ip, 'avis', 5\)/.test(avis) && /JSON\.stringify\(r\.ligne\)/.test(avis) && /return reponseInsertion\(data\)/.test(avis))
|
||||
verifier('comment/[orgId].get.ts : passe par commentairesPublics et idFicheValide', /commentairesPublics\(data\?\.list, orgId\)/.test(lire('server/api/comment/[orgId].get.ts')) && /idFicheValide\(getRouterParam/.test(lire('server/api/comment/[orgId].get.ts')))
|
||||
verifier('avis/[orgId].get.ts : passe par avisPublics et idFicheValide', /avisPublics\(data\?\.list, orgId\)/.test(lire('server/routes/api/avis/[orgId].get.ts')) && /idFicheValide\(getRouterParam/.test(lire('server/routes/api/avis/[orgId].get.ts')))
|
||||
verifier('comment/index.post.ts : le statut publié vient du filtre, pas du client', /published,\r?\n/.test(lire('server/api/comment/index.post.ts')) && !/body\.published|body\.safe_check|body\.status/.test(lire('server/api/comment/index.post.ts')))
|
||||
}
|
||||
|
||||
console.log(`\n${ok} sur ${ok + ko}`)
|
||||
if (ko) process.exit(1)
|
||||
|
||||
@@ -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)
|
||||
@@ -2,12 +2,17 @@
|
||||
* GET /api/comment/[orgId]
|
||||
* Retourne les commentaires publiés (published=true) pour une fiche.
|
||||
* Triés par submitted_at ASC (chronologique).
|
||||
* Lot 15a : numéro strict (utils/fichePublique.ts), lignes publiées seulement, champs lus par
|
||||
* CommentSection seulement (utils/contributionsPubliques.ts) : jamais auteur_email ni safe_*.
|
||||
*/
|
||||
import { idFicheValide } from '../../../utils/fichePublique'
|
||||
import { commentairesPublics } from '../../../utils/contributionsPubliques'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const config = useRuntimeConfig()
|
||||
const orgId = getRouterParam(event, 'orgId')
|
||||
const orgId = idFicheValide(getRouterParam(event, 'orgId'))
|
||||
|
||||
if (!orgId || isNaN(Number(orgId))) {
|
||||
if (orgId === null) {
|
||||
throw createError({ statusCode: 400, message: 'Identifiant invalide' })
|
||||
}
|
||||
|
||||
@@ -18,5 +23,5 @@ export default defineEventHandler(async (event) => {
|
||||
headers: { 'xc-token': config.nocodbToken },
|
||||
}).catch(() => ({ list: [] }))
|
||||
|
||||
return { list: data?.list ?? [] }
|
||||
return { list: commentairesPublics(data?.list, orgId) }
|
||||
})
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
@@ -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}`,
|
||||
|
||||
@@ -1,16 +1,37 @@
|
||||
/**
|
||||
* POST /api/avis — l'avis joint à « Proposer une fiche » (pages/ajouter.vue).
|
||||
* Lot 15a (checkpoint du 21/11) : le client fixait le statut de l'avis (`status`) et pouvait
|
||||
* donc le publier lui-même. Désormais : limite de débit, champs contrôlés
|
||||
* (utils/contributionsPubliques.ts), `status: 'pending'` imposé, réponse réduite au numéro.
|
||||
*/
|
||||
import { checkRateLimit } from '~/server/utils/rateLimit'
|
||||
import { ligneAvisPropose, reponseInsertion } from '../../../utils/contributionsPubliques'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const config = useRuntimeConfig()
|
||||
const body = await readBody(event)
|
||||
const url = `${config.nocodbUrl}/api/v2/tables/${config.avisTableId}/records`
|
||||
|
||||
const ip =
|
||||
getHeader(event, 'x-forwarded-for')?.split(',')[0].trim() ||
|
||||
event.node.req.socket?.remoteAddress ||
|
||||
'0.0.0.0'
|
||||
if (!(await checkRateLimit(ip, 'avis', 5))) {
|
||||
throw createError({ statusCode: 429, statusMessage: 'Trop d\'avis. Réessaie demain.' })
|
||||
}
|
||||
|
||||
const r = ligneAvisPropose(await readBody(event))
|
||||
if (!r.ok) {
|
||||
throw createError({ statusCode: 422, statusMessage: 'Validation échouée', data: r.erreurs })
|
||||
}
|
||||
|
||||
const url = `${config.nocodbUrl}/api/v2/tables/${config.avisTableId}/records`
|
||||
const data = await $fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'xc-token': config.nocodbToken,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
body: JSON.stringify(r.ligne),
|
||||
})
|
||||
|
||||
return data
|
||||
return reponseInsertion(data)
|
||||
})
|
||||
|
||||
@@ -1,13 +1,25 @@
|
||||
/**
|
||||
* GET /api/avis/[orgId] — avis approuvés d'une fiche.
|
||||
* Lot 15a : numéro vérifié avant la base (il entrait tel quel dans le filtre), lignes
|
||||
* approuvées seulement, champs publics seulement (utils/contributionsPubliques.ts) :
|
||||
* jamais le prénom ni un champ de modération. Aucun composant ne l'appelle au 21/11.
|
||||
*/
|
||||
import { idFicheValide } from '../../../../utils/fichePublique'
|
||||
import { avisPublics } from '../../../../utils/contributionsPubliques'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const config = useRuntimeConfig()
|
||||
const orgId = getRouterParam(event, 'orgId')
|
||||
const orgId = idFicheValide(getRouterParam(event, 'orgId'))
|
||||
if (orgId === null) {
|
||||
throw createError({ statusCode: 404, message: 'Organisation non trouvée' })
|
||||
}
|
||||
const url = `${config.nocodbUrl}/api/v2/tables/${config.avisTableId}/records?where=(organisation_id,eq,${orgId})~and(status,eq,approved)`
|
||||
|
||||
const data = await $fetch(url, {
|
||||
const data: any = await $fetch(url, {
|
||||
headers: {
|
||||
'xc-token': config.nocodbToken,
|
||||
},
|
||||
})
|
||||
|
||||
return data
|
||||
return { list: avisPublics(data?.list, orgId) }
|
||||
})
|
||||
|
||||
@@ -1,16 +1,41 @@
|
||||
/**
|
||||
* POST /api/organisations — « Proposer une fiche » (pages/ajouter.vue).
|
||||
*
|
||||
* Lot 15a (checkpoint du 21/11) : la route postait le corps brut dans la table avec le jeton
|
||||
* du serveur ; n'importe qui pouvait créer une fiche `approved`. Désormais :
|
||||
* - limite de débit de /api/submit (même compteur, 3 par IP et par jour) ;
|
||||
* - seuls les champs que la page envoie, contrôlés (utils/contributionsPubliques.ts) ;
|
||||
* - `moderation_status: 'pending'`, `ai_processed: false` imposés ; toute autre clé ignorée ;
|
||||
* - le client ne reçoit que le numéro de la ligne créée (ce que la page lit).
|
||||
*/
|
||||
import { checkRateLimit } from '~/server/utils/rateLimit'
|
||||
import { ligneOrganisationProposee, reponseInsertion } from '../../../utils/contributionsPubliques'
|
||||
|
||||
export default defineEventHandler(async (event) => {
|
||||
const config = useRuntimeConfig()
|
||||
const body = await readBody(event)
|
||||
const url = `${config.nocodbUrl}/api/v2/tables/${config.orgTableId}/records`
|
||||
|
||||
const ip =
|
||||
getHeader(event, 'x-forwarded-for')?.split(',')[0].trim() ||
|
||||
event.node.req.socket?.remoteAddress ||
|
||||
'0.0.0.0'
|
||||
if (!(await checkRateLimit(ip, 'submit', 3))) {
|
||||
throw createError({ statusCode: 429, statusMessage: 'Trop de soumissions. Réessaie demain.' })
|
||||
}
|
||||
|
||||
const r = ligneOrganisationProposee(await readBody(event))
|
||||
if (!r.ok) {
|
||||
throw createError({ statusCode: 422, statusMessage: 'Validation échouée', data: r.erreurs })
|
||||
}
|
||||
|
||||
const url = `${config.nocodbUrl}/api/v2/tables/${config.orgTableId}/records`
|
||||
const data = await $fetch(url, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'xc-token': config.nocodbToken,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(body),
|
||||
body: JSON.stringify(r.ligne),
|
||||
})
|
||||
|
||||
return data
|
||||
return reponseInsertion(data)
|
||||
})
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
/**
|
||||
* Ce que le public peut écrire, et ce qu'on lui relit, hors des fiches (lot 15a, checkpoint du 21/11/2026).
|
||||
*
|
||||
* - `POST /api/organisations` (pages/ajouter.vue) : seuls les champs que la page envoie, contrôlés ;
|
||||
* la ligne part toujours `pending`, jamais approuvée par le client.
|
||||
* - `POST /api/avis` (pages/ajouter.vue) : idem, statut forcé `pending`.
|
||||
* - `GET /api/comment/[orgId]` et `GET /api/avis/[orgId]` : lignes publiées seulement, champs affichés seulement.
|
||||
*
|
||||
* Fonctions pures, sans réseau : testées par scripts/test-fiche-publique.mjs.
|
||||
*/
|
||||
import { z } from 'zod'
|
||||
|
||||
// ── Proposer une organisation (pages/ajouter.vue) ─────────────────────────
|
||||
|
||||
/** Les options du <select> « Type d'organisation » de pages/ajouter.vue. */
|
||||
export const TYPES_ORG_AJOUTER = ['association', 'syndicat', 'institution', 'reseau', 'collectif', 'ecole', 'media'] as const
|
||||
|
||||
const lienHttp = z.string().trim().max(500, 'Maximum 500 caractères')
|
||||
.refine((v) => { try { const u = new URL(v); return u.protocol === 'http:' || u.protocol === 'https:' } catch { return false } }, 'URL invalide')
|
||||
|
||||
/** Corps accepté. `.strip()` (défaut zod) : toute autre clé du client est ignorée. */
|
||||
export const OrganisationProposeeSchema = z.object({
|
||||
// Bornes de /api/submit (SubmitSchema.nom)
|
||||
nom: z.string().trim().min(3, 'Minimum 3 caractères').max(150, 'Maximum 150 caractères'),
|
||||
type_org: z.enum(TYPES_ORG_AJOUTER),
|
||||
// Absent de /api/submit ; la page ne borne pas : 2 000 caractères
|
||||
description: z.string().trim().min(1, 'Champ requis').max(2000, 'Maximum 2000 caractères'),
|
||||
lien: z.union([z.literal(''), z.null(), lienHttp]).optional().transform((v) => v || null),
|
||||
tags: z.union([z.null(), z.string().trim().max(200, 'Maximum 200 caractères')]).optional().transform((v) => v || null),
|
||||
})
|
||||
|
||||
/** La ligne à insérer : champs contrôlés + statut imposé par le serveur. */
|
||||
export function ligneOrganisationProposee(corps: unknown):
|
||||
{ ok: true, ligne: Record<string, unknown> } | { ok: false, erreurs: Record<string, string[] | undefined> } {
|
||||
const r = OrganisationProposeeSchema.safeParse(corps)
|
||||
if (!r.success) return { ok: false, erreurs: r.error.flatten().fieldErrors }
|
||||
return {
|
||||
ok: true,
|
||||
ligne: { ...r.data, status: 'pending', moderation_status: 'pending', ai_processed: false },
|
||||
}
|
||||
}
|
||||
|
||||
// ── Proposer un avis (pages/ajouter.vue, après l'organisation) ────────────
|
||||
|
||||
export const AvisProposeSchema = z.object({
|
||||
organisation_id: z.number().int().positive().max(999999999),
|
||||
// « Ton prénom » : 100 caractères (comme localisation_ville dans /api/submit)
|
||||
auteur: z.string().trim().min(1, 'Champ requis').max(100, 'Maximum 100 caractères'),
|
||||
texte: z.string().trim().min(1, 'Champ requis').max(2000, 'Maximum 2000 caractères'),
|
||||
})
|
||||
|
||||
export function ligneAvisPropose(corps: unknown):
|
||||
{ ok: true, ligne: Record<string, unknown> } | { ok: false, erreurs: Record<string, string[] | undefined> } {
|
||||
const r = AvisProposeSchema.safeParse(corps)
|
||||
if (!r.success) return { ok: false, erreurs: r.error.flatten().fieldErrors }
|
||||
return { ok: true, ligne: { ...r.data, status: 'pending' } }
|
||||
}
|
||||
|
||||
/** Ce que la page lit de la réponse d'insertion : le numéro, rien d'autre. */
|
||||
export function reponseInsertion(data: unknown): { Id?: number } {
|
||||
const id = (data as { Id?: unknown } | null)?.Id
|
||||
return Number.isInteger(id) ? { Id: id as number } : {}
|
||||
}
|
||||
|
||||
// ── Relire les commentaires et les avis ───────────────────────────────────
|
||||
|
||||
/** Champs d'un commentaire lus par components/CommentSection.vue. */
|
||||
export const CHAMPS_PUBLICS_COMMENTAIRE = ['Id', 'orga_id', 'auteur_pseudo', 'contenu', 'submitted_at'] as const
|
||||
|
||||
/** Champs d'un avis : aucun composant n'affiche les avis au 21/11 ; le texte seulement (pas le prénom). */
|
||||
export const CHAMPS_PUBLICS_AVIS = ['Id', 'organisation_id', 'texte'] as const
|
||||
|
||||
function projeter(ligne: Record<string, unknown>, champs: readonly string[]) {
|
||||
const out: Record<string, unknown> = {}
|
||||
for (const k of champs) if (Object.prototype.hasOwnProperty.call(ligne, k)) out[k] = ligne[k]
|
||||
return out
|
||||
}
|
||||
|
||||
const objet = (l: unknown): l is Record<string, unknown> => !!l && typeof l === 'object'
|
||||
|
||||
/** Commentaires publiés (`published === true`) d'une fiche, réduits à leurs champs affichés. */
|
||||
export function commentairesPublics(lignes: unknown, orgaId: number) {
|
||||
return Array.isArray(lignes)
|
||||
? lignes.filter((l) => objet(l) && l.published === true && Number(l.orga_id) === orgaId).map((l) => projeter(l, CHAMPS_PUBLICS_COMMENTAIRE))
|
||||
: []
|
||||
}
|
||||
|
||||
/** Avis approuvés d'une fiche, réduits à leurs champs publics. */
|
||||
export function avisPublics(lignes: unknown, orgaId: number) {
|
||||
return Array.isArray(lignes)
|
||||
? lignes.filter((l) => objet(l) && l.status === 'approved' && Number(l.organisation_id) === orgaId).map((l) => projeter(l, CHAMPS_PUBLICS_AVIS))
|
||||
: []
|
||||
}
|
||||
+21
-2
@@ -67,10 +67,29 @@ export function estFichePublique(ligne: unknown): ligne is Record<string, unknow
|
||||
return !!ligne && typeof ligne === 'object' && (ligne as Record<string, unknown>).moderation_status === 'approved'
|
||||
}
|
||||
|
||||
/** La ligne réduite aux champs publics (les champs absents restent absents). */
|
||||
/** Vrai si la valeur est un lien http: ou https: (FicheDetail le rend cliquable). */
|
||||
export function estLienHttp(v: unknown): v is string {
|
||||
if (typeof v !== 'string') return false
|
||||
try {
|
||||
const u = new URL(v.trim())
|
||||
return u.protocol === 'http:' || u.protocol === 'https:'
|
||||
} catch {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* La ligne réduite aux champs publics (les champs absents restent absents).
|
||||
* `url` ne sort que s'il est en http(s) : le formulaire détaillé accepte `javascript:` ou `mailto:`
|
||||
* (z.string().url()) et FicheDetail en fait un lien cliquable. `null` reste `null` (pas de lien).
|
||||
*/
|
||||
export function projeterFiche(ligne: Record<string, unknown>): Partial<Record<ChampPublicFiche, unknown>> {
|
||||
const out: Record<string, unknown> = {}
|
||||
for (const k of CHAMPS_PUBLICS_FICHE) if (Object.prototype.hasOwnProperty.call(ligne, k)) out[k] = ligne[k]
|
||||
for (const k of CHAMPS_PUBLICS_FICHE) {
|
||||
if (!Object.prototype.hasOwnProperty.call(ligne, k)) continue
|
||||
if (k === 'url' && ligne.url != null && !estLienHttp(ligne.url)) continue
|
||||
out[k] = ligne[k]
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user