- security headers on every response (strict CSP, nosniff, frame DENY, no-referrer, HSTS behind TLS proxy) and no x-powered-by; hero image set through the CSSOM so the CSP needs no inline styles - error handler: 400 without stack trace for malformed URLs/JSON and multer errors, 500 logged in full - image uploads: type detected from the file signature (PNG/JPEG/WebP), not the client MIME type; multer part limits - storage: atomic JSON writes (tmp + rename) with mode 600, dirs 700; refuse to start when groups.json is corrupted instead of recreating admin; initial admin password written to a 600 file instead of the logs - status file read asynchronously in the background and cached, one read at a time with a 3 s timeout, so a hung NFS mount never blocks requests; cleanup refused when the status is stale or empty - launches: 10 min cooldown after a successful start (status lags behind), ssh BatchMode/ConnectTimeout/IdentitiesOnly, remote stdout/stderr kept in the server log instead of the API response Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
105 lines
3.3 KiB
JavaScript
105 lines
3.3 KiB
JavaScript
import fs from "node:fs/promises";
|
|
import { config } from "../config.js";
|
|
|
|
// Dernier contenu valide du fichier de statut. Les routes lisent uniquement ce cache:
|
|
// une lecture bloquee sur le montage NFS ne bloque donc jamais une requete.
|
|
let cachedStatuses = [];
|
|
let lastSuccessAt = 0;
|
|
// Une seule lecture a la fois: si le NFS ne repond plus, on n'empile pas de nouvelles
|
|
// lectures (chacune occuperait un thread du pool libuv, partage avec scrypt).
|
|
let pendingRead = null;
|
|
let refreshTimer = null;
|
|
|
|
async function readStatusFile() {
|
|
try {
|
|
const raw = await fs.readFile(config.statusFile, "utf8");
|
|
const parsed = JSON.parse(raw);
|
|
cachedStatuses = Array.isArray(parsed?.servers) ? parsed.servers : [];
|
|
lastSuccessAt = Date.now();
|
|
} catch (error) {
|
|
if (error.code === "ENOENT") {
|
|
cachedStatuses = [];
|
|
lastSuccessAt = Date.now();
|
|
}
|
|
console.error(`[status] Failed to read status file ${config.statusFile}:`, error.message);
|
|
}
|
|
}
|
|
|
|
// Relit le fichier et attend au plus statusReadTimeoutMs; en cas de depassement, le cache
|
|
// precedent reste utilise et la lecture en cours se terminera plus tard.
|
|
function refreshStatus() {
|
|
if (!pendingRead) {
|
|
pendingRead = readStatusFile().finally(() => {
|
|
pendingRead = null;
|
|
});
|
|
}
|
|
|
|
let timer;
|
|
const timeout = new Promise((resolve) => {
|
|
timer = setTimeout(() => {
|
|
console.error(
|
|
`[status] Reading ${config.statusFile} takes more than ${config.statusReadTimeoutMs} ms, using cached status`
|
|
);
|
|
resolve();
|
|
}, config.statusReadTimeoutMs);
|
|
});
|
|
return Promise.race([pendingRead, timeout]).finally(() => clearTimeout(timer));
|
|
}
|
|
|
|
function startStatusRefresh() {
|
|
if (refreshTimer) return;
|
|
refreshTimer = setInterval(refreshStatus, config.statusRefreshMs);
|
|
refreshTimer.unref();
|
|
}
|
|
|
|
function isStatusFresh(now = Date.now()) {
|
|
return lastSuccessAt > 0 && now - lastSuccessAt <= config.statusMaxAgeMs;
|
|
}
|
|
|
|
function mergeServersWithStatus(servers) {
|
|
return cachedStatuses.map((status) => {
|
|
const server = findConfiguredServer(status, servers);
|
|
const id = status.id || server?.id || createServerId(status);
|
|
|
|
return {
|
|
...(server || {}),
|
|
id,
|
|
game: status.game || server?.game || id,
|
|
address: status.address || server?.address || "",
|
|
port: status.port ?? server?.port ?? null,
|
|
active: Boolean(status.active),
|
|
};
|
|
});
|
|
}
|
|
|
|
function findConfiguredServer(status, servers) {
|
|
return (
|
|
servers.find((server) => status.id && server.id === status.id) ||
|
|
servers.find((server) => sameEndpoint(server, status)) ||
|
|
servers.find((server) => server.game === status.game) ||
|
|
null
|
|
);
|
|
}
|
|
|
|
function sameEndpoint(server, status) {
|
|
if (!server.address || !status.address) return false;
|
|
return normalizeAddress(server.address) === normalizeAddress(status.address);
|
|
}
|
|
|
|
function normalizeAddress(address) {
|
|
return String(address).trim().toLowerCase();
|
|
}
|
|
|
|
function createServerId(status) {
|
|
const base = `${status.game || "server"}-${status.address || ""}-${status.port || ""}`;
|
|
return (
|
|
base
|
|
.toLowerCase()
|
|
.normalize("NFD")
|
|
.replace(/[̀-ͯ]/g, "")
|
|
.replace(/[^a-z0-9]+/g, "-")
|
|
.replace(/^-|-$/g, "") || "server"
|
|
);
|
|
}
|
|
|
|
export { createServerId, isStatusFresh, mergeServersWithStatus, refreshStatus, startStatusRefresh };
|