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

@ -15,12 +15,12 @@
"preview": "vite preview",
"lists:index": "node scripts/generate-list-indexes.mjs",
"lint": "eslint .",
"lint:cards": "eslint server.mjs vite.config.js playwright.cards.config.js scripts/backup-nebula-cards.mjs scripts/start-cards-e2e-server.mjs services/cards tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs e2e/nebula-cards.spec.js e2e/style-layouts.spec.js website/src/features/cards website/src/components/Shell.jsx website/src/main.jsx website/src/router/RouteContent.jsx",
"lint:cards": "eslint server.mjs vite.config.js playwright.cards.config.js scripts/backup-nebula-cards.mjs scripts/start-cards-e2e-server.mjs services/cards tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs tests/server-robustness.test.mjs e2e/nebula-cards.spec.js e2e/style-layouts.spec.js website/src/features/cards website/src/components/Shell.jsx website/src/main.jsx website/src/router/RouteContent.jsx",
"check": "node --check server.mjs && node --check vite.config.js && npm run lint && npm run lists:index && npm test && npm run build",
"check:cards": "node --check server.mjs && node --check vite.config.js && npm run lint:cards && npm run test:cards && npm run test:e2e:cards",
"check:full": "npm run check && E2E_PORT=4181 npm run test:e2e && npm run test:e2e:production && npm run test:e2e:cards",
"test": "node --test",
"test:cards": "node --test tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs && node --test --test-name-pattern=\"site content json is complete\" tests/data-validation.test.mjs",
"test:cards": "node --test tests/nebula-cards.test.mjs tests/nebula-cards-api.test.mjs tests/server-robustness.test.mjs && node --test --test-name-pattern=\"site content json is complete\" tests/data-validation.test.mjs",
"test:e2e": "playwright test",
"test:e2e:production": "npm run build && playwright test --config playwright.production.config.js",
"test:e2e:cards": "playwright test --config playwright.cards.config.js",

View file

