diff --git a/lib/Server.js b/lib/Server.js index 6e208128f6..2aaf372a55 100644 --- a/lib/Server.js +++ b/lib/Server.js @@ -3121,6 +3121,10 @@ class Server { } // always allow localhost host, for convenience + if (value === "localhost" || value.endsWith(".localhost")) { + return true; + } + // allow if value is in allowedHosts if (Array.isArray(allowedHosts) && allowedHosts.length > 0) { for (let hostIdx = 0; hostIdx < allowedHosts.length; hostIdx++) { @@ -3210,14 +3214,10 @@ class Server { // an IPv6-address in URLs, // these are removed from the hostname in url.parse(), // so we have the pure IPv6-address in hostname. - // For convenience, always allow localhost (hostname === 'localhost') - // and its subdomains (hostname.endsWith(".localhost")). // allow hostname of listening address (hostname === this.options.host) const isValidHostname = ipaddr.IPv4.isValid(hostname) || ipaddr.IPv6.isValid(hostname) || - hostname === "localhost" || - hostname.endsWith(".localhost") || hostname === this.options.host; if (isValidHostname) { diff --git a/test/server/same-origin.test.js b/test/server/same-origin.test.js new file mode 100644 index 0000000000..ef4403d89a --- /dev/null +++ b/test/server/same-origin.test.js @@ -0,0 +1,41 @@ +"use strict"; + +const webpack = require("webpack"); +const Server = require("../../lib/Server"); +const config = require("../fixtures/simple-config/webpack.config"); + +describe("isSameOrigin", () => { + let server; + + beforeEach(async () => { + const compiler = webpack(config); + server = new Server({}, compiler); + }); + + it("should return true for localhost", () => { + const headers = { + host: "localhost:8080", + origin: "http://localhost:8080", + }; + + expect(server.isSameOrigin(headers)).toBe(true); + }); + + it("should return true for localhost subdomains", () => { + const headers = { + host: "localhost:8080", + origin: "http://subdomain.localhost:8080", + }; + + expect(server.isSameOrigin(headers)).toBe(true); + }); + + it("should return false for cross-origin requests", () => { + const headers = { + origin: "http://example.com", + host: "attacker.com", + }; + + expect(server.isSameOrigin(headers)).toBe(false); + }); +});