Node.js http module doesn't receive WS request (using https-proxy-agent)

983 Views Asked by At

The concept is simple, creating a http server that forward websocket request to another port.

Here is the code on my server side:

  http.createServer(onRequest).listen(9999);
  function onRequest(request, response) {
    console.log(request);
    ...
  }

So if the http server receive any request at all it should print out the request in console.

Then on the client side (also a node.js application), the code is:

    var HttpsProxyAgent = require('https-proxy-agent');
    var WebSocket = require('ws');
    ...
    var proxy = `http://${config.proxy.host}:${config.proxy.port}`;
    var options = url.parse(proxy);
    agent = new HttpsProxyAgent(options);
    ws = new WebSocket(target, {
      protocol: 'binary',
      agent: agent
    });

Now, when I use Charles to intercept the request, the client did indeed emit a request, here is the curl form captured by Charles:

curl -H 'Host: target.host.com:8080' -X CONNECT 'https://target.host.com:8080'

the problem seems to be that

  function onRequest(request, response) {
    console.log(request);
    ...
  }

didn't actually receive any -X CONNECT 'https://proxy.host.com:9999' request, or at least it didn't print it out (obviously it didn't work either).

1

There are 1 best solutions below

0
On BEST ANSWER
  var server = http.createServer(onRequest).listen(9999);
  server.on('connect', (req, cltSocket, head) => {
    const srvSocket = net.connect('8080', '127.0.0.1', () => {
      cltSocket.write('HTTP/1.1 200 Connection Established\r\n' +
                      'Proxy-agent: Node.js-Proxy\r\n' +
                      '\r\n');
      srvSocket.write(head);
      srvSocket.pipe(cltSocket);
      cltSocket.pipe(srvSocket);
    });
  });