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>
163 lines
8.3 KiB
JavaScript
163 lines
8.3 KiB
JavaScript
// 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, startServer } 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);
|
|
// La livraison s'appuie sur cette route pour refuser une version dont le jeu n'a pas démarré.
|
|
const health = await fetch(`http://127.0.0.1:${port}/api/health`);
|
|
assert.equal(health.status, 503);
|
|
assert.deepEqual(await health.json(), { ok: false, unavailable: ["cards"] });
|
|
});
|
|
|
|
test("the health route answers when every requested API started, including a deliberately disabled one", async (t) => {
|
|
const port = await listen(t, createCardsApi({ enabled: false, env: { NODE_ENV: "test" } }));
|
|
const health = await fetch(`http://127.0.0.1:${port}/api/health`);
|
|
assert.equal(health.status, 200);
|
|
assert.equal(health.headers.get("cache-control"), "no-store");
|
|
assert.deepEqual(await health.json(), { ok: true, unavailable: [] });
|
|
});
|
|
|
|
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/);
|
|
});
|
|
|
|
test("the server only listens on the HOST address when it is configured", async (t) => {
|
|
const originalEnv = { HOST: process.env.HOST, PORT: process.env.PORT };
|
|
const originalLog = console.log;
|
|
console.log = () => {};
|
|
t.after(() => {
|
|
console.log = originalLog;
|
|
for (const [name, value] of Object.entries(originalEnv)) {
|
|
if (value === undefined) delete process.env[name];
|
|
else process.env[name] = value;
|
|
}
|
|
});
|
|
const listenOn = async (host) => {
|
|
if (host) process.env.HOST = host;
|
|
else delete process.env.HOST;
|
|
process.env.PORT = "0";
|
|
const server = startServer({ cardsApiOptions: { enabled: false } });
|
|
await new Promise((resolvePromise) => server.once("listening", resolvePromise));
|
|
const { address } = server.address();
|
|
await new Promise((resolvePromise) => server.close(resolvePromise));
|
|
return address;
|
|
};
|
|
assert.equal(await listenOn("127.0.0.1"), "127.0.0.1");
|
|
assert.equal(await listenOn(""), "::");
|
|
});
|