From 481cb71e65e07fdcbbd0ae2d845de5bf4235af27 Mon Sep 17 00:00:00 2001 From: Ben Phelps Date: Thu, 25 Aug 2022 01:57:07 +0300 Subject: [PATCH] switch to https over fetch for the proxy api this allows for complete control and the ability to ignored self-signed certificates --- src/pages/api/proxy.js | 60 ++++++++++++++++++++++++++++-------------- 1 file changed, 40 insertions(+), 20 deletions(-) diff --git a/src/pages/api/proxy.js b/src/pages/api/proxy.js index 1c24757cc..194e4909e 100644 --- a/src/pages/api/proxy.js +++ b/src/pages/api/proxy.js @@ -1,5 +1,27 @@ import https from "https"; +function httpsRequest(params) { + return new Promise(function (resolve, reject) { + var request = https.request(params, function (response) { + let data = ""; + + response.on("data", (chunk) => { + data = data + chunk.toString(); + }); + + response.on("end", () => { + resolve([response.statusCode, data]); + }); + }); + + request.on("error", (error) => { + reject([500, error]); + }); + + request.end(); + }); +} + export default async function handler(req, res) { const headers = ["X-API-Key", "Content-Type", "Authorization"].reduce((obj, key) => { if (req.headers && req.headers.hasOwnProperty(key.toLowerCase())) { @@ -8,25 +30,23 @@ export default async function handler(req, res) { return obj; }, {}); - try { - // this agent allows us to bypass the certificate check - // which is required for most self-signed certificates - const httpsAgent = new https.Agent({ - rejectUnauthorized: false, - }); + // this agent allows us to bypass the certificate check + // which is required for most self-signed certificates + const httpsAgent = new https.Agent({ + rejectUnauthorized: false, + }); - const result = await fetch(req.query.url, { - agent: httpsAgent, - method: req.method, - headers: headers, - body: req.method == "GET" || req.method == "HEAD" ? null : req.body, - }).then((res) => res); - - const forward = await result.text(); - return res.status(result.status).send(forward); - } catch { - return res.status(500).send({ - error: "query failed", - }); - } + const url = new URL(req.query.url); + + const [status, data] = await httpsRequest({ + hostname: url.hostname, + path: url.pathname, + port: url.port, + agent: httpsAgent, + method: req.method, + headers: headers, + body: req.method == "GET" || req.method == "HEAD" ? null : req.body, + }); + + res.status(status).send(data); }