theturtle32 / WebSocket-Node

A WebSocket Implementation for Node.JS (Draft -08 through the final RFC 6455)
Apache License 2.0
3.75k stars 604 forks source link

Error 500 when acceptedProtocol not match #293

Closed ccamensuli closed 6 years ago

ccamensuli commented 7 years ago

failed: Error during WebSocket handshake: Unexpected response code: 500

The method WebSocketRequest.accept in WebSocketRequest .js

Lot of reason code don' t respect protocol ?

if (this.requestedProtocols.indexOf(acceptedProtocol) === -1) {
  this.reject(500);
  throw new Error('Specified protocol was not requested by the client.');
}
ibc commented 6 years ago

Can you please describe again your issue?

ccamensuli commented 6 years ago

Example :

var exampleSocket = new WebSocket("ws://www.example.com/socketserver", "protocolOne");

If we call method WebSocketRequest.accept(acceptedProtocol, allowedOrigin, cookies) with a bad acceptedProtocol (not "protocolOne" )

The browser catch : failed: Error during WebSocket handshake: Unexpected response code: 500

In https://github.com/theturtle32/WebSocket-Node/blob/master/lib/WebSocketRequest.js :287

if (this.requestedProtocols.indexOf(acceptedProtocol) === -1) {
  this.reject(500);
  throw new Error('Specified protocol was not requested by the client.');
}

In WebSocketRequest.js Lot of reason code don' t respect protocol ?

I don't know when http error codes (<=500) are allowed ( during handshake , before swith protocol ...) I looked "http error code" in the RFC 6455 and I found this

https://tools.ietf.org/html/rfc6455#section-4.2.2

https://tools.ietf.org/html/rfc6455#section-7.4

ibc commented 6 years ago

In the server side you are responsible of properly matching the WebSocket sub-protocol. This has been discussed in other issues (I think).

theturtle32 commented 6 years ago

This is replying with an HTTP 500 error (Internal Server Error) instead of proceeding with the websocket protocol upgrade (HTTP 101 Switching Protocols). And the reason for this is that your own bad code chose to accept the connection with the wrong protocol. That's your coding error, and it is, therefore, an Internal Server Error and the websocket connection cannot be established.

theturtle32 commented 6 years ago

Further clarification.. this is not replying with an invalid websocket close code. It is replying with an HTTP status code while we are still speaking HTTP, before the protocol has been switched to WebSocket.