Repository Public
1// Serveur du Groupe Ka : des fichiers statiques (dist/), rien d'autre. Aucune dépendance.2// PORT (8140) · HOST (0.0.0.0) · GROUPEKA_NOINDEX=1 : préproduction, aucune indexation3// /healthz : état · /api/version : version et chiffres affichés4// La page d'accueil reçoit les chiffres réels lus dans l'API publique de chaque site (server/chiffres.mjs),5// relus toutes les 30 minutes ; si une lecture échoue, la page n'affiche simplement pas de chiffre.6import http from "node:http";7import fs from "node:fs";8import path from "node:path";9import zlib from "node:zlib";10import crypto from "node:crypto";11import { fileURLToPath } from "node:url";12import { lireChiffres, poserChiffres } from "./chiffres.mjs";13import { extrairePiece, piecesPresentes } from "./piece.mjs";1415const ici = path.dirname(fileURLToPath(import.meta.url));16const DIST = path.resolve(ici, "..", "dist");17const PORT = Number(process.env.PORT || 8140);18const HOST = process.env.HOST || "0.0.0.0";19const NOINDEX = process.env.GROUPEKA_NOINDEX === "1";20const VERSION = JSON.parse(fs.readFileSync(path.resolve(ici, "..", "package.json"), "utf8")).version;21const DEBUT = Date.now();2223const TYPES = {24 ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8",25 ".svg": "image/svg+xml", ".png": "image/png", ".ico": "image/x-icon", ".woff2": "font/woff2",26 ".avif": "image/avif", ".webp": "image/webp", ".txt": "text/plain; charset=utf-8", ".json": "application/json; charset=utf-8", ".webmanifest": "application/manifest+json",27};28const COMPRESSIBLE = new Set([".html", ".js", ".css", ".svg", ".txt", ".json", ".webmanifest"]);29const AN = "public, max-age=31536000, immutable";30/** Durée de cache selon le chemin : fichiers à empreinte et polices versionnées pour un an, le reste court. */31function cache(url) {32 if (url.startsWith("/assets/") || (url.startsWith("/fonts/") && url.endsWith(".woff2"))) return AN;33 if (url.endsWith(".html") || url === "/") return "no-cache";34 if (url.startsWith("/vues/") || url.startsWith("/captures/")) return "public, max-age=86400";35 return "public, max-age=3600";36}3738// ── Fichiers en mémoire (le site pèse quelques centaines de ko) ──────────────39const fichiers = new Map();40function charger(dir = DIST, base = "") {41 for (const f of fs.readdirSync(dir, { withFileTypes: true })) {42 const abs = path.join(dir, f.name), url = `${base}/${f.name}`;43 if (f.isDirectory()) charger(abs, url);44 else fichiers.set(url, preparer(fs.readFileSync(abs), path.extname(f.name)));45 }46}47function preparer(corps, ext) {48 const e = { corps, type: TYPES[ext] || "application/octet-stream", etag: `"${crypto.createHash("sha1").update(corps).digest("base64url").slice(0, 20)}"` };49 if (COMPRESSIBLE.has(ext) && corps.length > 600) {50 e.br = zlib.brotliCompressSync(corps, { params: { [zlib.constants.BROTLI_PARAM_QUALITY]: 10 } });51 e.gz = zlib.gzipSync(corps, { level: 9 });52 }53 return e;54}55charger();56const GABARIT = fs.readFileSync(path.join(DIST, "index.html"), "utf8");57// les pages de détail (« la pièce derrière la porte ») : un seul gabarit, une page par adresse58const GABARIT_PIECES = fs.existsSync(path.join(DIST, "piece.html")) ? fs.readFileSync(path.join(DIST, "piece.html"), "utf8") : "";59const PIECES = piecesPresentes(GABARIT_PIECES);60fichiers.delete("/piece.html");6162// ── Page d'accueil : gabarit + chiffres ──────────────────────────────────────63let chiffres = {}, chiffresLe = 0, accueil, csp;64const pieces = new Map();65function page(gabarit) {66 let html = poserChiffres(gabarit, chiffres);67 if (NOINDEX) html = html.replace("<head>", `<head>\n <meta name="robots" content="noindex, nofollow" />`);68 return html;69}70function composer() {71 const html = page(GABARIT);72 accueil = preparer(Buffer.from(html), ".html");73 // seul le petit script de thème est en ligne (le même sur toutes les pages) : on autorise son empreinte, rien d'autre74 const hashes = [...html.matchAll(/<script>([\s\S]*?)<\/script>/g)].map((m) => `'sha256-${crypto.createHash("sha256").update(m[1]).digest("base64")}'`);75 csp = `default-src 'none'; script-src 'self' ${hashes.join(" ")}; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'`;76 for (const slug of PIECES) pieces.set(slug, preparer(Buffer.from(page(extrairePiece(GABARIT_PIECES, slug))), ".html"));77}78const IDS = ["louka", "immoka", "vraiprix", "autoka", "foodka", "fabrika"];79async function rafraichir() {80 try {81 chiffres = await lireChiffres(chiffres);82 chiffresLe = Date.now();83 composer();84 } catch (e) {85 console.error("chiffres :", e?.message || e);86 }87 // complet : relecture dans 30 minutes ; incomplet (site muet, réseau pas encore prêt au démarrage) : dans une minute88 const complet = IDS.every((id) => chiffres[id]);89 setTimeout(rafraichir, complet ? 30 * 60 * 1000 : 60 * 1000).unref();90}91composer();92rafraichir();9394const ROBOTS = NOINDEX ? "User-agent: *\nDisallow: /\n" : "User-agent: *\nAllow: /\nSitemap: https://www.groupe-ka.com/sitemap.xml\n";95const SITEMAP = `<?xml version="1.0" encoding="UTF-8"?>\n<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"><url><loc>https://www.groupe-ka.com/</loc></url>${PIECES.map((s) => `<url><loc>https://www.groupe-ka.com/${s}</loc></url>`).join("")}</urlset>\n`;96const INTROUVABLE = Buffer.from(97 `<!doctype html><html lang="fr-CA"><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><meta name="robots" content="noindex"><title>Page introuvable — Groupe Ka</title><style>body{margin:0;min-height:100vh;display:grid;place-items:center;background:#f4f2ec;color:#1a1b1e;font:16px/1.5 system-ui,sans-serif;text-align:center}@media (prefers-color-scheme:dark){body{background:#131416;color:#efede6}}a{color:inherit}h1{font:500 1.8rem Georgia,serif;margin:0 0 .4rem}</style><main><h1>Cette porte n'existe pas</h1><p><a href="/">Revenir à la rotonde du Groupe Ka</a></p></main></html>`,98);99100function envoyer(req, res, code, e, extra = {}) {101 const h = {102 "content-type": e.type,103 "x-content-type-options": "nosniff",104 "referrer-policy": "strict-origin-when-cross-origin",105 ...(NOINDEX ? { "x-robots-tag": "noindex, nofollow" } : {}),106 ...extra,107 };108 if (e.etag) {109 h.etag = e.etag;110 if (req.headers["if-none-match"] === e.etag) { res.writeHead(304, h); return res.end(); }111 }112 let corps = e.corps;113 const ae = String(req.headers["accept-encoding"] || "");114 if (e.br || e.gz) h.vary = "accept-encoding";115 if (e.br && /\bbr\b/.test(ae)) { corps = e.br; h["content-encoding"] = "br"; }116 else if (e.gz && /\bgzip\b/.test(ae)) { corps = e.gz; h["content-encoding"] = "gzip"; }117 h["content-length"] = corps.length;118 res.writeHead(code, h);119 res.end(req.method === "HEAD" ? undefined : corps);120}121const json = (o) => ({ corps: Buffer.from(JSON.stringify(o)), type: TYPES[".json"] });122123const serveur = http.createServer((req, res) => {124 if (req.method !== "GET" && req.method !== "HEAD") { res.writeHead(405, { allow: "GET, HEAD" }); return res.end(); }125 let url;126 try { url = decodeURIComponent(new URL(req.url, "http://x").pathname); } catch { res.writeHead(400); return res.end(); }127 if (url === "/healthz") return envoyer(req, res, 200, json({ ok: true, name: "Groupe Ka", version: VERSION, uptime_s: Math.round((Date.now() - DEBUT) / 1000) }), { "cache-control": "no-store" });128 if (url === "/api/version")129 return envoyer(req, res, 200, json({ name: "Groupe Ka", version: VERSION, noindex: NOINDEX, contact: "contact@spboucher.ai", chiffres, chiffres_lus_a: chiffresLe ? new Date(chiffresLe).toISOString() : null }), { "cache-control": "no-store" });130 if (url === "/robots.txt") return envoyer(req, res, 200, { corps: Buffer.from(ROBOTS), type: TYPES[".txt"] }, { "cache-control": "public, max-age=3600" });131 if (url === "/sitemap.xml" && !NOINDEX) return envoyer(req, res, 200, { corps: Buffer.from(SITEMAP), type: "application/xml; charset=utf-8" }, { "cache-control": "public, max-age=3600" });132 if (url === "/" || url === "/index.html")133 return envoyer(req, res, 200, accueil, { "cache-control": "no-cache", "content-security-policy": csp, "x-frame-options": "DENY" });134 // une pièce par site : /lou-ka, /immo-ka… (avec une barre finale : redirection vers l'adresse propre)135 const slug = url.replace(/^\/|\/$/g, "");136 if (pieces.has(slug)) {137 if (url.endsWith("/")) { res.writeHead(301, { location: `/${slug}` }); return res.end(); }138 return envoyer(req, res, 200, pieces.get(slug), { "cache-control": "no-cache", "content-security-policy": csp, "x-frame-options": "DENY" });139 }140 const f = fichiers.get(url);141 if (f) return envoyer(req, res, 200, f, { "cache-control": cache(url) });142 envoyer(req, res, 404, { corps: INTROUVABLE, type: TYPES[".html"] }, { "cache-control": "no-store" });143});144serveur.listen(PORT, HOST, () => console.log(`Groupe Ka ${VERSION} : http://${HOST}:${PORT}${NOINDEX ? " (préproduction, noindex)" : ""}`));145for (const s of ["SIGINT", "SIGTERM"]) process.on(s, () => serveur.close(() => process.exit(0)));146