119 lines
3.7 KiB
JavaScript
119 lines
3.7 KiB
JavaScript
// Petits outils HTTP partagés par les routes du serveur.
|
|
|
|
/** En-têtes de sécurité de toutes les réponses, repris du Caddyfile du lot 1. */
|
|
export const CSP = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; font-src 'self'; connect-src 'self'; worker-src 'self'; manifest-src 'self'; object-src 'none'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'";
|
|
|
|
export const SECURITY_HEADERS = {
|
|
"x-content-type-options": "nosniff",
|
|
"referrer-policy": "no-referrer",
|
|
"content-security-policy": CSP,
|
|
};
|
|
|
|
/** Corps trop gros : le client reçoit 413. */
|
|
export class BodyTooLarge extends Error {}
|
|
|
|
/** Erreur à renvoyer telle quelle au client (code HTTP, corps JSON). */
|
|
export class HttpError extends Error {
|
|
/** @param {number} status @param {string} error @param {string} [description] */
|
|
constructor(status, error, description) {
|
|
super(description ?? error);
|
|
this.status = status;
|
|
this.error = error;
|
|
this.description = description;
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Lit le corps d'une requête, en refusant au-delà de `limit` octets.
|
|
* @param {import("node:http").IncomingMessage} req
|
|
* @param {number} limit
|
|
* @returns {Promise<string>}
|
|
*/
|
|
export function readBody(req, limit) {
|
|
return new Promise((resolve, reject) => {
|
|
const declared = Number(req.headers["content-length"]);
|
|
if (declared > limit) {
|
|
req.resume();
|
|
return reject(new BodyTooLarge());
|
|
}
|
|
/** @type {Buffer[]} */
|
|
const chunks = [];
|
|
let size = 0;
|
|
let failed = false;
|
|
req.on("data", (/** @type {Buffer} */ chunk) => {
|
|
if (failed) return;
|
|
size += chunk.length;
|
|
if (size > limit) {
|
|
failed = true;
|
|
reject(new BodyTooLarge());
|
|
return;
|
|
}
|
|
chunks.push(chunk);
|
|
});
|
|
req.on("end", () => failed || resolve(Buffer.concat(chunks).toString("utf8")));
|
|
req.on("error", reject);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* Lit un corps JSON ; lève une HttpError 400 s'il est illisible.
|
|
* @param {import("node:http").IncomingMessage} req
|
|
* @param {number} limit
|
|
* @returns {Promise<any>}
|
|
*/
|
|
export async function readJson(req, limit) {
|
|
let text;
|
|
try {
|
|
text = await readBody(req, limit);
|
|
} catch (e) {
|
|
if (e instanceof BodyTooLarge) throw new HttpError(413, "payload_too_large", "Requête trop volumineuse.");
|
|
throw e;
|
|
}
|
|
try {
|
|
return JSON.parse(text || "null");
|
|
} catch {
|
|
throw new HttpError(400, "invalid_request", "Corps JSON illisible.");
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Envoie une réponse JSON (ou vide pour 202 et 204), jamais mise en cache.
|
|
* @param {import("node:http").ServerResponse} res
|
|
* @param {number} status
|
|
* @param {unknown} body
|
|
* @param {Record<string, string>} [headers]
|
|
*/
|
|
export function sendJson(res, status, body, headers = {}) {
|
|
const text = body === undefined ? "" : JSON.stringify(body);
|
|
res.writeHead(status, {
|
|
...SECURITY_HEADERS,
|
|
"cache-control": "no-store",
|
|
...(text ? { "content-type": "application/json; charset=utf-8", "content-length": Buffer.byteLength(text) } : {}),
|
|
...headers,
|
|
});
|
|
res.end(text);
|
|
}
|
|
|
|
/**
|
|
* @param {import("node:http").ServerResponse} res
|
|
* @param {number} status
|
|
* @param {string} text
|
|
* @param {Record<string, string>} [headers]
|
|
*/
|
|
export function sendText(res, status, text, headers = {}) {
|
|
res.writeHead(status, {
|
|
...SECURITY_HEADERS,
|
|
"cache-control": "no-store",
|
|
"content-type": "text/plain; charset=utf-8",
|
|
"content-length": Buffer.byteLength(text),
|
|
...headers,
|
|
});
|
|
res.end(text);
|
|
}
|
|
|
|
/** Jeton porteur de l'en-tête Authorization, ou "" s'il n'y en a pas. @param {import("node:http").IncomingMessage} req */
|
|
export function bearer(req) {
|
|
const m = /^Bearer\s+(\S+)\s*$/i.exec(req.headers.authorization ?? "");
|
|
return m ? m[1] : "";
|
|
}
|