nestjs / nest

A progressive Node.js framework for building efficient, scalable, and enterprise-grade server-side applications with TypeScript/JavaScript 🚀
https://nestjs.com
MIT License
67.73k stars 7.63k forks source link

Socket Gateway Should handle Preflight Requests sent from https socket.io client #3539

Closed AhmedMahmoud2012 closed 4 years ago

AhmedMahmoud2012 commented 4 years ago

Socket Gateway in nestjs uses socket.io and socket.io is built on engine.io and If you check the code of server.js line 168

if ('GET' !== req.method) return fn(Server.errors.BAD_HANDSHAKE_METHOD, false);

So engine.io always expects requests with method 'GET' but that isn't the case all the time because if you open socket.io-client with https you will have preflight requests becuase https adds additional headers to the first http request to establish the socket.

when the browser sends preflight request? the answer is , if the request isn't "simple request"

Criteria to be considered a simple request :

If the request uses methods

Allowed headers

If the Content-Type header has a value

As we know socket.io sends first http request to establish the connection and that request is "simple request" that only If you are use HTTP not HTTPS

But If you are using HTTPS , HTTPS used to add additional request headers so the first request to establish the socket won't be "simple request" so the broswer will send preflight request with method "OPTIONS" but as we mentioned engine.io expects 'GET' according to this line if ('GET' !== req.method) return fn(Server.errors.BAD_HANDSHAKE_METHOD, false);

so you will get BAD_HANDSHAKE_METHOD response because of that you will find options to handle that :

const io = require('socket.io')(3000, { handlePreflightRequest: function (req, res) { var headers = { 'Access-Control-Allow-Headers': 'Content-Type, Authorization, x-token', 'Access-Control-Allow-Origin': 'http://localhost:3001', 'Access-Control-Allow-Credentials': true }; res.writeHead(200, headers); res.end(); } });

So the issue is : we need to be able to add handlePreflightRequest to @WebSocketGateway() meta because engine.io is always waiting 'GET'

To solve this issue I use nesjs Adaptor wsAdaptor

Greetings from Berlin <3

kamilmysliwiec commented 4 years ago

Thanks for reporting. This will be fixed once we merge this PR https://github.com/nestjs/nest/pull/3543

lock[bot] commented 4 years ago

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.