Skip to content

Commit

Permalink
[fix] Use the defaultPort option (#1510)
Browse files Browse the repository at this point in the history
Prevent the default port from being added to the `Host` header when no
`Agent` is used.

Fixes #1505
  • Loading branch information
lpinca committed Feb 16, 2019
1 parent 8b5422e commit 92b0a65
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 30 deletions.
4 changes: 3 additions & 1 deletion lib/websocket.js
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
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

0 comments on commit 92b0a65

Please sign in to comment.