sokko-g/services/http.js
Shinuwa 22b397ebfa Document Sokko G's architecture and folders, and move JavaScript file headers to JSDoc @file blocks
Add ARCHITECTURE.md (layers, flows, folder map, glossary), CONTRIBUTING.md
(setup and step-by-step recipes) and a README in each main folder, with an
index of docs/. Convert the 511 JavaScript headers from "// Rôle :" lines to
JSDoc @file blocks, define a three-level header template in website/AGENTS.md
and check the header in tests/file-headers.test.mjs.

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

48 lines
1.7 KiB
JavaScript

/**
* @file Regroupe les petits outils HTTP partagés par les API du serveur Node.
*/
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;
}