Create a HTTPS Proxy for arbitrary external urls

476 Views Asked by At

I want to create a simple proxy for requests to arbitrary websites with Node.js (http-node-proxy) (and TypeScript for my case). I know that several questions exist on this difficult topic, but none of them helped me so far. I tried:

import axios from 'axios';
import http from 'http';
import httpProxy from 'http-proxy';
import url from 'url';

async function mainHTTP() {
  // create the proxy
  const proxy = httpProxy.createProxy({});
  const server = http.createServer(function(request, response) {
    console.log([request.url, response.statusCode]);
    const requestURL = new url.URL(request.url!);
    const target = `${requestURL.protocol}//${requestURL.host}`;
    proxy.web(request, response, {target: target});
  });
  server.listen(8080);

  // make an example request
  const response = await axios.request({
    'url': 'http://www.example.org',
    'proxy': {host: 'localhost', port: 8080},
  });
  console.log(response);
}
mainHTTP();

And this works fine! But only for HTTP requests. So I tried the same thing "translated" to HTTPS:

// ...
import fs from 'fs';
import https from 'https';

async function mainHTTPs() {
  // create the proxy
  const proxy = httpProxy.createProxy({});
  const ssl = { // keys tested, they work in other situations
    'key': fs.readFileSync('key.pem'),
    'cert': fs.readFileSync('cert.pem'),
  }
  const server = https.createServer(ssl, function(request, response) {
    console.log([request.url, response.statusCode]); // error happens before this is executed!
    const requestURL = new url.URL(request.url!);
    const target = `${requestURL.protocol}//${requestURL.host}`;
    proxy.web(request, response, {target: target});
  });
  server.listen(8080);
  server.on('tlsClientError', (err) => console.log(err)); // added for debugging

  // make an example request
  const response = await axios.request({
    'url': 'https://www.example.org',
    'proxy': {host: 'localhost', port: 8080},
  });
  console.log(response);
}
mainHTTPs();

But now I get suddenly a "socket hang up" error. The debugging line gives me the following cryptic error:

"Error: 9356:error:1408F09C:SSL routines:ssl3_get_record:http request:c:\ws\deps\openssl\openssl\ssl\record\ssl3_record.c:322:".

Note that the error happens before the call to proxy.web, so I assume it should not be caused by the proxying itself.

Does anyone understand this error and can help me with getting rid of it?

0

There are 0 best solutions below