From 29ddd948407322c67aace0336fdc65eed12bad20 Mon Sep 17 00:00:00 2001 From: Pooya Parsa Date: Thu, 4 Jan 2024 20:31:28 +0100 Subject: [PATCH] fix(dev): correctly set `x-forwarded-*` headers resolves #1978 closes #2047 --- src/dev/server.ts | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) diff --git a/src/dev/server.ts b/src/dev/server.ts index 0c1323789d..f892165c75 100644 --- a/src/dev/server.ts +++ b/src/dev/server.ts @@ -1,6 +1,7 @@ import { Worker } from "node:worker_threads"; import { existsSync, accessSync, promises as fsp } from "node:fs"; import { writeFile } from "node:fs/promises"; +import { TLSSocket } from "node:tls"; import { debounce } from "perfect-debounce"; import { App, @@ -193,15 +194,19 @@ export function createDevServer(nitro: Nitro): NitroDevServer { // Main worker proxy const proxy = createProxy(); proxy.proxy.on("proxyReq", (proxyReq, req) => { - const proxyRequestHeaders = proxyReq.getHeaders(); - if (req.socket.remoteAddress && !proxyRequestHeaders["x-forwarded-for"]) { - proxyReq.setHeader("X-Forwarded-For", req.socket.remoteAddress); + // TODO: Use httpxy to set these headers + if (!proxyReq.hasHeader("x-forwarded-for")) { + proxyReq.appendHeader("x-forwarded-for", req.socket.remoteAddress); } - if (req.socket.remotePort && !proxyRequestHeaders["x-forwarded-port"]) { - proxyReq.setHeader("X-Forwarded-Port", req.socket.remotePort); + if (!proxyReq.hasHeader("x-forwarded-port")) { + const localPort = req?.socket?.localPort; + if (localPort) { + proxyReq.setHeader("x-forwarded-port", req.socket.localPort); + } } - if (req.socket.remoteFamily && !proxyRequestHeaders["x-forwarded-proto"]) { - proxyReq.setHeader("X-Forwarded-Proto", req.socket.remoteFamily); + if (!proxyReq.hasHeader("x-forwarded-Proto")) { + const encrypted = (req?.connection as TLSSocket)?.encrypted; + proxyReq.setHeader("x-forwarded-proto", encrypted ? "https" : "http"); } });