Skip to content
Merged
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
4 changes: 3 additions & 1 deletion lib/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -479,6 +479,7 @@ function initAsClient(address, protocols, options) {

const isSecure =
parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:';
const defaultPort = isSecure ? 443 : 80;
const key = crypto.randomBytes(16).toString('base64');
const httpObj = isSecure ? https : http;
const path = parsedUrl.search
Expand All @@ -487,7 +488,8 @@ function initAsClient(address, protocols, options) {
var perMessageDeflate;

options.createConnection = isSecure ? tlsConnect : netConnect;
options.port = parsedUrl.port || (isSecure ? 443 : 80);
options.defaultPort = options.defaultPort || defaultPort;
options.port = parsedUrl.port || defaultPort;
options.host = parsedUrl.hostname.startsWith('[')
? parsedUrl.hostname.slice(1, -1)
: parsedUrl.hostname;
Expand Down
44 changes: 15 additions & 29 deletions test/websocket.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -1840,38 +1840,24 @@ describe('WebSocket', function() {
});
});

it('includes the host header with port number', function(done) {
const agent = new CustomAgent();

agent.addRequest = (req) => {
assert.strictEqual(req._headers.host, 'localhost:1337');
done();
};

const ws = new WebSocket('ws://localhost:1337', { agent });
it('includes the host header with port number', function() {
const ws = new WebSocket('ws://localhost:1337', { lookup() {} });
assert.strictEqual(ws._req._headers.host, 'localhost:1337');
});

it('excludes default ports from host header', function() {
const httpsAgent = new https.Agent();
const httpAgent = new http.Agent();
const values = [];
let ws;

httpsAgent.addRequest = httpAgent.addRequest = (req) => {
values.push(req._headers.host);
};

ws = new WebSocket('wss://localhost:8443', { agent: httpsAgent });
ws = new WebSocket('wss://localhost:443', { agent: httpsAgent });
ws = new WebSocket('ws://localhost:88', { agent: httpAgent });
ws = new WebSocket('ws://localhost:80', { agent: httpAgent });

assert.deepStrictEqual(values, [
'localhost:8443',
'localhost',
'localhost:88',
'localhost'
]);
const options = { lookup() {} };
const variants = [
['wss://localhost:8443', 'localhost:8443'],
['wss://localhost:443', 'localhost'],
['ws://localhost:88', 'localhost:88'],
['ws://localhost:80', 'localhost']
];

for (const [url, host] of variants) {
const ws = new WebSocket(url, options);
assert.strictEqual(ws._req._headers.host, host);
}
});

it("doesn't add the origin header by default", function(done) {
Expand Down