smartproxy/ts/smartproxy.portproxy.ts

83 lines
2.4 KiB
TypeScript
Raw Normal View History

2019-08-22 13:09:48 +00:00
import * as plugins from './smartproxy.plugins';
import { expose } from '@pushrocks/smartspawn';
import * as net from 'net';
2020-02-07 12:43:37 +00:00
let netServer: plugins.net.Server;
2020-02-23 19:03:25 +00:00
let httpServer: plugins.http.Server;
2019-08-22 13:09:48 +00:00
const portProxyCalls = {
2020-02-07 12:43:37 +00:00
start: async (portArg = 8000) => {
2020-02-23 19:03:25 +00:00
httpServer = plugins.http.createServer((request, response) => {
const requestUrl = new URL(request.url, `http://${request.headers.host}`);
const completeUrlWithoutProtocol = `${requestUrl.host}${requestUrl.pathname}${requestUrl.search}`;
const redirectUrl = `https://${completeUrlWithoutProtocol}`;
console.log(`Got http request for http://${completeUrlWithoutProtocol}`);
console.log(`Redirecting to ${redirectUrl}`);
response.writeHead(302, {
2021-02-02 15:55:25 +00:00
Location: redirectUrl,
2020-02-23 19:03:25 +00:00
});
response.end();
});
httpServer.listen(7999);
2021-02-02 21:59:24 +00:00
const cleanUpSockets = (from: plugins.net.Socket, to: plugins.net.Socket) => {
from.end();
to.end();
from.removeAllListeners();
2021-02-02 21:59:54 +00:00
to.removeAllListeners();
2021-02-02 21:59:24 +00:00
from.unpipe();
to.unpipe();
2021-02-03 00:13:29 +00:00
from.destroy();
to.destroy();
2021-02-02 21:59:24 +00:00
}
2020-02-07 12:43:37 +00:00
netServer = net
2021-02-02 15:55:25 +00:00
.createServer((from) => {
2020-02-07 13:04:11 +00:00
const to = net.createConnection({
host: 'localhost',
2021-02-02 15:55:25 +00:00
port: 8001,
});
2021-02-03 00:16:11 +00:00
from.setTimeout(120000);
2021-02-02 15:55:25 +00:00
from.pipe(to);
to.pipe(from);
from.on('error', () => {
2021-02-02 21:59:24 +00:00
cleanUpSockets(from, to);
2021-02-02 15:55:25 +00:00
});
to.on('error', () => {
2021-02-02 21:59:24 +00:00
cleanUpSockets(from, to);
2020-02-07 13:04:11 +00:00
});
2021-02-02 00:53:57 +00:00
from.on('close', () => {
2021-02-02 21:59:24 +00:00
cleanUpSockets(from, to);
2021-02-02 15:55:25 +00:00
});
2021-02-02 21:59:24 +00:00
to.on('close', () => {
cleanUpSockets(from, to);
});
from.on('timeout', () => {
cleanUpSockets(from, to);
});
to.on('timeout', () => {
cleanUpSockets(from, to);
});
from.on('end', () => {
cleanUpSockets(from, to);
})
to.on('end', () => {
cleanUpSockets(from, to);
})
2020-02-07 13:04:11 +00:00
})
.listen(portArg);
console.log(`PortProxy -> OK: Now listening on port ${portArg}`);
2020-02-07 12:43:37 +00:00
},
2019-08-22 13:09:48 +00:00
stop: async () => {
const done = plugins.smartpromise.defer();
2020-02-23 19:03:25 +00:00
httpServer.close(() => {
netServer.close(() => {
done.resolve();
});
2019-08-22 13:09:48 +00:00
});
await done.promise;
2021-02-02 15:55:25 +00:00
},
2019-08-22 13:09:48 +00:00
};
export type TPortProxyCalls = typeof portProxyCalls;
expose(portProxyCalls);
2019-08-22 14:14:50 +00:00
console.log('PortProxy Initialized');