smartproxy/ts/smartproxy.classes.networkproxy.ts

358 lines
12 KiB
TypeScript
Raw Normal View History

2022-07-29 00:49:46 +02:00
import * as plugins from './smartproxy.plugins.js';
import { ProxyRouter } from './smartproxy.classes.router.js';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
2019-08-21 15:09:32 +02:00
2022-07-29 00:49:46 +02:00
export interface INetworkProxyOptions {
port: number;
}
interface WebSocketWithHeartbeat extends plugins.wsDefault {
lastPong: number;
}
2022-07-29 00:49:46 +02:00
export class NetworkProxy {
// INSTANCE
public options: INetworkProxyOptions;
2019-09-23 19:20:53 +02:00
public proxyConfigs: plugins.tsclass.network.IReverseProxyConfig[] = [];
2022-07-29 00:49:46 +02:00
public httpsServer: plugins.https.Server;
public router = new ProxyRouter();
2021-02-02 15:55:25 +00:00
public socketMap = new plugins.lik.ObjectMap<plugins.net.Socket>();
2021-02-03 19:42:27 +00:00
public defaultHeaders: { [key: string]: string } = {};
public heartbeatInterval: NodeJS.Timeout;
private defaultCertificates: { key: string; cert: string };
2021-02-03 19:42:27 +00:00
public alreadyAddedReverseConfigs: {
[hostName: string]: plugins.tsclass.network.IReverseProxyConfig;
} = {};
2019-08-21 15:09:32 +02:00
2022-07-29 00:49:46 +02:00
constructor(optionsArg: INetworkProxyOptions) {
this.options = optionsArg;
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const certPath = path.join(__dirname, '..', 'assets', 'certs');
try {
this.defaultCertificates = {
key: fs.readFileSync(path.join(certPath, 'key.pem'), 'utf8'),
cert: fs.readFileSync(path.join(certPath, 'cert.pem'), 'utf8')
};
} catch (error) {
console.error('Error loading certificates:', error);
throw error;
}
2022-07-29 00:49:46 +02:00
}
2019-08-21 23:54:55 +02:00
/**
* starts the proxyInstance
*/
public async start() {
2019-11-03 03:04:23 +01:00
this.httpsServer = plugins.https.createServer(
{
key: this.defaultCertificates.key,
cert: this.defaultCertificates.cert
2019-11-03 03:04:23 +01:00
},
2022-08-01 18:40:44 +02:00
async (originRequest, originResponse) => {
2022-07-29 01:23:17 +02:00
/**
* endRequest function
* can be used to prematurely end a request
*/
2022-08-01 18:40:44 +02:00
const endOriginReqRes = (
2019-11-03 03:04:23 +01:00
statusArg: number = 404,
messageArg: string = 'This route is not available on this server.',
headers: plugins.http.OutgoingHttpHeaders = {},
2019-11-03 03:04:23 +01:00
) => {
2022-08-01 18:40:44 +02:00
originResponse.writeHead(statusArg, messageArg);
originResponse.end(messageArg);
if (originRequest.socket !== originResponse.socket) {
2023-07-27 16:27:50 +02:00
console.log('hey, something is strange.');
2022-08-01 18:40:44 +02:00
}
originResponse.destroy();
2019-11-03 03:04:23 +01:00
};
2023-07-27 16:27:50 +02:00
console.log(
`got request: ${originRequest.headers.host}${plugins.url.parse(originRequest.url).path}`,
2023-07-27 16:27:50 +02:00
);
2022-08-01 18:40:44 +02:00
const destinationConfig = this.router.routeReq(originRequest);
2022-07-29 04:25:01 +02:00
if (!destinationConfig) {
2023-07-27 16:27:50 +02:00
console.log(
`${originRequest.headers.host} can't be routed properly. Terminating request.`,
2023-07-27 16:27:50 +02:00
);
2022-08-01 18:40:44 +02:00
endOriginReqRes();
2022-07-29 04:25:01 +02:00
return;
}
2019-11-03 03:04:23 +01:00
// authentication
if (destinationConfig.authentication) {
const authInfo = destinationConfig.authentication;
switch (authInfo.type) {
case 'Basic':
2022-08-01 18:40:44 +02:00
const authHeader = originRequest.headers.authorization;
2019-11-03 03:04:23 +01:00
if (authHeader) {
if (!authHeader.includes('Basic ')) {
2022-08-01 18:40:44 +02:00
return endOriginReqRes(401, 'Authentication required', {
2021-02-02 15:55:25 +00:00
'WWW-Authenticate': 'Basic realm="Access to the staging site", charset="UTF-8"',
2019-11-03 03:04:23 +01:00
});
}
2022-08-01 18:40:44 +02:00
const authStringBase64 = originRequest.headers.authorization.replace('Basic ', '');
2019-11-03 03:04:23 +01:00
const authString: string = plugins.smartstring.base64.decode(authStringBase64);
const userPassArray = authString.split(':');
const user = userPassArray[0];
const pass = userPassArray[1];
if (user === authInfo.user && pass === authInfo.pass) {
console.log('request successfully authenticated');
} else {
2022-08-01 18:40:44 +02:00
return endOriginReqRes(403, 'Forbidden: Wrong credentials');
2019-11-03 03:04:23 +01:00
}
}
break;
default:
2022-08-01 18:40:44 +02:00
return endOriginReqRes(
2019-11-03 03:04:23 +01:00
403,
'Forbidden: unsupported authentication method configured. Please report to the admin.',
2019-11-03 03:04:23 +01:00
);
}
}
let destinationUrl: string;
if (destinationConfig) {
2022-08-01 18:40:44 +02:00
destinationUrl = `http://${destinationConfig.destinationIp}:${destinationConfig.destinationPort}${originRequest.url}`;
2019-11-03 03:04:23 +01:00
} else {
2022-08-01 18:40:44 +02:00
return endOriginReqRes();
2019-09-29 01:06:07 +02:00
}
2019-11-03 03:04:23 +01:00
console.log(destinationUrl);
try {
const proxyResponse = await plugins.smartrequest.request(
destinationUrl,
{
method: originRequest.method,
headers: {
...originRequest.headers,
'X-Forwarded-Host': originRequest.headers.host,
'X-Forwarded-Proto': 'https',
},
keepAlive: true,
2022-08-04 14:21:05 +02:00
},
true, // lets make this streaming (keepAlive)
(proxyRequest) => {
originRequest.on('data', (data) => {
proxyRequest.write(data);
});
originRequest.on('end', () => {
proxyRequest.end();
});
originRequest.on('error', () => {
proxyRequest.end();
});
originRequest.on('close', () => {
proxyRequest.end();
});
originRequest.on('timeout', () => {
proxyRequest.end();
originRequest.destroy();
});
proxyRequest.on('error', () => {
endOriginReqRes();
});
},
);
originResponse.statusCode = proxyResponse.statusCode;
console.log(proxyResponse.statusCode);
for (const defaultHeader of Object.keys(this.defaultHeaders)) {
originResponse.setHeader(defaultHeader, this.defaultHeaders[defaultHeader]);
2019-11-03 03:04:23 +01:00
}
for (const header of Object.keys(proxyResponse.headers)) {
originResponse.setHeader(header, proxyResponse.headers[header]);
}
proxyResponse.on('data', (data) => {
originResponse.write(data);
});
proxyResponse.on('end', () => {
originResponse.end();
});
proxyResponse.on('error', () => {
originResponse.destroy();
});
proxyResponse.on('close', () => {
originResponse.end();
});
proxyResponse.on('timeout', () => {
originResponse.end();
originResponse.destroy();
});
} catch (error) {
console.error('Error while processing request:', error);
endOriginReqRes(502, 'Bad Gateway: Error processing the request');
2019-11-03 03:04:23 +01:00
}
},
2019-11-03 03:04:23 +01:00
);
2019-08-21 23:54:55 +02:00
// Enable websockets
2023-07-27 16:27:50 +02:00
const wsServer = new plugins.ws.WebSocketServer({ server: this.httpsServer });
// Set up the heartbeat interval
this.heartbeatInterval = setInterval(() => {
wsServer.clients.forEach((ws: plugins.wsDefault) => {
const wsIncoming = ws as WebSocketWithHeartbeat;
if (!wsIncoming.lastPong) {
wsIncoming.lastPong = Date.now();
}
if (Date.now() - wsIncoming.lastPong > 5 * 60 * 1000) {
console.log('Terminating websocket due to missing pong for 5 minutes.');
wsIncoming.terminate();
} else {
wsIncoming.ping();
}
});
}, 60000); // runs every 1 minute
2023-07-27 16:27:50 +02:00
wsServer.on(
'connection',
async (wsIncoming: WebSocketWithHeartbeat, reqArg: plugins.http.IncomingMessage) => {
2023-07-27 16:27:50 +02:00
console.log(
`wss proxy: got connection for wsc for https://${reqArg.headers.host}${reqArg.url}`,
2023-07-27 16:27:50 +02:00
);
2023-02-04 19:32:13 +01:00
wsIncoming.lastPong = Date.now();
wsIncoming.on('pong', () => {
wsIncoming.lastPong = Date.now();
});
2023-07-27 16:27:50 +02:00
let wsOutgoing: plugins.wsDefault;
2023-02-04 19:32:13 +01:00
2023-07-27 16:27:50 +02:00
const outGoingDeferred = plugins.smartpromise.defer();
2021-02-03 19:42:27 +00:00
2023-07-27 16:27:50 +02:00
try {
wsOutgoing = new plugins.wsDefault(
`ws://${this.router.routeReq(reqArg).destinationIp}:${
this.router.routeReq(reqArg).destinationPort
}${reqArg.url}`,
2023-07-27 16:27:50 +02:00
);
console.log('wss proxy: initiated outgoing proxy');
wsOutgoing.on('open', async () => {
outGoingDeferred.resolve();
});
} catch (err) {
console.log(err);
wsIncoming.terminate();
return;
}
2023-01-06 13:04:11 +01:00
2023-07-27 16:27:50 +02:00
wsIncoming.on('message', async (message, isBinary) => {
try {
await outGoingDeferred.promise;
wsOutgoing.send(message, { binary: isBinary });
} catch (error) {
console.error('Error sending message to wsOutgoing:', error);
}
2023-07-27 16:27:50 +02:00
});
2023-01-06 11:57:11 +01:00
2023-07-27 16:27:50 +02:00
wsOutgoing.on('message', async (message, isBinary) => {
try {
wsIncoming.send(message, { binary: isBinary });
} catch (error) {
console.error('Error sending message to wsIncoming:', error);
}
2023-07-27 16:27:50 +02:00
});
2023-07-27 16:27:50 +02:00
const terminateWsOutgoing = () => {
if (wsOutgoing) {
wsOutgoing.terminate();
console.log('terminated outgoing ws.');
}
2023-07-27 16:27:50 +02:00
};
wsIncoming.on('error', () => terminateWsOutgoing());
wsIncoming.on('close', () => terminateWsOutgoing());
const terminateWsIncoming = () => {
if (wsIncoming) {
wsIncoming.terminate();
console.log('terminated incoming ws.');
}
2023-07-27 16:27:50 +02:00
};
wsOutgoing.on('error', () => terminateWsIncoming());
wsOutgoing.on('close', () => terminateWsIncoming());
},
2023-07-27 16:27:50 +02:00
);
2023-01-04 15:59:31 +01:00
this.httpsServer.keepAliveTimeout = 600 * 1000;
this.httpsServer.headersTimeout = 600 * 1000;
2019-09-29 17:18:40 +02:00
2021-02-03 11:02:26 +00:00
this.httpsServer.on('connection', (connection: plugins.net.Socket) => {
2019-09-29 17:18:40 +02:00
this.socketMap.add(connection);
2022-07-29 15:26:02 +02:00
console.log(`added connection. now ${this.socketMap.getArray().length} sockets connected.`);
2021-02-03 19:42:27 +00:00
const cleanupConnection = () => {
2022-07-29 00:49:46 +02:00
if (this.socketMap.checkForObject(connection)) {
this.socketMap.remove(connection);
2022-07-29 15:26:02 +02:00
console.log(`removed connection. ${this.socketMap.getArray().length} sockets remaining.`);
2022-07-31 08:30:13 +02:00
connection.destroy();
2022-07-29 00:49:46 +02:00
}
2021-02-03 19:42:27 +00:00
};
2022-07-29 15:26:02 +02:00
connection.on('close', () => {
2021-02-03 19:42:27 +00:00
cleanupConnection();
2021-02-03 11:02:26 +00:00
});
2022-07-29 15:26:02 +02:00
connection.on('error', () => {
2021-02-03 19:42:27 +00:00
cleanupConnection();
2021-02-03 11:02:26 +00:00
});
2022-07-29 15:26:02 +02:00
connection.on('end', () => {
2021-02-03 19:42:27 +00:00
cleanupConnection();
2021-02-03 11:02:26 +00:00
});
2022-07-30 22:29:31 +02:00
connection.on('timeout', () => {
cleanupConnection();
2023-07-27 16:27:50 +02:00
});
2019-09-29 17:18:40 +02:00
});
2022-07-29 00:49:46 +02:00
this.httpsServer.listen(this.options.port);
2022-07-29 01:52:34 +02:00
console.log(
`NetworkProxy -> OK: now listening for new connections on port ${this.options.port}`,
2022-07-29 01:52:34 +02:00
);
2019-08-21 23:54:55 +02:00
}
2020-02-07 16:06:11 +00:00
public async updateProxyConfigs(proxyConfigsArg: plugins.tsclass.network.IReverseProxyConfig[]) {
2022-07-30 08:20:20 +02:00
console.log(`got new proxy configs`);
2019-09-23 19:20:53 +02:00
this.proxyConfigs = proxyConfigsArg;
this.router.setNewProxyConfigs(proxyConfigsArg);
for (const hostCandidate of this.proxyConfigs) {
2021-02-03 19:42:27 +00:00
const existingHostNameConfig = this.alreadyAddedReverseConfigs[hostCandidate.hostName];
if (!existingHostNameConfig) {
this.alreadyAddedReverseConfigs[hostCandidate.hostName] = hostCandidate;
} else {
if (
existingHostNameConfig.publicKey === hostCandidate.publicKey &&
existingHostNameConfig.privateKey === hostCandidate.privateKey
) {
continue;
} else {
this.alreadyAddedReverseConfigs[hostCandidate.hostName] = hostCandidate;
}
}
2019-08-22 12:49:29 +02:00
this.httpsServer.addContext(hostCandidate.hostName, {
cert: hostCandidate.publicKey,
2021-02-02 15:55:25 +00:00
key: hostCandidate.privateKey,
2019-08-22 12:49:29 +02:00
});
}
2019-08-21 23:54:55 +02:00
}
2022-07-29 01:52:34 +02:00
public async addDefaultHeaders(headersArg: { [key: string]: string }) {
2022-07-29 01:37:47 +02:00
for (const headerKey of Object.keys(headersArg)) {
this.defaultHeaders[headerKey] = headersArg[headerKey];
}
}
2019-08-21 23:54:55 +02:00
public async stop() {
const done = plugins.smartpromise.defer();
this.httpsServer.close(() => {
done.resolve();
});
2021-02-02 15:55:25 +00:00
await this.socketMap.forEach(async (socket) => {
2019-09-29 17:18:40 +02:00
socket.destroy();
});
2019-08-22 15:09:48 +02:00
await done.promise;
clearInterval(this.heartbeatInterval);
console.log('NetworkProxy -> OK: Server has been stopped and all connections closed.');
2019-08-21 23:54:55 +02:00
}
}