Document how server.mjs keeps the site up when an API is misconfigured and reports it on /api/health, the cache and CSP policy, the share API's synchronous reservation, the trust placed in X-Forwarded-For, the hooks main.jsx wires once, and how to run each script. The deploy script header now recalls that CI runs the copy installed on the server. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
248 lines
10 KiB
JavaScript
248 lines
10 KiB
JavaScript
/**
|
|
* @file Serveur Node de production : sert le build (website/dist), applique la politique de cache et les en-têtes
|
|
* de sécurité (CSP), branche les API de Sokko TCG et de l'envoi de toolbox, et répond à `/api/health`.
|
|
*
|
|
* Contexte : serveur HTTP natif, sans framework. Lancé par `npm start` et par le service systemd sokko-g ; en
|
|
* développement, Vite le remplace et branche les mêmes API (vite.config.js).
|
|
* Points d'entrée : `startServer` (lancé quand le fichier est exécuté), `createStaticServer`, `createCardsApi`,
|
|
* `createSharesApi`.
|
|
* Utilisé par : ops/systemd/sokko-g.service, scripts/start-cards-e2e-server.mjs, scripts/measure-public-assets.mjs,
|
|
* les tests du serveur.
|
|
* Dépend de : services/cards/api.js, services/shares/api.js, scripts/load-project-env.mjs.
|
|
* Attention :
|
|
* - Une API mal configurée ne bloque pas le site : elle démarre désactivée, et `/api/health` répond 503 en la
|
|
* nommant, pour que la livraison le voie.
|
|
* - Cache : les fichiers versionnés de `assets/` sont gardés un an (`immutable`) ; HTML et JSON sont
|
|
* revalidés à chaque visite (`no-cache`).
|
|
* - La CSP autorise le script inline d'index.html par son empreinte, recalculée au démarrage.
|
|
* - `HOST` limite l'écoute (réseau privé en production) ; à l'arrêt, la base du TCG est fermée proprement.
|
|
* @see docs/DELIVERY.md
|
|
* @see docs/SERVER.md
|
|
*/
|
|
|
|
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 { createSharesApiHandler } from "./services/shares/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(/<script(?:\s[^>]*)?>([\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=()"
|
|
};
|
|
}
|
|
|
|
// Une API demandée mais tombée en repli au démarrage laisse le site ouvert : la livraison doit pourtant le voir.
|
|
function sendHealth(res, cardsApi, sharesApi) {
|
|
const unavailable = [cardsApi?.unavailable && "cards", sharesApi?.unavailable && "shares"].filter(Boolean);
|
|
const payload = JSON.stringify({ ok: !unavailable.length, unavailable });
|
|
res.writeHead(unavailable.length ? 503 : 200, { "Content-Type": "application/json; charset=utf-8", "Cache-Control": "no-store" });
|
|
res.end(payload);
|
|
}
|
|
|
|
export function createStaticServer({ root = defaultRoot, publicRoot = defaultPublicRoot, cardsApi = null, sharesApi = null } = {}) {
|
|
const headers = securityHeaders(root);
|
|
|
|
async function handleRequest(req, res) {
|
|
for (const [name, value] of Object.entries(headers)) res.setHeader(name, value);
|
|
if (req.method === "GET" && String(req.url || "").split("?")[0] === "/api/health") {
|
|
sendHealth(res, cardsApi, sharesApi);
|
|
return;
|
|
}
|
|
if (sharesApi && await sharesApi(req, res)) return;
|
|
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);
|
|
if (sharesApi?.close) server.once("close", sharesApi.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 Object.assign(createCardsApiHandler({ projectRoot, ...options, enabled: false }), { unavailable: true });
|
|
}
|
|
}
|
|
|
|
// Une configuration d'envoi invalide désactive seulement l'envoi de toolbox.
|
|
export function createSharesApi(options = {}) {
|
|
try {
|
|
return createSharesApiHandler({ projectRoot, ...options });
|
|
} catch (error) {
|
|
console.error("Toolbox sharing is disabled because its configuration is invalid:", error);
|
|
return Object.assign(createSharesApiHandler({ projectRoot, ...options, enabled: false }), { unavailable: true });
|
|
}
|
|
}
|
|
|
|
export function startServer({ cardsApiOptions = {}, sharesApiOptions = {} } = {}) {
|
|
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 sharesApi = createSharesApi(sharesApiOptions);
|
|
const server = createStaticServer({ cardsApi, sharesApi });
|
|
|
|
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());
|