Keep the Node server alive on invalid requests and Cards failures

An invalid URL or Host header rejected inside the async request handler and
ended the process, even with Sokko TCG disabled. Requests now parse against a
fixed base and any unexpected failure answers 500. An invalid Cards setup
disables the game instead of the site, SIGTERM closes the database cleanly,
and the rate limiter forgets past minutes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Shinuwa 2026-11-05 17:52:18 +01:00
parent 5ce35cd7ba
commit d72dd38317
4 changed files with 202 additions and 17 deletions

View file

@ -31,10 +31,19 @@ function redirect(res, location, cookies = []) {
res.end();
}
// Un cookie d'une autre application du domaine peut être mal encodé : il ne doit pas bloquer l'API.
function decodeCookiePart(value) {
try {
return decodeURIComponent(value);
} catch {
return value;
}
}
function parseCookies(req) {
return Object.fromEntries(String(req.headers.cookie || "").split(";").map((entry) => entry.trim()).filter(Boolean).map((entry) => {
const separator = entry.indexOf("=");
return [decodeURIComponent(entry.slice(0, separator)), decodeURIComponent(entry.slice(separator + 1))];
return [decodeCookiePart(entry.slice(0, separator)), decodeCookiePart(entry.slice(separator + 1))];
}));
}
@ -77,22 +86,31 @@ function requestOrigin(req) {
function routeMatch(pathname, pattern) {
const match = pathname.match(pattern);
return match ? match.slice(1).map(decodeURIComponent) : null;
if (!match) return null;
try {
return match.slice(1).map(decodeURIComponent);
} catch {
throw Object.assign(new Error("Adresse de requête invalide."), { status: 400, code: "INVALID_PATH" });
}
}
function createRateLimiter(now) {
// Les compteurs ne valent que pour la minute en cours : ils sont tous oubliés à la suivante pour que la mémoire reste bornée.
export function createRateLimiter(now) {
const buckets = new Map();
return (req, scope, limit = 60) => {
let currentMinute = null;
const limiter = (req, scope, limit = 60) => {
const key = `${String(req.headers["x-forwarded-for"] || req.socket?.remoteAddress || "unknown").split(",")[0]}:${scope}`;
const minute = Math.floor(now() / 60_000);
const current = buckets.get(key);
if (!current || current.minute !== minute) {
buckets.set(key, { minute, count: 1 });
return;
if (minute !== currentMinute) {
buckets.clear();
currentMinute = minute;
}
current.count += 1;
if (current.count > limit) throw Object.assign(new Error("Trop de tentatives. Réessayez dans quelques instants."), { status: 429, code: "RATE_LIMITED" });
const count = (buckets.get(key) || 0) + 1;
buckets.set(key, count);
if (count > limit) throw Object.assign(new Error("Trop de tentatives. Réessayez dans quelques instants."), { status: 429, code: "RATE_LIMITED" });
};
limiter.bucketCount = () => buckets.size;
return limiter;
}
export function createCardsApiHandler({
@ -141,7 +159,13 @@ export function createCardsApiHandler({
}
async function handler(req, res) {
const url = new URL(req.url || "/", requestOrigin(req));
// Seuls le chemin et les paramètres servent ici : ils ne doivent pas dépendre des en-têtes envoyés par le client.
let url;
try {
url = new URL(req.url || "/", "http://localhost");
} catch {
return false;
}
if (!url.pathname.startsWith("/api/cards")) return false;
try {
if (req.method === "GET" && url.pathname === "/api/cards/config") {