sokko-g/services/http.js
Shinuwa d8c94f6834 Give the server, React entry, shared hooks and scripts headers that explain their role and pitfalls
Document how server.mjs keeps the site up when an API is misconfigured and
reports it on /api/health, the cache and CSP policy, the share API's
synchronous reservation, the trust placed in X-Forwarded-For, the hooks main.jsx
wires once, and how to run each script. The deploy script header now recalls
that CI runs the copy installed on the server.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-01 11:00:04 +01:00

55 lines
2.1 KiB
JavaScript

/**
* @file Petits outils HTTP partagés par les API du serveur : lecture d'un booléen d'environnement, réponse JSON,
* erreur avec statut, adresse du client, limite de débit par minute.
*
* Utilisé par : services/cards/api.js, services/shares/api.js.
* Attention : `clientAddress` prend la première adresse de `X-Forwarded-For`. En production, Caddy remplace cet
* en-tête par l'adresse réelle ; sans un proxy qui le fait, un client pourrait la falsifier et contourner les
* limites par adresse.
* @see docs/SERVER.md
*/
export function bool(value, fallback = false) {
if (value == null || value === "") return fallback;
return /^(1|true|yes|on)$/i.test(String(value));
}
export function json(res, status, body, headers = {}) {
const payload = JSON.stringify(body);
res.writeHead(status, {
"Content-Type": "application/json; charset=utf-8",
"Content-Length": Buffer.byteLength(payload),
"Cache-Control": "no-store",
"X-Content-Type-Options": "nosniff",
...headers
});
res.end(payload);
}
export function httpError(status, code, message, extra = {}) {
return Object.assign(new Error(message), { status, code, ...extra });
}
// Caddy remplace X-Forwarded-For par l'adresse réelle du client (voir docs/SERVER.md).
export function clientAddress(req) {
return String(req.headers["x-forwarded-for"] || req.socket?.remoteAddress || "unknown").split(",")[0].trim();
}
// 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();
let currentMinute = null;
const limiter = (req, scope, limit = 60) => {
const key = `${clientAddress(req)}:${scope}`;
const minute = Math.floor(now() / 60_000);
if (minute !== currentMinute) {
buckets.clear();
currentMinute = minute;
}
const count = (buckets.get(key) || 0) + 1;
buckets.set(key, count);
if (count > limit) throw httpError(429, "RATE_LIMITED", "Trop de tentatives. Réessayez dans quelques instants.");
};
limiter.bucketCount = () => buckets.size;
return limiter;
}