Updated Local Alloy Proxy v2.2

v2.2
This commit is contained in:
TheEmeraldStarr 2020-10-02 08:32:55 -07:00
parent c5189dfcc1
commit 3ce747eacc
8 changed files with 475 additions and 592 deletions

600
app.js
View file

@ -1,347 +1,291 @@
var https = require('https');
var http = require('http');
var fetch = require('node-fetch');
var express = require('express');
var fs = require('fs');
var app = express();
var cookieParser = require('cookie-parser');
var session = require('express-session');
var xss = require("xss");
const express = require('express'),
app = express(),
http = require('http'),
https = require('https'),
fs = require('fs'),
querystring = require('querystring'),
session = require('express-session'),
sanitizer = require('sanitizer'),
fetch = require('node-fetch');
var config = JSON.parse(fs.readFileSync('config.json', 'utf-8')),
httpsAgent = new https.Agent({
rejectUnauthorized: false,
keepAlive: true,
}),
httpAgent = new http.Agent({
rejectUnauthorized: false,
keepAlive: true,
}),
ssl = { key: fs.readFileSync('ssl/default.key', 'utf8'), cert: fs.readFileSync('ssl/default.crt', 'utf8') },
server,
port = process.env.PORT || config.port,
ready = (() => {
var a = 'http://', b = config.listenip;
if (config.ssl) a = 'https://';
if (b == '0.0.0.0' || b == '127.0.0.1') b = 'localhost';
console.log('AlloyProxy is now running at', a + b + ':' + port);
});
http.globalAgent.maxSockets = Infinity;
https.globalAgent.maxSockets = Infinity;
if (config.ssl) server = https.createServer(ssl, app).listen(port, config.listenip, ready);
else server = http.createServer(app).listen(port, config.listenip, ready);
app.use(cookieParser());
app.use(session({
secret: 'alloy',
saveUninitialized: true,
resave: true
}));
app.use((req, res, next)=>{
// nice bodyparser alternative that wont cough up errors
req.setEncoding('utf8');
req.raw_body = ''
req.body = new Object()
req.on('data', chunk=>{ req.raw_body += chunk });
req.on('end', ()=>{
req.str_body = req.raw_body.toString('utf8');
try{
var result = new Object();
req.str_body.split('&').forEach((pair)=>{
pair = pair.split('=');
req.body[pair[0]] = decodeURIComponent(pair[1] || '');
});
}catch(err){
req.body = {}
}
return next();
});
});
function base64Encode(data) {
return new Buffer.from(data).toString('base64')
}
// How to use: base64Decode('string') will return any input base64 decoded
function base64Decode(data) {
return new Buffer.from(data, 'base64').toString('ascii')
}
// How to use: rewritingURL('https://example.org/assets/main.js') will rewrite any external URL. Output: aHR0cHM6Ly9leGFtcGxlLm9yZw==/assets/main.js
function rewriteURL(dataURL, option) {
var websiteURL
var websitePath
if (option == 'decode') {
websiteURL = base64Decode(dataURL.split('/').splice(0, 1).join('/'))
websitePath = '/' + dataURL.split('/').splice(1).join('/')
} else {
websiteURL = base64Encode(dataURL.split('/').splice(0, 3).join('/'))
websitePath = '/' + dataURL.split('/').splice(3).join('/')
const config = JSON.parse(fs.readFileSync('./config.json', {encoding:'utf8'}));
if (!config.prefix.startsWith('/')) {
config.prefix = `/${config.prefix}`;
}
if (websitePath == '/') {
return `${websiteURL}`
} else return `${websiteURL}${websitePath}`
}
// To be used with res.send() to send error. Example: res.send(error('404', 'No valid directory or file was found!'))
function error(statusCode, info) {
if (statusCode && info) {
return fs.readFileSync('alloy/assets/error.html', 'utf8').toString().replace('%ERROR%', `Error ${statusCode}: ${info}`)
if (!config.prefix.endsWith('/')) {
config.prefix = `${config.prefix}/`;
}
if (info && !statusCode) {
return (fs.readFileSync('alloy/assets/error.html', 'utf8').toString().replace('%ERROR%', `Error: ${info}`))
}
if (statusCode && !info) {
return (fs.readFileSync('alloy/assets/error.html', 'utf8').toString().replace('%ERROR%', `Error ${statusCode}`))
}
return (fs.readFileSync('public/assets/error.html', 'utf8').toString().replace('%ERROR%', `An error has occurred!`))
}
// Post data to set URl's for reverse proxy URL's, or safer redirecting to proxied websites.
app.post('/createSession', async (req, res) => {
if (req.body.url.startsWith('//')) {
req.body.url = 'http:' + req.body.url;
} else if (req.body.url.startsWith('https://') || req.body.url.startsWith('http://')) {
req.body.url = req.body.url;
} else {
req.body.url = 'http://' + req.body.url;
}
if (req.body.rv) {
req.session.rvURL = String(req.body.url).split('/').splice(0, 3).join('/')
return res.redirect('/fetch/rv/' + String(req.body.url).split('/').splice(3).join('/'))
} else {
return res.redirect('/fetch/' + rewriteURL(String(req.body.url)))
}
})
// Custom prefix support will be in full effect soon!
var prefix = '/fetch';
let server;
let server_protocol;
const server_options = {
key: fs.readFileSync('./ssl/default.key'),
cert: fs.readFileSync('./ssl/default.crt')
}
if (config.ssl == true) { server = https.createServer(server_options, app); server_protocol = 'https://';}
else { server = http.createServer(app); server_protocol = 'http://';};
app.use(prefix, async (req, res, next) => {
var location = rewriteURL(req.url.slice(1), 'decode');
if (req.url.startsWith('/rv') && !req.session.rvURL) {
res.send(error('400', 'No valid session URL for reverse proxy mode was found!'))
}
if (req.url.startsWith('/rv') && req.session.rvURL) {
location = req.session.rvURL + req.url.slice(3)
}
location = {
href: location,
hostname : location.split('/').splice(2).splice(0, 1).join('/'),
origin : location.split('/').splice(0, 3).join('/'),
origin_encoded : base64Encode(location.split('/').splice(0, 3).join('/')),
path : '/' + location.split('/').splice(3).join('/'),
protocol : location.split('\:').splice(0, 1).join(''),
}
var httpAgent = new http.Agent({
keepAlive: true
});
var httpsAgent = new https.Agent({
keepAlive: true
});
// We are using the clients request headers as the headers to send the request so that headers such as Authorization will be passed through in a XML or fetch() request.
// The host header has to be set to the websites host and not the apps hostname so that there won't be issues.
var fetchHeaders = req.headers
fetchHeaders['referer'] = location.href
fetchHeaders['origin'] = location.origin
fetchHeaders['host'] = location.hostname
// Cookie header causing issues sometimes :cursed:
if (fetchHeaders['cookie']) {
delete fetchHeaders['cookie']
}
var options = {
method: req.method,
headers: fetchHeaders,
redirect: 'manual',
agent: function(_parsedURL) {
if (_parsedURL.protocol == 'http:') {
return httpAgent;
} else {
return httpsAgent;
}
}
console.log(`Alloy Proxy now running on ${server_protocol}0.0.0.0:${config.port}! Proxy prefix is "${config.prefix}"!`);
server.listen(process.env.PORT || config.port);
btoa = (str) => {
str = new Buffer.from(str).toString('base64');
return str;
};
if (req.method == 'POST') {
try {
// str_body is a string containing the requests body
options['body'] = req.str_body;
}catch(err){
return;
}
}
// Makes sure to use the session URL that is contained so RV mode works.
if (req.url.startsWith('/rv')) {
location.origin_encoded = 'rv'
}
if (!req.url.startsWith(`/${location.origin_encoded}/`)) {
try{
return res.redirect(307,`/fetch/${location.origin_encoded}/`)
}catch(err){
return;
}
}
// Custom fixes for websites such as Discord and Reddit.
if (location.href == 'https://discord.com' || location.href == 'https://discord.com/new') {
return res.redirect(307, `/fetch/${location.origin_encoded}/login`)
}
if (location.origin == 'https://www.reddit.com') {
if (req.url.startsWith('/rv') && req.session.rvURL) {
req.session.rvURL = 'https://old.reddit.com'
return res.redirect(307, '/fetch/rv' + location.path)
}
return res.redirect(307, '/fetch/' + base64Encode('https://old.reddit.com') + location.path)
}
// This is where I am making the request, and getting the buffer and headers.
const response = await fetch(location.href, options).catch(err => res.send(error('404', `"${xss(location.href)}" was not found!`)));
if(typeof response.buffer != 'function')return;
var resbody = await response.buffer();
var contentType = 'text/plain'
response.headers.forEach((e, i, a) => {
if (i == 'content-type') contentType = e;
atob = (str) => {
str = new Buffer.from(str, 'base64').toString('utf-8');
return str;
};
rewrite_url = (dataURL, option) => {
var websiteURL;
var websitePath;
if (option == 'decode') {
websiteURL = atob(dataURL.split('/').splice(0, 1).join('/'));
websitePath = '/' + dataURL.split('/').splice(1).join('/');
} else {
websiteURL = btoa(dataURL.split('/').splice(0, 3).join('/'));
websitePath = '/' + dataURL.split('/').splice(3).join('/');
}
if (websitePath == '/') { return `${websiteURL}`; } else return `${websiteURL}${websitePath}`;
};
app.use(session({
secret: 'alloy',
saveUninitialized: true,
resave: true
}));
// We made our own version of body-parser instead, due to issues.
app.use((req, res, next) => {
if (req.method == 'POST') {
req.raw_body = '';
req.on('data', chunk => {
req.raw_body += chunk.toString(); // convert Buffer to string
});
req.on('end', () => {
req.str_body = req.raw_body;
try {
req.body = JSON.parse(req.raw_body);
} catch(err) {
req.body = {}
}
next();
});
} else return next();
});
if (contentType == null || typeof contentType == 'undefined') ct = 'text/html';
var serverHeaders = Object.fromEntries(
Object.entries(JSON.parse(JSON.stringify(response.headers.raw())))
.map(([key, val]) => [key, val[0]])
);
// Making sure redirects are proxied.
if (serverHeaders['location']) {
if (req.url.startsWith('/rv') && req.session.rvURL) {
req.session.rvURL = String(serverHeaders['location']).split('/').splice(0, 3).join('/')
return res.redirect(307, '/fetch/rv/' + String(serverHeaders['location']).split('/').splice(3).join('/'))
} else return res.redirect(307, '/fetch/' + rewriteURL(String(serverHeaders['location'])))
}
// These headers can be conflicting.
delete serverHeaders['content-encoding']
delete serverHeaders['x-frame-options']
delete serverHeaders['strict-transport-security']
delete serverHeaders['content-security-policy']
delete serverHeaders['location']
// Setting status, headers, and content-type.
res.status(response.status)
res.set(serverHeaders)
res.contentType(contentType)
if (response.redirected == true) {
if (req.url.startsWith('/rv') && req.session.rvURL) {
req.session.rvURL = response.url.split('/').splice(0, 3).join('/')
return res.redirect(307, '/fetch/rv/' + response.url.split('/').splice(3).join('/'))
} else return res.redirect(307, '/fetch/' + rewriteURL(response.url))
}
if (contentType.startsWith('text/html')) {
req.session.fetchURL = location.origin_encoded
resbody = resbody.toString()
.replace(/integrity="(.*?)"/gi, '')
.replace(/nonce="(.*?)"/gi, '')
.replace(/(href|src|poster|data|action)="\/\/(.*?)"/gi, `$1` + `="http://` + `$2` + `"`)
.replace(/(href|src|poster|data|action)='\/\/(.*?)'/gi, `$1` + `='http://` + `$2` + `'`)
.replace(/(href|src|poster|data|action)="\/(.*?)"/gi, `$1` + `="/fetch/${location.origin_encoded}/` + `$2` + `"`)
.replace(/(href|src|poster|data|action)='\/(.*?)'/gi, `$1` + `='/fetch/${location.origin_encoded}/` + `$2` + `'`)
.replace(/'(https:\/\/|http:\/\/)(.*?)'/gi, function(str) {
str = str.split(`'`).slice(1).slice(0, -1).join(``);
return `'/fetch/${rewriteURL(str)}'`
})
.replace(/"(https:\/\/|http:\/\/)(.*?)"/gi, function(str) {
str = str.split(`"`).slice(1).slice(0, -1).join(``);
return `"/fetch/${rewriteURL(str)}"`
})
.replace(/(window|document).location.href/gi, `"${location.href}"`)
.replace(/(window|document).location.hostname/gi, `"${location.hostname}"`)
.replace(/(window|document).location.pathname/gi, `"${location.path}"`)
.replace(/location.href/gi, `"${location.href}"`)
.replace(/location.hostname/gi, `"${location.hostname}"`)
.replace(/location.pathname/gi, `"${location.path}"`)
.replace(/<html(.*?)>/gi, '<html' + '$1' + '><script id="alloyData" data-alloyURL="' + location.origin_encoded + '"' + ' src="/alloy/assets/inject.js"></script>')
} else if (contentType.startsWith('text/css')) {
resbody = resbody.toString()
.replace(/url\("\/\/(.*?)"\)/gi, `url("http://` + `$1` + `")`)
.replace(/url\('\/\/(.*?)'\)/gi, `url('http://` + `$1` + `')`)
.replace(/url\(\/\/(.*?)\)/gi, `url(http://` + `$1` + `)`)
.replace(/url\("\/(.*?)"\)/gi, `url("/fetch/${location.origin_encoded}/` + `$1` + `")`)
.replace(/url\('\/(.*?)'\)/gi, `url('/fetch/${location.origin_encoded}/` + `$1` + `')`)
.replace(/url\(\/(.*?)\)/gi, `url(/fetch/${location.origin_encoded}/` + `$1` + `)`)
.replace(/"(https:\/\/|http:\/\/)(.*?)"/gi, function(str) {
str = str.split(`"`).slice(1).slice(0, -1).join(``);
return `"/fetch/${rewriteURL(str)}"`
})
.replace(/'(https:\/\/|http:\/\/)(.*?)'/gi, function(str) {
str = str.split(`'`).slice(1).slice(0, -1).join(``);
return `'/fetch/${rewriteURL(str)}'`
})
.replace(/\((https:\/\/|http:\/\/)(.*?)\)/gi, function(str) {
str = str.split(`(`).slice(1).join(``).split(')').slice(0, -1).join('');
return `(/fetch/${rewriteURL(str)})`
})
} else if (contentType.startsWith('text/javascript') || contentType.startsWith('application/javascript')) {
resbody = resbody.toString()
.replace(/xhttp.open\("GET",(.*?)"http(.*?)"(.*?),(.*?)true\);/gi, ' xhttp.open("GET",' + '$1' + '"/alloy/url/http' + '$2' + '"' + '$3' + ',' + '$4' + 'true')
.replace(/xhttp.open\("POST",(.*?)"http(.*?)"(.*?),(.*?)true\);/gi, ' xhttp.open("POST",' + '$1' + '"/alloy/url/http' + '$2' + '"' + '$3' + ',' + '$4' + 'true')
.replace(/xhttp.open\("OPTIONS",(.*?)"http(.*?)"(.*?),(.*?)true\);/gi, ' xhttp.open("OPTIONS",' + '$1' + '"/alloy/url/http' + '$2' + '"' + '$3' + ',' + '$4' + 'true')
.replace(/xhr.open\("GET",(.*?)"http(.*?)"(.*?),(.*?)true\);/gi, ' xhr.open("GET",' + '$1' + '"/alloy/url/http' + '$2' + '"' + '$3' + ',' + '$4' + 'true')
.replace(/xhr.open\("POST",(.*?)"http(.*?)"(.*?),(.*?)true\);/gi, ' xhr.open("POST",' + '$1' + '"/alloy/url/http' + '$2' + '"' + '$3' + ',' + '$4' + 'true')
.replace(/xhr.open\("OPTIONS",(.*?)"http(.*?)"(.*?),(.*?)true\);/gi, ' xhr.open("OPTIONS",' + '$1' + '"/alloy/url/http' + '$2' + '"' + '$3' + ',' + '$4' + 'true')
.replace(/ajax\("http:\/\/(.*?)"\)/gi, 'ajax("/alloy/url/http://' + '$1' + '")')
.replace(/ajax\("https:\/\/(.*?)"\)/gi, 'ajax("/alloy/url/https://' + '$1' + '")')
app.use(`${config.prefix}utils/`, async(req, res, next) => {
if (req.url.startsWith('/assets/')){res.sendFile(__dirname + '/utils' + req.url);}
if (req.query.url) {
let url = atob(req.query.url);
if (url.startsWith('https://') || url.startsWith('http://')) {
url = url;
} else if (url.startsWith('//')) {
url = 'http:' + url;
} else {
url = 'http://' + url;
}
res.send(resbody)
})
return res.redirect(307, config.prefix + rewrite_url(url));
}
});
app.use('/alloy/url/',function (req, res, next) {
const mainurl = req.url.split('/').slice(1).join('/')
const host = mainurl.split('/').slice(0, 3).join('/')
const buff = new Buffer(host);
const host64 = buff.toString('base64');
const path = mainurl.split('/').slice(3).join('/')
const fullURL = host64 + '/' + path
res.redirect(307, '/fetch/' + fullURL)
})
app.post(`${config.prefix}session/`, async(req, res, next) => {
let url = querystring.parse(req.raw_body).url;
if (url.startsWith('//')) { url = 'http:' + url; }
else if (url.startsWith('https://') || url.startsWith('http://')) { url = url }
else {url = 'http://' + url};
return res.redirect(config.prefix + rewrite_url(url));
});
// Utils section. Where stuff such as inject scripts are found!
app.use('/alloy/',function (req, res, next) {
app.use(config.prefix, async(req, res, next) => {
var proxy = {};
proxy.url = rewrite_url(req.url.slice(1), 'decode');
proxy.url = {
href: proxy.url,
hostname : proxy.url.split('/').splice(2).splice(0, 1).join('/'),
origin : proxy.url.split('/').splice(0, 3).join('/'),
encoded_origin : btoa(proxy.url.split('/').splice(0, 3).join('/')),
path : '/' + proxy.url.split('/').splice(3).join('/'),
protocol : proxy.url.split('\:').splice(0, 1).join(''),
}
if (req.query.url) {
var clientInput = base64Decode(req.query.url)
var fetchURL;
if (clientInput.startsWith('//')) {
fetchURL = rewriteURL('http:' + clientInput)
} else if (clientInput.startsWith('http://') || clientInput.startsWith('https://')) {
fetchURL = rewriteURL(clientInput)
} else {
fetchURL = rewriteURL('http://' + clientInput)
}
return res.redirect(307, '/fetch/' + fetchURL)
}
res.sendFile(__dirname + '/alloy' + req.url, function (err) {
if (err) {
if (req.session.fetchURL) {
return res.redirect(307, '/fetch/' + req.session.fetchURL + req.url)
} else return res.redirect(307, '/')
proxy.url.encoded_origin = btoa(proxy.url.origin);
proxy.requestHeaders = req.headers;
proxy.requestHeaders['host'] = proxy.url.hostname;
if (proxy.requestHeaders['referer']) {
let referer = '/' + String(proxy.requestHeaders['referer']).split('/').splice(3).join('/');
referer = rewrite_url(referer.replace(config.prefix, ''), 'decode');
if (referer.startsWith('https://') || referer.startsWith('http://')) {
referer = referer;
} else referer = proxy.url.href;
proxy.requestHeaders['referer'] = referer;
}
if (proxy.requestHeaders['origin']) {
let origin = '/' + String(proxy.requestHeaders['origin']).split('/').splice(3).join('/');
origin = rewrite_url(origin.replace(config.prefix, ''), 'decode');
if (origin.startsWith('https://') || origin.startsWith('http://')) {
origin = origin.split('/').splice(0, 3).join('/');
} else origin = proxy.url.origin;
proxy.requestHeaders['origin'] = origin;
}
if (proxy.requestHeaders.cookie) {
delete proxy.requestHeaders.cookie;
}
const httpAgent = new http.Agent({
keepAlive: true
});
const httpsAgent = new https.Agent({
keepAlive: true
});
proxy.options = {
method: req.method,
headers: proxy.requestHeaders,
redirect: 'manual',
agent: function(_parsedURL) {
if (_parsedURL.protocol == 'http:') {
return httpAgent;
} else {
return httpsAgent;
}
}
};
if (req.method == 'POST') {
proxy.options.body = req.str_body;
}
})
if (proxy.url.hostname == 'discord.com' && proxy.url.path == '/') { return res.redirect(307, config.prefix + rewrite_url('https://discord.com/login'));};
})
if (proxy.url.hostname == 'www.reddit.com') { return res.redirect(307, config.prefix + rewrite_url('https://old.reddit.com'));};
app.use(function (req, res, next) {
res.sendFile(__dirname + '/public' + req.url, function (err) {
if (err) {
if (req.session.fetchURL) {
return res.redirect(307, '/fetch/' + req.session.fetchURL + req.url)
} else return res.redirect(307, '/')
if (!req.url.slice(1).startsWith(`${proxy.url.encoded_origin}/`)) { return res.redirect(307, config.prefix + proxy.url.encoded_origin + '/');};
proxy.response = await fetch(proxy.url.href, proxy.options).catch(err => res.send(fs.readFileSync('./utils/error/error.html', 'utf8').toString().replace('%ERROR%', `Error 400: Could not make request to '${sanitizer.sanitize(proxy.url.href)}'!`)));
if(typeof proxy.response.buffer != 'function')return;
proxy.buffer = await proxy.response.buffer();
proxy.content_type = 'text/plain';
proxy.response.headers.forEach((e, i, a) => {
if (i == 'content-type') proxy.content_type = e;
});
if (proxy.content_type == null || typeof proxy.content_type == 'undefined') proxy.content_type = 'text/html';
proxy.sendResponse = proxy.buffer;
// Parsing the headers from the response to remove square brackets so we can set them as the response headers.
proxy.headers = Object.fromEntries(
Object.entries(JSON.parse(JSON.stringify(proxy.response.headers.raw())))
.map(([key, val]) => [key, val[0]])
);
// Parsing all the headers to remove all of the bad headers that could affect proxies performance.
Object.entries(proxy.headers).forEach(([header_name, header_value]) => {
if (header_name.startsWith('content-encoding') || header_name.startsWith('x-') || header_name.startsWith('cf-') || header_name.startsWith('strict-transport-security') || header_name.startsWith('content-security-policy')) {
delete proxy.headers[header_name];
}
});
// If theres a location for a redirect in the response, then the proxy will get the response location then redirect you to the proxied version of the url.
if (proxy.response.headers.get('location')) {
return res.redirect(307, config.prefix + rewrite_url(String(proxy.response.headers.get('location'))));
}
})
});
res.status(proxy.response.status);
res.set(proxy.headers);
res.contentType(proxy.content_type);
if (proxy.content_type.startsWith('text/html')) {
req.session.url = proxy.url.origin;
proxy.sendResponse = proxy.sendResponse.toString()
.replace(/integrity="(.*?)"/gi, '')
.replace(/nonce="(.*?)"/gi, '')
.replace(/(href|src|poster|data|action|srcset)="\/\/(.*?)"/gi, `$1` + `="http://` + `$2` + `"`)
.replace(/(href|src|poster|data|action|srcset)='\/\/(.*?)'/gi, `$1` + `='http://` + `$2` + `'`)
.replace(/(href|src|poster|data|action|srcset)="\/(.*?)"/gi, `$1` + `="${config.prefix}${proxy.url.encoded_origin}/` + `$2` + `"`)
.replace(/(href|src|poster|data|action|srcset)='\/(.*?)'/gi, `$1` + `='${config.prefix}${proxy.url.encoded_origin}/` + `$2` + `'`)
.replace(/'(https:\/\/|http:\/\/)(.*?)'/gi, function(str) {
str = str.split(`'`).slice(1).slice(0, -1).join(``);
return `'${config.prefix}${rewrite_url(str)}'`
})
.replace(/"(https:\/\/|http:\/\/)(.*?)"/gi, function(str) {
str = str.split(`"`).slice(1).slice(0, -1).join(``);
return `"${config.prefix}${rewrite_url(str)}"`
})
.replace(/(window|document).location.href/gi, `"${proxy.url.href}"`)
.replace(/(window|document).location.hostname/gi, `"${proxy.url.hostname}"`)
.replace(/(window|document).location.pathname/gi, `"${proxy.url.path}"`)
.replace(/location.href/gi, `"${proxy.url.href}"`)
.replace(/location.hostname/gi, `"${proxy.url.hostname}"`)
.replace(/location.pathname/gi, `"${proxy.url.path}"`)
.replace(/<html(.*?)>/gi, `<html` + '$1' + `><script src="${config.prefix}utils/assets/inject.js" id="_alloy_data" prefix="${config.prefix}" url="${btoa(proxy.url.href)}"></script>`);
// Temp hotfix for Youtube search bar until my script injection can fix it.
if (proxy.url.hostname == 'www.youtube.com') { proxy.sendResponse = proxy.sendResponse.replace(/\/results/gi, `${config.prefix}${proxy.url.encoded_origin}/results`);};
} else if (proxy.content_type.startsWith('text/css')) {
proxy.sendResponse = proxy.sendResponse.toString()
.replace(/url\("\/\/(.*?)"\)/gi, `url("http://` + `$1` + `")`)
.replace(/url\('\/\/(.*?)'\)/gi, `url('http://` + `$1` + `')`)
.replace(/url\(\/\/(.*?)\)/gi, `url(http://` + `$1` + `)`)
.replace(/url\("\/(.*?)"\)/gi, `url("${config.prefix}${proxy.url.encoded_origin}/` + `$1` + `")`)
.replace(/url\('\/(.*?)'\)/gi, `url('${config.prefix}${proxy.url.encoded_origin}/` + `$1` + `')`)
.replace(/url\(\/(.*?)\)/gi, `url(${config.prefix}${proxy.url.encoded_origin}/` + `$1` + `)`)
.replace(/"(https:\/\/|http:\/\/)(.*?)"/gi, function(str) {
str = str.split(`"`).slice(1).slice(0, -1).join(``);
return `"${config.prefix}${rewrite_url(str)}"`
})
.replace(/'(https:\/\/|http:\/\/)(.*?)'/gi, function(str) {
str = str.split(`'`).slice(1).slice(0, -1).join(``);
return `'${config.prefix}${rewrite_url(str)}'`
})
.replace(/\((https:\/\/|http:\/\/)(.*?)\)/gi, function(str) {
str = str.split(`(`).slice(1).join(``).split(')').slice(0, -1).join('');
return `(${config.prefix}${rewrite_url(str)})`
});
};
// We send the response from the server rewritten.
res.send(proxy.sendResponse);
});
app.use('/', express.static('public'));
app.use(async(req, res, next) => {
if (req.headers['referer']) {
let referer = '/' + String(req.headers['referer']).split('/').splice(3).join('/');
referer = rewrite_url(referer.replace(config.prefix, ''), 'decode').split('/').splice(0, 3).join('/');
if (referer.startsWith('https://') || referer.startsWith('http://')) {
res.redirect(307, config.prefix + btoa(referer) + req.url)
} else {
if (req.session.url) {
res.redirect(307, config.prefix + btoa(req.session.url) + req.url)
} else return next();
}
} else if (req.session.url) {
res.redirect(307, config.prefix + btoa(req.session.url) + req.url)
} else return next();
});