Compare commits

...

4 Commits

8 changed files with 140 additions and 84 deletions

View File

@ -1,5 +1,19 @@
# Changelog # Changelog
## 2025-02-21 - 3.8.1 - fix(plugins)
Simplified plugin import structure across codebase
- Consolidated plugin imports under a single 'plugins.ts' file.
- Replaced individual plugin imports in smartproxy files with the consolidated plugin imports.
- Fixed error handling for early socket errors in PortProxy setup.
## 2025-02-21 - 3.8.0 - feat(PortProxy)
Add active connection tracking and logging in PortProxy
- Implemented a feature to track active incoming connections in PortProxy.
- Active connections are now logged every 10 seconds for monitoring purposes.
- Refactored connection handling to ensure proper cleanup and logging.
## 2025-02-21 - 3.7.3 - fix(portproxy) ## 2025-02-21 - 3.7.3 - fix(portproxy)
Fix handling of connections in PortProxy to improve stability and performance. Fix handling of connections in PortProxy to improve stability and performance.

View File

@ -1,6 +1,6 @@
{ {
"name": "@push.rocks/smartproxy", "name": "@push.rocks/smartproxy",
"version": "3.7.3", "version": "3.8.1",
"private": false, "private": false,
"description": "a proxy for handling high workloads of proxying", "description": "a proxy for handling high workloads of proxying",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",

View File

@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartproxy', name: '@push.rocks/smartproxy',
version: '3.7.3', version: '3.8.1',
description: 'a proxy for handling high workloads of proxying' description: 'a proxy for handling high workloads of proxying'
} }

View File

@ -1,4 +1,4 @@
import * as plugins from './smartproxy.plugins.js'; import * as plugins from './plugins.js';
import { ProxyRouter } from './smartproxy.classes.router.js'; import { ProxyRouter } from './smartproxy.classes.router.js';
import * as fs from 'fs'; import * as fs from 'fs';
import * as path from 'path'; import * as path from 'path';

View File

