diff --git a/system-metrics.js b/system-metrics.js index bc2eaac..6c42e63 100644 --- a/system-metrics.js +++ b/system-metrics.js @@ -470,7 +470,13 @@ const server = http.createServer(async (req, res) => { // Solo lectura: cualquier otro método se rechaza. if (req.method !== "GET") { res.writeHead(405); return res.end(JSON.stringify({ error: "Solo GET" })); } - const url = new URL(req.url, `http://${req.headers.host || "localhost"}`); + // La base es fija: solo hace falta para separar la ruta de los parámetros. + // Hasta la v2.1.0 se montaba con la cabecera Host de la petición, fuera de + // todo try: un Host mal formado («a b», «[») hacía saltar new URL y tumbaba + // el servicio entero (systemd lo levantaba a los 5 s). + let url; + try { url = new URL(req.url, "http://localhost"); } + catch { res.writeHead(400); return res.end(JSON.stringify({ error: "Bad request" })); } const handler = routes[url.pathname]; if (!handler) { diff --git a/tests/test50.js b/tests/test50.js new file mode 100644 index 0000000..7814296 --- /dev/null +++ b/tests/test50.js @@ -0,0 +1,50 @@ +// v2.1.1 — S1 de la auditoría del 10-nov-2026: el servicio de métricas se +// caía con una cabecera Host mal formada. La dirección de cada petición se +// montaba con `new URL(req.url, "http://" + Host)` fuera de todo try, y el +// manejador es asíncrono: la excepción quedaba sin recoger y Node cerraba el +// proceso. Ahora la base es fija y una ruta imposible se contesta con 400. +// +// La prueba carga system-metrics.js con un `http` de mentira: no abre ningún +// puerto, no ejecuta ningún comando y no toca Bitcoin Core. +// +// Uso: node tests/test50.js +const fs = require("fs"); +const path = require("path"); +const src = fs.readFileSync(path.join(__dirname, "..", "system-metrics.js"), "utf8").replace(/^#!.*\n/, ""); + +let manejador = null; +const httpFalso = { createServer: h => { manejador = h; return { listen() {} }; }, request() { throw new Error("la prueba no debe llamar a Bitcoin Core"); } }; +const requireFalso = m => m === "http" ? httpFalso : m === "child_process" ? { exec() { throw new Error("la prueba no debe ejecutar comandos"); } } : require(m); +new Function("require", "process", "console", src)(requireFalso, { env: {}, platform: process.platform, uptime: () => 0 }, { log() {}, error() {}, warn() {} }); + +let pass = 0, fail = 0; +const ok = (n, c, x) => { console.log(` ${c ? "✓" : "✗"} ${n}`); if (!c && x !== undefined) console.log(" " + JSON.stringify(x)); c ? pass++ : fail++; }; + +const pedir = async (url, host, method = "GET") => { + const r = { estado: null, cuerpo: null, error: null }; + const res = { setHeader() {}, writeHead(c) { r.estado = c; }, end(b) { r.cuerpo = b; } }; + try { await manejador({ url, method, headers: host === undefined ? {} : { host } }, res); } + catch (e) { r.error = e.message; } + return r; +}; + +(async () => { + console.log("=== S1. Una cabecera Host mal formada no tumba el servicio ===\n"); + ok("el servicio se carga sin abrir puerto", typeof manejador === "function"); + for (const host of ["a b", "[", "exa mple.com:99999", "::::", "", "%%%"]) { + const r = await pedir("/no-existe", host); + ok(`Host «${host}» → se contesta (404), sin excepción`, r.error === null && r.estado === 404, r); + } + const sin = await pedir("/no-existe", undefined); + ok("sin cabecera Host → 404, sin excepción", sin.error === null && sin.estado === 404, sin); + const normal = await pedir("/no-existe?x=1", "127.0.0.1:4082"); + ok("Host normal → 404 para una ruta que no existe (como antes)", normal.error === null && normal.estado === 404, normal); + const post = await pedir("/system/info", "a b", "POST"); + ok("otro método → 405 (como antes)", post.error === null && post.estado === 405, post); + const mala = await pedir("//[", "127.0.0.1:4082"); + ok("ruta imposible de leer → 400, sin excepción", mala.error === null && mala.estado === 400, mala); + ok("la base de la URL ya no depende de la petición", !/new URL\([^)]*headers/.test(src) && /new URL\(req\.url, "http:\/\/localhost"\)/.test(src)); + + console.log(`\n${pass} ✓ · ${fail} ✗`); + process.exit(fail ? 1 : 0); +})();