@ -67,7 +67,7 @@ function getCacheControl(root, file) {
}
export function createStaticServer({ root = defaultRoot, publicRoot = defaultPublicRoot, cardsApi = null } = {}) {
const server = createServer(async (req, res) => {
async function handleRequest(req, res) {
if (cardsApi && await cardsApi(req, res)) return;
const file = resolvePath(req.url || "/", root, publicRoot);
if (!file || !existsSync(file)) {
@ -83,16 +83,40 @@ export function createStaticServer({ root = defaultRoot, publicRoot = defaultPub
"Content-Type": types[extname(file)] || "application/octet-stream",
"Cache-Control": getCacheControl(root, file)
});
createReadStream(file).pipe(res);
// 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);
const cardsApi = createCardsApiHandler({ projectRoot, ...cardsApiOptions });
const cardsApi = createCardsApi(cardsApiOptions);
const server = createStaticServer({ cardsApi });
server.on("error", (error) => {
@ -111,4 +135,15 @@ export function startServer({ cardsApiOptions = {} } = {}) {
return server;
}
if (process.argv[1] && resolve(process.argv[1]) === modulePath) startServer();
// 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());

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") {

View file

@ -0,0 +1,126 @@
// Rôle : vérifie qu'aucune requête ni erreur de configuration Sokko TCG ne peut interrompre le serveur Node.
import assert from "node:assert/strict";
import { spawn } from "node:child_process";
import { existsSync } from "node:fs";
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import { connect } from "node:net";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
import { test } from "node:test";
import { createCardsApi, createStaticServer } from "../server.mjs";
import { createCardsApiHandler, createRateLimiter } from "../services/cards/api.js";
const projectRoot = resolve(".");
const serverFile = join(projectRoot, "server.mjs");
// `fetch` normalise les URL et les en-têtes : seule une requête brute reproduit ce qu'un client hostile peut envoyer.
function rawRequest(port, { target = "/", host = "localhost", extraHeaders = "" }) {
return new Promise((resolvePromise, reject) => {
const socket = connect(port, "127.0.0.1", () => socket.write(`GET ${target} HTTP/1.1\r\nHost: ${host}\r\n${extraHeaders}Connection: close\r\n\r\n`));
let response = "";
socket.on("data", (chunk) => { response += chunk; });
socket.on("close", () => resolvePromise(response.split("\r\n")[0]));
socket.on("error", reject);
});
}
async function listen(t, cardsApi) {
const root = await mkdtemp(join(tmpdir(), "sokko-server-robustness-"));
await writeFile(join(root, "index.html"), "<main>Sokko G</main>");
const server = createStaticServer({ root, publicRoot: root, cardsApi });
await new Promise((resolvePromise) => server.listen(0, "127.0.0.1", resolvePromise));
t.after(async () => {
await new Promise((resolvePromise) => server.close(resolvePromise));
await rm(root, { recursive: true, force: true });
});
return server.address().port;
}
const hostileRequests = [
["an empty authority in the path", { target: "//" }],
["an invalid Host header", { host: "[" }],
["an invalid X-Forwarded-Proto header", { extraHeaders: "X-Forwarded-Proto: a b\r\n" }]
];
for (const enabled of [false, true]) {
for (const [label, request] of hostileRequests) {
test(`${label} leaves the server responding when Sokko TCG is ${enabled ? "enabled" : "disabled"}`, async (t) => {
const cardsApi = createCardsApiHandler({ projectRoot, enabled, devAuth: false, databasePath: ":memory:", env: { NODE_ENV: "test" } });
const port = await listen(t, cardsApi);
const status = await rawRequest(port, request);
assert.match(status, /^HTTP\/1\.1 [2-5]\d\d /);
assert.match(await rawRequest(port, {}), /^HTTP\/1\.1 200 /);
});
}
}
test("an unexpected API failure answers 500 instead of ending the process", async (t) => {
const failingApi = async () => { throw new Error("expected test failure"); };
const originalError = console.error;
console.error = () => {};
t.after(() => { console.error = originalError; });
const port = await listen(t, failingApi);
assert.match(await rawRequest(port, {}), /^HTTP\/1\.1 500 /);
assert.match(await rawRequest(port, {}), /^HTTP\/1\.1 500 /);
});
test("a malformed API path answers 400 and an undecodable foreign cookie is ignored", async (t) => {
const cardsApi = createCardsApiHandler({ projectRoot, enabled: true, devAuth: false, databasePath: ":memory:", env: { NODE_ENV: "test" } });
const port = await listen(t, cardsApi);
const session = cardsApi.service.createSession(cardsApi.service.upsertPlayer({ discordId: "cookie", displayName: "Cookie" }).id);
const cookieHeader = `Cookie: foreign=100%; sokkog_cards_session=${session.token}\r\n`;
assert.match(await rawRequest(port, { target: "/api/cards/session", extraHeaders: cookieHeader }), /^HTTP\/1\.1 200 /);
assert.match(await rawRequest(port, { target: "/api/cards/admin/campaigns/%E0%A4%A", extraHeaders: cookieHeader }), /^HTTP\/1\.1 400 /);
});
test("a Sokko TCG configuration failure disables the game and keeps the site running", async (t) => {
const directory = await mkdtemp(join(tmpdir(), "sokko-server-config-"));
t.after(() => rm(directory, { recursive: true, force: true }));
// Un fichier à la place du dossier parent : la base ne peut pas être créée, comme un dossier non inscriptible.
await writeFile(join(directory, "not-a-directory"), "");
const logged = [];
const originalError = console.error;
console.error = (...values) => logged.push(values);
t.after(() => { console.error = originalError; });
const cardsApi = createCardsApi({ enabled: true, devAuth: false, databasePath: join(directory, "not-a-directory", "cards.sqlite"), env: { NODE_ENV: "test" } });
const port = await listen(t, cardsApi);
assert.equal(logged.length, 1);
assert.match(await rawRequest(port, {}), /^HTTP\/1\.1 200 /);
const config = await fetch(`http://127.0.0.1:${port}/api/cards/config`).then((response) => response.json());
assert.equal(config.enabled, false);
});
test("SIGTERM closes the database cleanly so no write-ahead log stays behind", async (t) => {
const directory = await mkdtemp(join(tmpdir(), "sokko-server-stop-"));
t.after(() => rm(directory, { recursive: true, force: true }));
const databasePath = join(directory, "cards.sqlite");
// Le dossier courant isole le test d'un éventuel .env du projet.
const child = spawn(process.execPath, ["--no-warnings", serverFile], {
cwd: directory,
env: { PATH: process.env.PATH, NODE_ENV: "test", PORT: "0", CARDS_ENABLED: "true", CARDS_DEV_AUTH: "false", CARDS_DB_PATH: databasePath },
stdio: ["ignore", "pipe", "pipe"]
});
t.after(() => child.kill("SIGKILL"));
await new Promise((resolvePromise, reject) => {
child.stdout.once("data", resolvePromise);
child.once("exit", (code) => reject(new Error(`Server exited early with code ${code}.`)));
});
assert.equal(existsSync(`${databasePath}-wal`), true);
const exit = new Promise((resolvePromise) => child.once("exit", (code, signal) => resolvePromise({ code, signal })));
child.kill("SIGTERM");
assert.deepEqual(await exit, { code: 0, signal: null });
assert.equal(existsSync(`${databasePath}-wal`), false);
});
test("the rate limiter forgets past minutes instead of growing without bound", () => {
let current = 0;
const limiter = createRateLimiter(() => current);
const request = (address) => ({ headers: { "x-forwarded-for": address }, socket: {} });
for (let index = 0; index < 100; index += 1) limiter(request(`10.0.0.${index}`), "api");
assert.equal(limiter.bucketCount(), 100);
current = 60_000;
limiter(request("10.0.0.1"), "api");
assert.equal(limiter.bucketCount(), 1);
for (let index = 1; index < 60; index += 1) limiter(request("10.0.0.1"), "api");
assert.throws(() => limiter(request("10.0.0.1"), "api"), /Trop de tentatives/);
});