Skip to content

Commit

Permalink
fix(dev): correctly set x-forwarded-* headers
Browse files Browse the repository at this point in the history
resolves #1978
closes #2047
  • Loading branch information
pi0 committed Jan 4, 2024
1 parent 1e8910d commit 29ddd94
Showing 1 changed file with 12 additions and 7 deletions.
19 changes: 12 additions & 7 deletions src/dev/server.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand Down Expand Up @@ -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");
}
});

Expand Down

0 comments on commit 29ddd94

Please sign in to comment.