Skip to content

Commit ebea038

Browse files
committedJul 14, 2021
[major] Throw an error if the connection URL is invalid
Make the `WebSocket` constructor throw a `SyntaxError` if the URL contains a fragment identifier or if the URL's protocol is not one of `'ws:'`, `'wss:'`, or `'ws+unix:'`.
1 parent 552b506 commit ebea038

File tree

2 files changed

+35
-6
lines changed

2 files changed

+35
-6
lines changed
 

‎lib/websocket.js

+19-5
Original file line numberDiff line numberDiff line change
@@ -613,18 +613,32 @@ function initAsClient(websocket, address, protocols, options) {
613613
parsedUrl = address;
614614
websocket._url = address.href;
615615
} else {
616-
parsedUrl = new URL(address);
616+
try {
617+
parsedUrl = new URL(address);
618+
} catch (e) {
619+
throw new SyntaxError(`Invalid URL: ${address}`);
620+
}
621+
617622
websocket._url = address;
618623
}
619624

625+
const isSecure = parsedUrl.protocol === 'wss:';
620626
const isUnixSocket = parsedUrl.protocol === 'ws+unix:';
621627

622-
if (!parsedUrl.host && (!isUnixSocket || !parsedUrl.pathname)) {
623-
throw new Error(`Invalid URL: ${websocket.url}`);
628+
if (parsedUrl.protocol !== 'ws:' && !isSecure && !isUnixSocket) {
629+
throw new SyntaxError(
630+
'The URL\'s protocol must be one of "ws:", "wss:", or "ws+unix:"'
631+
);
632+
}
633+
634+
if (isUnixSocket && !parsedUrl.pathname) {
635+
throw new SyntaxError("The URL's pathname is empty");
636+
}
637+
638+
if (parsedUrl.hash) {
639+
throw new SyntaxError('The URL contains a fragment identifier');
624640
}
625641

626-
const isSecure =
627-
parsedUrl.protocol === 'wss:' || parsedUrl.protocol === 'https:';
628642
const defaultPort = isSecure ? 443 : 80;
629643
const key = randomBytes(16).toString('base64');
630644
const get = isSecure ? https.get : http.get;

‎test/websocket.test.js

+16-1
Original file line numberDiff line numberDiff line change
@@ -20,9 +20,24 @@ class CustomAgent extends http.Agent {
2020
describe('WebSocket', () => {
2121
describe('#ctor', () => {
2222
it('throws an error when using an invalid url', () => {
23+
assert.throws(
24+
() => new WebSocket('foo'),
25+
/^SyntaxError: Invalid URL: foo$/
26+
);
27+
28+
assert.throws(
29+
() => new WebSocket('https://echo.websocket.org'),
30+
/^SyntaxError: The URL's protocol must be one of "ws:", "wss:", or "ws\+unix:"$/
31+
);
32+
2333
assert.throws(
2434
() => new WebSocket('ws+unix:'),
25-
/^Error: Invalid URL: ws\+unix:$/
35+
/^SyntaxError: The URL's pathname is empty$/
36+
);
37+
38+
assert.throws(
39+
() => new WebSocket('wss://echo.websocket.org#foo'),
40+
/^SyntaxError: The URL contains a fragment identifier$/
2641
);
2742
});
2843

1 commit comments

Comments
 (1)

abratnap commented on Apr 28, 2022

@abratnap

What if someone running websocket over http/s?

Please sign in to comment.