// Rôle : sert l'application Vite construite ou les sources publiques avec leur politique de cache. import { createHash } from "node:crypto"; import { createReadStream, existsSync, readFileSync, statSync } from "node:fs"; import { loadProjectEnv } from "./scripts/load-project-env.mjs"; import { createCardsApiHandler } from "./services/cards/api.js"; import { createServer } from "node:http"; import { extname, join, relative, resolve } from "node:path"; import { fileURLToPath } from "node:url"; const modulePath = fileURLToPath(import.meta.url); const projectRoot = resolve(fileURLToPath(new URL(".", import.meta.url))); const websiteRoot = join(projectRoot, "website"); const distRoot = join(websiteRoot, "dist"); const defaultRoot = existsSync(distRoot) ? distRoot : websiteRoot; const defaultPublicRoot = existsSync(distRoot) ? distRoot : join(websiteRoot, "public"); const types = { ".html": "text/html; charset=utf-8", ".css": "text/css; charset=utf-8", ".js": "text/javascript; charset=utf-8", ".json": "application/json; charset=utf-8", ".svg": "image/svg+xml", ".ico": "image/x-icon", ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp" }; function isInsideRoot(parent, file) { const relativePath = relative(parent, file); return Boolean(relativePath) && !relativePath.startsWith("..") && !relativePath.startsWith("/"); } function fileIfReadable(parent, file) { return isInsideRoot(parent, file) && existsSync(file) && statSync(file).isFile() ? file : null; } function resolvePath(url, root, publicRoot) { let requested; try { requested = decodeURIComponent(new URL(url, "http://localhost").pathname); } catch { return null; } const candidate = fileIfReadable(root, resolve(root, `.${requested}`)); if (candidate) return candidate; const publicCandidate = fileIfReadable(publicRoot, resolve(publicRoot, `.${requested}`)); if (publicCandidate) return publicCandidate; return extname(requested) ? null : join(root, "index.html"); } function isVersionedAsset(root, file) { const relativePath = relative(root, file).replaceAll("\\", "/"); const fileName = relativePath.split("/").at(-1) || ""; return relativePath.startsWith("assets/") && /-[a-z0-9_-]{8,}\.[^.]+(?:\.map)?$/i.test(fileName); } function getCacheControl(root, file) { const extension = extname(file); if (extension === ".html") return "no-store"; if (extension === ".json") return "no-cache"; if (isVersionedAsset(root, file)) return "public, max-age=31536000, immutable"; return "no-cache"; } function fileEtag(file) { const { size, mtimeMs } = statSync(file); return `W/"${size.toString(16)}-${Math.floor(mtimeMs).toString(16)}"`; } // Le script inline d'index.html est autorisé par son empreinte, recalculée car un build peut le modifier. function inlineScriptHashes(root) { const indexFile = join(root, "index.html"); if (!existsSync(indexFile)) return []; return [...readFileSync(indexFile, "utf8").matchAll(/]*)?>([\s\S]*?)<\/script>/g)] .filter(([, body]) => body.trim()) .map(([, body]) => `'sha256-${createHash("sha256").update(body).digest("base64")}'`); } function securityHeaders(root) { const contentSecurityPolicy = [ "default-src 'self'", ["script-src 'self'", ...inlineScriptHashes(root)].join(" "), // Le bloc-notes conserve ses couleurs dans des attributs style, relus depuis le stockage. "style-src 'self' 'unsafe-inline'", "img-src 'self' data: blob: https://cdn.discordapp.com", "object-src 'none'", "base-uri 'self'", "form-action 'self'", "frame-ancestors 'none'" ].join("; "); return { "Content-Security-Policy": contentSecurityPolicy, // Sans includeSubDomains : les autres applications du domaine gèrent leur propre transport. "Strict-Transport-Security": "max-age=31536000", "X-Content-Type-Options": "nosniff", "X-Frame-Options": "DENY", "Referrer-Policy": "strict-origin-when-cross-origin", "Permissions-Policy": "camera=(), microphone=(), geolocation=()" }; } export function createStaticServer({ root = defaultRoot, publicRoot = defaultPublicRoot, cardsApi = null } = {}) { const headers = securityHeaders(root); async function handleRequest(req, res) { for (const [name, value] of Object.entries(headers)) res.setHeader(name, value); if (cardsApi && await cardsApi(req, res)) return; const file = resolvePath(req.url || "/", root, publicRoot); if (!file || !existsSync(file)) { res.writeHead(404, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" }); res.end("Not found"); return; } const cacheControl = getCacheControl(root, file); // `no-cache` impose de revalider : sans validateur, chaque visite retéléchargerait le fichier entier. const etag = cacheControl === "no-cache" ? fileEtag(file) : null; if (etag && String(req.headers["if-none-match"] || "").split(",").some((value) => value.trim() === etag)) { res.writeHead(304, { ETag: etag, "Cache-Control": cacheControl }); res.end(); return; } res.writeHead(200, { "Content-Type": types[extname(file)] || "application/octet-stream", "Cache-Control": cacheControl, ...(etag ? { ETag: etag } : {}) }); // Un fichier remplacé pendant une livraison ne doit pas lever d'erreur non gérée. createReadStream(file).on("error", () => res.destroy()).pipe(res); } // Une promesse rejetée arrêterait tout le process : aucune requête ne doit pouvoir le faire. const server = createServer((req, res) => { handleRequest(req, res).catch((error) => { console.error(error); if (res.headersSent) { res.destroy(); return; } res.writeHead(500, { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store" }); res.end("Internal server error"); }); }); if (cardsApi?.close) server.once("close", cardsApi.close); return server; } // Une configuration Sokko TCG invalide désactive le jeu sans priver le site de ses toolboxes et guides. export function createCardsApi(options = {}) { try { return createCardsApiHandler({ projectRoot, ...options }); } catch (error) { console.error("Sokko TCG is disabled because its configuration is invalid:", error); return createCardsApiHandler({ projectRoot, ...options, enabled: false }); } } export function startServer({ cardsApiOptions = {} } = {}) { loadProjectEnv(); const port = Number(process.env.PORT || 5173); // En production, limite l'écoute au réseau privé : seul le proxy doit pouvoir joindre le serveur. const host = process.env.HOST || undefined; const cardsApi = createCardsApi(cardsApiOptions); const server = createStaticServer({ cardsApi }); server.on("error", (error) => { if (error.code === "EADDRINUSE") { console.error(`Port ${port} is already in use. Set PORT to another value.`); process.exit(1); } console.error(error); process.exit(1); }); server.listen(port, host, () => { console.log(`Sokko G server running at http://${host || "localhost"}:${port}`); }); return server; } // Ferme la base à l'arrêt du service pour vider son journal WAL ; les requêtes en cours disposent d'un court délai. function stopOnSignal(server) { const stop = () => { server.close(() => process.exit(0)); server.closeIdleConnections(); setTimeout(() => server.closeAllConnections(), 3000).unref(); }; process.once("SIGTERM", stop); process.once("SIGINT", stop); } if (process.argv[1] && resolve(process.argv[1]) === modulePath) stopOnSignal(startServer());