Share uploads now reserve their slot, bytes and per-IP count before the disk check, so simultaneous uploads can no longer exceed the limits. Writes to a share's metadata run one after another, and a revocation can no longer be undone by a pending read count. The TCG page ignores a state reload that started before or during a mutation, the last mutation wins, and returning to the page triggers a single reload. The card cache confirms writes only once the IndexedDB transaction completes and shows only the current player's copy. The administration panel loads on demand, which shrinks the TCG chunk from 311.6 to 191.8 kB. A new /api/health route answers 503 when the cards or shares API failed to start. The deploy script ships the commit's production dependencies with the build, waits up to 30 s for a healthy server instead of trusting systemctl is-active, and restores node_modules on rollback. Both Forgejo workflows check the route on the public site. The updated script applies once reinstalled on the server. Unused helpers, the ignored join role and duplicate button selectors are removed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
227 lines
8.9 KiB
JavaScript
227 lines
8.9 KiB
JavaScript
// 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 { 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());
|