// Site statique : les mêmes réponses que le Caddyfile du lot 1 (types MIME fixés, // en-têtes de sécurité, revalidation à chaque visite, compression des textes). import fs from "node:fs/promises"; import path from "node:path"; import zlib from "node:zlib"; import { SECURITY_HEADERS, sendText } from "./http.js"; /** * Types MIME fixés ici plutôt que devinés : avec nosniff, un module ES servi * sous un autre type ne se charge pas. * @type {Record} */ export const MIME_TYPES = { ".html": "text/html; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".mjs": "text/javascript; charset=utf-8", ".css": "text/css; charset=utf-8", ".json": "application/json", ".webmanifest": "application/manifest+json", ".md": "text/markdown; charset=utf-8", ".txt": "text/plain; charset=utf-8", ".svg": "image/svg+xml", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".ico": "image/x-icon", ".woff2": "font/woff2", }; /** Types compressés : les textes. Les polices woff2 et les images le sont déjà. */ const COMPRESSIBLE = /^(text\/|application\/json|application\/manifest\+json|image\/svg\+xml)/; /** Comme Caddy : en dessous, la compression ne fait rien gagner. */ const MIN_COMPRESS = 512; /** * Encodage choisi d'après Accept-Encoding : zstd, sinon gzip, sinon aucun. * @param {string|undefined} header * @returns {"zstd"|"gzip"|null} */ export function pickEncoding(header) { /** @type {Map} */ const accepted = new Map(); for (const part of (header ?? "").split(",")) { const [name, ...params] = part.trim().toLowerCase().split(";"); if (!name) continue; const q = params.map((p) => /^\s*q=([0-9.]+)\s*$/.exec(p)).find(Boolean); accepted.set(name, q ? Number(q[1]) : 1); } const ok = (/** @type {string} */ name) => (accepted.get(name) ?? accepted.get("*") ?? 0) > 0; if (ok("zstd")) return "zstd"; if (ok("gzip")) return "gzip"; return null; } /** * @param {string} siteDir dossier du site assemblé (make site) */ export function createStaticHandler(siteDir) { const root = path.resolve(siteDir); /** Versions compressées, gardées en mémoire tant que le fichier ne change pas. */ /** @type {Map} */ const compressed = new Map(); /** * @param {import("node:http").IncomingMessage} req * @param {import("node:http").ServerResponse} res * @param {string} pathname chemin de l'URL, non décodé */ return async function serveStatic(req, res, pathname) { if (req.method !== "GET" && req.method !== "HEAD") return sendText(res, 405, "Méthode non permise.", { allow: "GET, HEAD" }); let rel; try { rel = decodeURIComponent(pathname); } catch { return sendText(res, 400, "Adresse invalide."); } // Ni remontée, ni fichier caché, ni caractère nul. if (rel.includes("\0") || rel.split("/").some((seg) => seg === ".." || seg.startsWith("."))) return notFound(res); let file = path.join(root, rel); if (file !== root && !file.startsWith(root + path.sep)) return notFound(res); let stat = await fs.stat(file).catch(() => null); if (stat?.isDirectory()) { if (!rel.endsWith("/")) { const index = await fs.stat(path.join(file, "index.html")).catch(() => null); if (!index) return notFound(res); res.writeHead(308, { ...SECURITY_HEADERS, location: pathname + "/", "cache-control": "no-cache" }); return res.end(); } file = path.join(file, "index.html"); stat = await fs.stat(file).catch(() => null); } if (!stat?.isFile()) return notFound(res); const type = MIME_TYPES[path.extname(file).toLowerCase()] ?? "application/octet-stream"; const encoding = COMPRESSIBLE.test(type) && stat.size >= MIN_COMPRESS ? pickEncoding(req.headers["accept-encoding"]) : null; const baseTag = `${Math.floor(stat.mtimeMs).toString(36)}${stat.size.toString(36)}`; const etag = `"${baseTag}${encoding ? "-" + encoding : ""}"`; /** @type {Record} */ const headers = { ...SECURITY_HEADERS, // Les noms de fichiers ne changent pas d'une version à l'autre : le // navigateur revalide chaque fichier (ETag). sw.js porte la version. "cache-control": "no-cache", "content-type": type, etag, "last-modified": stat.mtime.toUTCString(), }; if (COMPRESSIBLE.test(type)) headers.vary = "Accept-Encoding"; const inm = req.headers["if-none-match"]; if (inm && inm.split(",").some((t) => t.trim().replace(/^W\//, "") === etag)) { res.writeHead(304, headers); return res.end(); } let body = await fs.readFile(file); if (encoding) { const key = `${file}|${baseTag}|${encoding}`; let packed = compressed.get(key); if (!packed) { packed = encoding === "zstd" ? zlib.zstdCompressSync(body) : zlib.gzipSync(body); if (compressed.size > 2000) compressed.clear(); compressed.set(key, packed); } body = packed; headers["content-encoding"] = encoding; } headers["content-length"] = body.length; res.writeHead(200, headers); res.end(req.method === "HEAD" ? undefined : body); }; } /** @param {import("node:http").ServerResponse} res */ function notFound(res) { res.writeHead(404, { ...SECURITY_HEADERS, "cache-control": "no-cache", "content-type": "text/plain; charset=utf-8" }); res.end("Introuvable."); }