@ -1,4 +1,4 @@
import * as plugins from './smartproxy.plugins.js'; import * as plugins from './plugins.js';
export class ProxyRouter { export class ProxyRouter {
public reverseProxyConfigs: plugins.tsclass.network.IReverseProxyConfig[] = []; public reverseProxyConfigs: plugins.tsclass.network.IReverseProxyConfig[] = [];

View File

@ -1,4 +1,4 @@
import * as plugins from './smartproxy.plugins.js'; import * as plugins from './plugins.js';
export class SslRedirect { export class SslRedirect {
httpServer: plugins.http.Server; httpServer: plugins.http.Server;

View File

@ -1,4 +1,4 @@
import * as plugins from './smartproxy.plugins.js'; import * as plugins from './plugins.js';
export interface IDomainConfig { export interface IDomainConfig {
domain: string; // glob pattern for domain domain: string; // glob pattern for domain
@ -115,6 +115,9 @@ function extractSNI(buffer: Buffer): string | undefined {
export class PortProxy { export class PortProxy {
netServer: plugins.net.Server; netServer: plugins.net.Server;
settings: IProxySettings; settings: IProxySettings;
// Track active incoming connections
private activeConnections: Set<plugins.net.Socket> = new Set();
private connectionLogger: NodeJS.Timeout | null = null;
constructor(settings: IProxySettings) { constructor(settings: IProxySettings) {
this.settings = { this.settings = {
@ -161,23 +164,64 @@ export class PortProxy {
return this.settings.domains.find(config => plugins.minimatch(serverName, config.domain)); return this.settings.domains.find(config => plugins.minimatch(serverName, config.domain));
}; };
// Always create a plain net server for TLS passthrough. // Create a plain net server for TLS passthrough.
this.netServer = plugins.net.createServer((socket: plugins.net.Socket) => { this.netServer = plugins.net.createServer((socket: plugins.net.Socket) => {
const remoteIP = socket.remoteAddress || ''; const remoteIP = socket.remoteAddress || '';
// If SNI is enabled, we peek at the first chunk to extract the SNI. // Flag to detect if we've received the first data chunk.
if (this.settings.sniEnabled) { let initialDataReceived = false;
socket.once('data', (chunk: Buffer) => {
// Try to extract the server name from the ClientHello.
const serverName = extractSNI(chunk) || '';
console.log(`Received connection from ${remoteIP} with SNI: ${serverName}`);
// Immediately attach an error handler to catch early errors.
socket.on('error', (err: Error) => {
if (!initialDataReceived) {
console.log(`(Premature) Incoming socket error from ${remoteIP} before data received: ${err.message}`);
} else {
console.log(`(Immediate) Incoming socket error from ${remoteIP}: ${err.message}`);
}
});
// Track the new incoming connection.
this.activeConnections.add(socket);
console.log(`New connection from ${remoteIP}. Active connections: ${this.activeConnections.size}`);
// Flag to ensure cleanup happens only once.
let connectionClosed = false;
const cleanupOnce = () => {
if (!connectionClosed) {
connectionClosed = true;
cleanUpSockets(socket, to);
if (this.activeConnections.has(socket)) {
this.activeConnections.delete(socket);
console.log(`Connection from ${remoteIP} terminated. Active connections: ${this.activeConnections.size}`);
}
}
};
let to: plugins.net.Socket;
const handleError = (side: 'incoming' | 'outgoing') => (err: Error) => {
const code = (err as any).code;
if (code === 'ECONNRESET') {
console.log(`ECONNRESET on ${side} side from ${remoteIP}: ${err.message}`);
} else {
console.log(`Error on ${side} side from ${remoteIP}: ${err.message}`);
}
cleanupOnce();
};
const handleClose = (side: 'incoming' | 'outgoing') => () => {
console.log(`Connection closed on ${side} side from ${remoteIP}`);
cleanupOnce();
};
// Setup connection, optionally accepting the initial data chunk.
const setupConnection = (serverName: string, initialChunk?: Buffer) => {
// Check if the IP is allowed by default. // Check if the IP is allowed by default.
const isDefaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs); const isDefaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
if (!isDefaultAllowed && serverName) { if (!isDefaultAllowed && serverName) {
const domainConfig = findMatchingDomain(serverName); const domainConfig = findMatchingDomain(serverName);
if (!domainConfig) { if (!domainConfig) {
console.log(`Connection rejected: No matching domain config for ${serverName} from IP ${remoteIP}`); console.log(`Connection rejected: No matching domain config for ${serverName} from ${remoteIP}`);
socket.end(); socket.end();
return; return;
} }
@ -207,58 +251,47 @@ export class PortProxy {
connectionOptions.localAddress = remoteIP.replace('::ffff:', ''); connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
} }
const to = plugins.net.connect(connectionOptions); // Establish outgoing connection.
to = plugins.net.connect(connectionOptions);
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`); console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`);
// Unshift the data chunk back so that the TLS handshake can complete at the backend. // Push back the initial chunk if provided.
socket.unshift(chunk); if (initialChunk) {
socket.unshift(initialChunk);
}
socket.setTimeout(120000); socket.setTimeout(120000);
socket.pipe(to); socket.pipe(to);
to.pipe(socket); to.pipe(socket);
const errorHandler = () => { // Attach error and close handlers for both sockets.
cleanUpSockets(socket, to); socket.on('error', handleError('incoming'));
to.on('error', handleError('outgoing'));
socket.on('close', handleClose('incoming'));
to.on('close', handleClose('outgoing'));
socket.on('timeout', handleError('incoming'));
to.on('timeout', handleError('outgoing'));
socket.on('end', handleClose('incoming'));
to.on('end', handleClose('outgoing'));
}; };
socket.on('error', errorHandler);
to.on('error', errorHandler); // For SNI-enabled connections, peek at the first chunk.
socket.on('close', errorHandler); if (this.settings.sniEnabled) {
to.on('close', errorHandler); socket.once('data', (chunk: Buffer) => {
socket.on('timeout', errorHandler); initialDataReceived = true;
to.on('timeout', errorHandler); // Try to extract the server name from the ClientHello.
socket.on('end', errorHandler); const serverName = extractSNI(chunk) || '';
to.on('end', errorHandler); console.log(`Received connection from ${remoteIP} with SNI: ${serverName}`);
setupConnection(serverName, chunk);
}); });
} else { } else {
// If SNI is not enabled, use defaultAllowedIPs check. // For non-SNI connections, simply check defaultAllowedIPs.
initialDataReceived = true;
if (!this.settings.defaultAllowedIPs || !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) { if (!this.settings.defaultAllowedIPs || !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
console.log(`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`); console.log(`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
socket.end(); socket.end();
return; return;
} }
const targetHost = this.settings.toHost!; setupConnection('');
const connectionOptions: plugins.net.NetConnectOpts = {
host: targetHost,
port: this.settings.toPort,
};
if (this.settings.preserveSourceIP) {
connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
}
const to = plugins.net.connect(connectionOptions);
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}`);
socket.setTimeout(120000);
socket.pipe(to);
to.pipe(socket);
const errorHandler = () => {
cleanUpSockets(socket, to);
};
socket.on('error', errorHandler);
to.on('error', errorHandler);
socket.on('close', errorHandler);
to.on('close', errorHandler);
socket.on('timeout', errorHandler);
to.on('timeout', errorHandler);
socket.on('end', errorHandler);
to.on('end', errorHandler);
} }
}) })
.on('error', (err: Error) => { .on('error', (err: Error) => {
@ -267,6 +300,11 @@ export class PortProxy {
.listen(this.settings.fromPort, () => { .listen(this.settings.fromPort, () => {
console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`); console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`);
}); });
// Log active connection count every 10 seconds.
this.connectionLogger = setInterval(() => {
console.log(`(Interval Log) Active connections: ${this.activeConnections.size}`);
}, 10000);
} }
public async stop() { public async stop() {
@ -274,6 +312,10 @@ export class PortProxy {
this.netServer.close(() => { this.netServer.close(() => {
done.resolve(); done.resolve();
}); });
if (this.connectionLogger) {
clearInterval(this.connectionLogger);
this.connectionLogger = null;
}
await done.promise; await done.promise;
} }
} }