-
-
Save supersonictw/cf01a30ed886c8763bdd8329c1115f8c to your computer and use it in GitHub Desktop.
Easy CORS/Reverse Proxy
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
// ecrp.js - Easy CORS/Reverse Proxy | |
// SPDX-License-Identifier: MIT (https://ncurl.xyz/s/o_o6DVqIR) | |
// https://gist.github.com/supersonictw/cf01a30ed886c8763bdd8329c1115f8c | |
"use strict"; | |
const cookieEncoder = (data) => { | |
const cookies = []; | |
for (const key in data) { | |
const value = encodeURIComponent(data[key]); | |
cookies.push(`${key}=${value}`); | |
} | |
return cookies.join("; "); | |
}; | |
const config = { | |
connection: { | |
scheme: 'https', | |
host: 'example.com', | |
}, | |
reqOrigin: 'https://example.com', | |
resOrigin: 'http://example.com', | |
extendReqHeaders: { | |
cookie: cookieEncoder({ | |
lang: "en", | |
}), | |
"x-requested-with": "ECRP", | |
}, | |
extendResHeaders: { | |
"x-powered-by": "ECRP", | |
}, | |
}; | |
const http = require("node:http"); | |
const https = require("node:https"); | |
http.createServer((req, rsp) => { | |
const options = { | |
...config.connection, | |
path: req.url, | |
method: req.method, | |
headers: { | |
...req.headers, | |
host: config.connection.host, | |
origin: config.reqOrigin, | |
referer: config.reqOrigin, | |
connection: "close", | |
...config.extendReqHeaders | |
}, | |
port: config.connection.port || | |
(config.connection.scheme === 'https' ? 443 : 80), | |
}; | |
const client = config.connection.scheme === 'https' ? https : http; | |
const proxy = client.request(options, (response) => { | |
rsp.writeHead(response.statusCode, { | |
...response.headers, | |
"access-control-allow-origin": config.resOrigin, | |
"access-control-allow-credentials": "true", | |
...config.extendResHeaders | |
}); | |
response.on("data", (chunk) => { | |
rsp.write(chunk); | |
}); | |
response.on("end", () => { | |
rsp.end(); | |
}); | |
}); | |
proxy.once("error", (e) => { | |
console.error(e); | |
rsp.writeHead(500); | |
rsp.end(); | |
}); | |
req.pipe(proxy); | |
req.on('end', () => { | |
proxy.end() | |
}); | |
}).listen(8000); | |
console.info("Proxy server running at http://localhost:8000/"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment