From 5449e3f70acac28e7bfbcf984930d89a24f6fdaf Mon Sep 17 00:00:00 2001 From: Claude Date: Tue, 20 Jan 2026 19:48:28 +0000 Subject: [PATCH] fix(metrics): handle malformed URLs gracefully in metrics endpoint Wrap URL parsing in try/catch to prevent server crashes from malformed requests (invalid percent-encoding, problematic Host headers, etc.). Returns 400 Bad Request instead of crashing the process. --- src/Utils/prometheus-metrics.ts | 18 ++++++++++++++++-- 1 file changed, 16 insertions(+), 2 deletions(-) diff --git a/src/Utils/prometheus-metrics.ts b/src/Utils/prometheus-metrics.ts index b9d6893c..619edebc 100644 --- a/src/Utils/prometheus-metrics.ts +++ b/src/Utils/prometheus-metrics.ts @@ -1222,8 +1222,22 @@ export class MetricsServer { this.server = createServer(async (req: IncomingMessage, res: ServerResponse) => { // Parse URL to handle querystrings and trailing slashes - const parsedUrl = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`) - const pathname = parsedUrl.pathname.replace(/\/+$/, '') || '/' // Normalize trailing slashes + // Wrapped in try/catch to handle malformed URLs gracefully + let pathname: string + try { + const parsedUrl = new URL(req.url || '/', `http://${req.headers.host || 'localhost'}`) + pathname = parsedUrl.pathname.replace(/\/+$/, '') || '/' + } catch { + // Malformed URL - return 400 Bad Request + res.writeHead(400, { 'Content-Type': 'application/json' }) + res.end(JSON.stringify({ + error: 'Bad Request', + message: 'Malformed URL', + timestamp: new Date().toISOString() + })) + return + } + const configPath = this.config.path.replace(/\/+$/, '') || '/' if (pathname === configPath && req.method === 'GET') {