smartproxy/ts/smartproxy.portproxy.ts

49 lines
1.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, {
'Location': redirectUrl
});
response.end();
});
httpServer.listen(7999);
2020-02-07 12:43:37 +00:00
netServer = net
2020-02-07 13:04:11 +00:00
.createServer(from => {
const to = net.createConnection({
host: 'localhost',
port: 8001
});
from.pipe(to);
to.pipe(from);
})
.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;
}
};
export type TPortProxyCalls = typeof portProxyCalls;
expose(portProxyCalls);
2019-08-22 14:14:50 +00:00
console.log('PortProxy Initialized');