Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions src/_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -80,6 +80,16 @@ export function setupOutgoing(
}
}

// Derive `host` from `hostname` (+ port) when the target was provided as a
// plain object without `host`. IPv6 literals must be bracketed in URI host
// syntax (RFC 3986 3.2.2), otherwise the `changeOrigin` branch below would
// produce a malformed `Host` header like `undefined:<port>`.
if (outgoing.host === undefined && typeof outgoing.hostname === "string") {
const isIPv6Literal = outgoing.hostname.includes(":") && !outgoing.hostname.startsWith("[");
const bracketedHost = isIPv6Literal ? `[${outgoing.hostname}]` : outgoing.hostname;
outgoing.host = outgoing.port ? `${bracketedHost}:${outgoing.port}` : bracketedHost;
}

outgoing.method = options.method || req.method;
outgoing.headers = { ...req.headers };

Expand Down
34 changes: 34 additions & 0 deletions test/_utils.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -507,6 +507,40 @@ describe("lib/http-proxy/common.js", () => {
);
expect(outgoing.headers!.host).to.eql("mycouch.com:6984");
});

it("should derive host from hostname when target is a plain object without host", () => {
const outgoing = createOutgoing();
common.setupOutgoing(
outgoing,
{
target: {
protocol: "http:",
hostname: "example.com",
port: 8080,
},
changeOrigin: true,
},
stubIncomingMessage({ url: "/" }),
);
expect(outgoing.headers!.host).to.eql("example.com:8080");
});

it("should bracket IPv6 hostname when target is a plain object without host (RFC 3986 §3.2.2)", () => {
const outgoing = createOutgoing();
common.setupOutgoing(
outgoing,
{
target: {
protocol: "http:",
hostname: "::1",
port: 8080,
},
changeOrigin: true,
},
stubIncomingMessage({ url: "/" }),
);
expect(outgoing.headers!.host).to.eql("[::1]:8080");
});
});

it("should pass through https client parameters", () => {
Expand Down
Loading