smartproxy/ts/smartproxy.classes.smartproxy.ts

90 lines
2.4 KiB
TypeScript
Raw Normal View History

2019-08-20 16:42:52 +00:00
import * as plugins from './smartproxy.plugins';
import * as interfaces from './interfaces';
import { SmartproxyRouter } from './smartproxy.classes.router';
2019-08-21 11:06:13 +00:00
import { Socket } from 'net';
2019-08-20 16:42:52 +00:00
export class SmartProxy {
2019-08-20 20:26:44 +00:00
public httpsServer: plugins.https.Server | plugins.http.Server;
2019-08-20 16:42:52 +00:00
public router = new SmartproxyRouter();
public hostCandidates: interfaces.IHostConfig[] = [];
public addHostCandidate(hostCandidate: interfaces.IHostConfig) {
// TODO search for old hostCandidates with that target
this.hostCandidates.push(hostCandidate);
2019-08-20 16:43:15 +00:00
}
2019-08-20 16:42:52 +00:00
/**
* starts the proxyInstance
*/
public async start() {
2019-08-21 01:14:42 +00:00
this.httpsServer = plugins.http.createServer(async (req, res) => {
req.headers.host = this.router.routeReq(req);
2019-08-21 21:41:06 +00:00
const response = await plugins.smartrequest.request(
`https://${req.headers.host}${req.url}`,
{
method: req.method,
headers: req.headers
},
true
);
2019-08-21 01:14:42 +00:00
res.statusCode = response.statusCode;
for (const header of Object.keys(response.headers)) {
res.setHeader(header, response.headers[header]);
}
response.on('data', data => {
res.write(data);
});
response.on('end', () => {
res.end();
});
});
2019-08-20 17:02:13 +00:00
for (const hostCandidate of this.hostCandidates) {
2019-08-20 20:26:44 +00:00
/* this.httpsServer.addContext(hostCandidate.hostName, {
2019-08-20 17:02:13 +00:00
cert: hostCandidate.publicKey,
key: hostCandidate.privateKey
2019-08-20 20:26:44 +00:00
}); */
2019-08-20 17:02:13 +00:00
}
2019-08-21 21:41:06 +00:00
// Enable websockets
const wss = new plugins.ws.Server({ server: this.httpsServer });
wss.on('connection', function connection(ws) {
const wscConnected = plugins.smartpromise.defer();
const wsc = new plugins.ws(`${ws.url}`);
wsc.on('open', () => {
wscConnected.resolve();
});
2019-08-20 17:02:13 +00:00
2019-08-21 21:41:06 +00:00
ws.on('message', async (message) => {
await wscConnected.promise;
wsc.emit('message', message);
});
wsc.on('message', (message) => {
ws.emit('message', message);
});
// handle closing
ws.on('close', (message) => {
wsc.close();
});
wsc.on('close', (message) => {
ws.close();
});
});
this.httpsServer.listen(3000);
2019-08-20 16:42:52 +00:00
}
public async update() {
await this.start();
}
2019-08-21 21:41:06 +00:00
public async stop() {
const done = plugins.smartpromise.defer();
this.httpsServer.close(() => {
done.resolve();
});
}
2019-08-20 16:42:52 +00:00
}