Compare commits

...

40 Commits

Author SHA1 Message Date
2df2f0ceaf 3.9.4 2025-02-22 05:41:29 +00:00
2b266ca779 fix(PortProxy): Ensure proper cleanup on connection rejection in PortProxy 2025-02-22 05:41:29 +00:00
c2547036fd 3.9.3 2025-02-21 23:57:54 +00:00
a8131ece26 fix(PortProxy): Fix handling of optional outgoing socket in PortProxy 2025-02-21 23:57:54 +00:00
ad8c667dec 3.9.2 2025-02-21 23:33:16 +00:00
942e0649c8 fix(PortProxy): Improve timeout handling for port proxy connections 2025-02-21 23:33:15 +00:00
59625167b4 3.9.1 2025-02-21 23:30:51 +00:00
385d984727 fix(dependencies): Ensure correct ordering of dependencies and improve logging format. 2025-02-21 23:30:51 +00:00
a959c2ad0e 3.9.0 2025-02-21 23:18:17 +00:00
88f5436c9a feat(smartproxy.portproxy): Add logging of connection durations to PortProxy 2025-02-21 23:18:17 +00:00
06101cd1b1 3.8.1 2025-02-21 23:11:14 +00:00
438d65107d fix(plugins): Simplified plugin import structure across codebase 2025-02-21 23:11:13 +00:00
233b26c308 3.8.0 2025-02-21 23:05:18 +00:00
ba787729e8 feat(PortProxy): Add active connection tracking and logging in PortProxy 2025-02-21 23:05:17 +00:00
4854d7c38d 3.7.3 2025-02-21 20:17:35 +00:00
e841bda003 fix(portproxy): Fix handling of connections in PortProxy to improve stability and performance. 2025-02-21 20:17:35 +00:00
477b930a37 3.7.2 2025-02-21 19:56:28 +00:00
935bd95723 fix(PortProxy): Improve SNICallback and connection handling in PortProxy 2025-02-21 19:56:28 +00:00
0e33ea4eb5 3.7.1 2025-02-21 19:53:20 +00:00
6181065963 fix(smartproxy.portproxy): Optimize SNI handling by simplifying context creation 2025-02-21 19:53:19 +00:00
1a586dcbd7 3.7.0 2025-02-21 19:44:59 +00:00
ee03224561 feat(PortProxy): Add optional source IP preservation support in PortProxy 2025-02-21 19:44:59 +00:00
483cbb3634 3.6.0 2025-02-21 19:39:52 +00:00
c77b31b72c feat(PortProxy): Add feature to preserve original client IP through chained proxies 2025-02-21 19:39:52 +00:00
8cb8fa1a52 3.5.0 2025-02-21 19:34:11 +00:00
8e5bb12edb feat(PortProxy): Enhance PortProxy to support domain-specific target IPs 2025-02-21 19:34:11 +00:00
9be9a426ad 3.4.4 2025-02-21 18:54:40 +00:00
32d875aed9 fix(PortProxy): Fixed handling of SNI domain connections and IP allowance checks 2025-02-21 18:54:40 +00:00
4747462cff 3.4.3 2025-02-21 18:48:39 +00:00
70f69ef1ea fix(PortProxy): Fixed indentation issue and ensured proper cleanup of sockets in PortProxy 2025-02-21 18:48:39 +00:00
2be1c57dd7 3.4.2 2025-02-21 18:47:18 +00:00
58bd6b4a85 fix(smartproxy): Enhance SSL/TLS handling with SNI and error logging 2025-02-21 18:47:18 +00:00
63e1cd48e8 3.4.1 2025-02-21 18:43:08 +00:00
5150ddc18e fix(PortProxy): Normalize IP addresses for port proxy to handle IPv4-mapped IPv6 addresses. 2025-02-21 18:43:08 +00:00
4bee483954 3.4.0 2025-02-21 17:01:02 +00:00
4328d4365f feat(PortProxy): Enhanced PortProxy with custom target host and improved testing 2025-02-21 17:01:02 +00:00
21e9d0fd0d 3.3.1 2025-02-21 15:17:20 +00:00
6c0c65bb1a fix(PortProxy): fixed import usage of net and tls libraries for PortProxy 2025-02-21 15:17:19 +00:00
23f61eb60b 3.3.0 2025-02-21 15:14:03 +00:00
a4ad6c59c1 feat(PortProxy): Enhanced PortProxy with domain and IP filtering, SNI support, and minimatch integration 2025-02-21 15:14:02 +00:00
10 changed files with 628 additions and 55 deletions

View File

@ -1,5 +1,135 @@
# Changelog
## 2025-02-22 - 3.9.4 - fix(PortProxy)
Ensure proper cleanup on connection rejection in PortProxy
- Added cleanup calls after socket end in connection rejection scenarios within PortProxy
## 2025-02-21 - 3.9.3 - fix(PortProxy)
Fix handling of optional outgoing socket in PortProxy
- Refactored the cleanUpSockets function to correctly handle cases where the outgoing socket may be undefined.
- Ensured correct handling of socket events with non-null assertions where applicable.
- Improved robustness in connection establishment and cleanup processes.
## 2025-02-21 - 3.9.2 - fix(PortProxy)
Improve timeout handling for port proxy connections
- Added console logging for both incoming and outgoing side timeouts in the PortProxy class.
- Updated the timeout event handlers to ensure proper cleanup of connections.
## 2025-02-21 - 3.9.1 - fix(dependencies)
Ensure correct ordering of dependencies and improve logging format.
- Reorder dependencies in package.json for better readability.
- Use pretty-ms for displaying time durations in logs.
## 2025-02-21 - 3.9.0 - feat(smartproxy.portproxy)
Add logging of connection durations to PortProxy
- Track start times for incoming and outgoing connections.
- Log duration of longest running incoming and outgoing connections every 10 seconds.
## 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)
Fix handling of connections in PortProxy to improve stability and performance.
- Improved IP normalization and matching
- Better SNI extraction and handling for TLS
- Streamlined connection handling with robust error management
## 2025-02-21 - 3.7.2 - fix(PortProxy)
Improve SNICallback and connection handling in PortProxy
- Fixed SNICallback to create minimal TLS context for SNI.
- Changed connection setup to use net.connect for raw passthrough.
## 2025-02-21 - 3.7.1 - fix(smartproxy.portproxy)
Optimize SNI handling by simplifying context creation
- Removed unnecessary SecureContext creation for SNI requests in PortProxy
- Improved handling of SNI passthrough by acknowledging requests without context creation
## 2025-02-21 - 3.7.0 - feat(PortProxy)
Add optional source IP preservation support in PortProxy
- Added a feature to optionally preserve the client's source IP when proxying connections.
- Enhanced test cases to include scenarios for source IP preservation.
## 2025-02-21 - 3.6.0 - feat(PortProxy)
Add feature to preserve original client IP through chained proxies
- Added support to bind local address in PortProxy to preserve original client IP.
- Implemented test for chained proxies to ensure client IP is preserved.
## 2025-02-21 - 3.5.0 - feat(PortProxy)
Enhance PortProxy to support domain-specific target IPs
- Introduced support for domain-specific target IP configurations in PortProxy.
- Updated connection handling to prioritize domain-specific target IPs if provided.
- Added tests to verify forwarding based on domain-specific target IPs.
## 2025-02-21 - 3.4.4 - fix(PortProxy)
Fixed handling of SNI domain connections and IP allowance checks
- Improved logic for handling SNI domain checks, ensuring IPs are correctly verified.
- Fixed issue where default allowed IPs were not being checked correctly for non-SNI connections.
- Revised the SNICallback behavior to handle connections more gracefully when domain configurations are unavailable.
## 2025-02-21 - 3.4.3 - fix(PortProxy)
Fixed indentation issue and ensured proper cleanup of sockets in PortProxy
- Fixed inconsistent indentation in IP allowance check.
- Ensured proper cleanup of sockets on connection end in PortProxy.
## 2025-02-21 - 3.4.2 - fix(smartproxy)
Enhance SSL/TLS handling with SNI and error logging
- Improved handling for SNI-enabled and non-SNI connections
- Added detailed logging for connection establishment and rejections
- Introduced error logging for TLS client errors and server errors
## 2025-02-21 - 3.4.1 - fix(PortProxy)
Normalize IP addresses for port proxy to handle IPv4-mapped IPv6 addresses.
- Improved IP normalization logic in PortProxy to support IPv4-mapped IPv6 addresses.
- Updated isAllowed function to expand patterns for better matching accuracy.
## 2025-02-21 - 3.4.0 - feat(PortProxy)
Enhanced PortProxy with custom target host and improved testing
- PortProxy constructor now accepts 'fromPort', 'toPort', and optional 'toHost' directly from settings
- Refactored test cases to cover forwarding to the custom host
- Added support to handle multiple concurrent connections
- Refactored internal connection handling logic to utilize default configurations
## 2025-02-21 - 3.3.1 - fix(PortProxy)
fixed import usage of net and tls libraries for PortProxy
- Corrected the use of plugins for importing 'tls' and 'net' libraries in the PortProxy module.
- Updated the constructor of PortProxy to accept combined tls options with ProxySettings.
## 2025-02-21 - 3.3.0 - feat(PortProxy)
Enhanced PortProxy with domain and IP filtering, SNI support, and minimatch integration
- Added new ProxySettings interface to configure domain patterns, SNI, and default allowed IPs.
- Integrated minimatch to filter allowed IPs and domains.
- Enabled SNI support for PortProxy connections.
- Updated port proxy test to accommodate new settings.
## 2025-02-04 - 3.2.0 - feat(testing)
Added a comprehensive test suite for the PortProxy class

View File

@ -1,6 +1,6 @@
{
"name": "@push.rocks/smartproxy",
"version": "3.2.0",
"version": "3.9.4",
"private": false,
"description": "a proxy for handling high workloads of proxying",
"main": "dist_ts/index.js",
@ -29,7 +29,10 @@
"@push.rocks/smartrequest": "^2.0.23",
"@push.rocks/smartstring": "^4.0.15",
"@tsclass/tsclass": "^4.4.0",
"@types/minimatch": "^5.1.2",
"@types/ws": "^8.5.14",
"minimatch": "^9.0.3",
"pretty-ms": "^9.2.0",
"ws": "^8.18.0"
},
"files": [

9
pnpm-lock.yaml generated
View File

@ -26,9 +26,18 @@ importers:
'@tsclass/tsclass':
specifier: ^4.4.0
version: 4.4.0
'@types/minimatch':
specifier: ^5.1.2
version: 5.1.2
'@types/ws':
specifier: ^8.5.14
version: 8.5.14
minimatch:
specifier: ^9.0.3
version: 9.0.5
pretty-ms:
specifier: ^9.2.0
version: 9.2.0
ws:
specifier: ^8.18.0
version: 8.18.0

View File

@ -58,7 +58,14 @@ function createTestClient(port: number, data: string): Promise<string> {
// Setup test environment
tap.test('setup port proxy test environment', async () => {
testServer = await createTestServer(TEST_SERVER_PORT);
portProxy = new PortProxy(PROXY_PORT, TEST_SERVER_PORT);
portProxy = new PortProxy({
fromPort: PROXY_PORT,
toPort: TEST_SERVER_PORT,
toHost: 'localhost',
domains: [],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1']
});
});
tap.test('should start port proxy', async () => {
@ -66,11 +73,76 @@ tap.test('should start port proxy', async () => {
expect(portProxy.netServer.listening).toBeTrue();
});
tap.test('should forward TCP connections and data', async () => {
tap.test('should forward TCP connections and data to localhost', async () => {
const response = await createTestClient(PROXY_PORT, TEST_DATA);
expect(response).toEqual(`Echo: ${TEST_DATA}`);
});
tap.test('should forward TCP connections to custom host', async () => {
// Create a new proxy instance with a custom host
const customHostProxy = new PortProxy({
fromPort: PROXY_PORT + 1,
toPort: TEST_SERVER_PORT,
toHost: '127.0.0.1',
domains: [],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1']
});
await customHostProxy.start();
const response = await createTestClient(PROXY_PORT + 1, TEST_DATA);
expect(response).toEqual(`Echo: ${TEST_DATA}`);
await customHostProxy.stop();
});
tap.test('should forward connections based on domain-specific target IP', async () => {
// Create a second test server on a different port
const TEST_SERVER_PORT_2 = TEST_SERVER_PORT + 100;
const testServer2 = await createTestServer(TEST_SERVER_PORT_2);
// Create a proxy with domain-specific target IPs
const domainProxy = new PortProxy({
fromPort: PROXY_PORT + 2,
toPort: TEST_SERVER_PORT, // default port
toHost: 'localhost', // default host
domains: [{
domain: 'domain1.test',
allowedIPs: ['127.0.0.1'],
targetIP: '127.0.0.1'
}, {
domain: 'domain2.test',
allowedIPs: ['127.0.0.1'],
targetIP: 'localhost'
}],
sniEnabled: false, // We'll test without SNI first since this is a TCP proxy test
defaultAllowedIPs: ['127.0.0.1']
});
await domainProxy.start();
// Test default connection (should use default host)
const response1 = await createTestClient(PROXY_PORT + 2, TEST_DATA);
expect(response1).toEqual(`Echo: ${TEST_DATA}`);
// Create another proxy with different default host
const domainProxy2 = new PortProxy({
fromPort: PROXY_PORT + 3,
toPort: TEST_SERVER_PORT,
toHost: '127.0.0.1',
domains: [],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1']
});
await domainProxy2.start();
const response2 = await createTestClient(PROXY_PORT + 3, TEST_DATA);
expect(response2).toEqual(`Echo: ${TEST_DATA}`);
await domainProxy.stop();
await domainProxy2.stop();
await new Promise<void>((resolve) => testServer2.close(() => resolve()));
});
tap.test('should handle multiple concurrent connections', async () => {
const concurrentRequests = 5;
const requests = Array(concurrentRequests).fill(null).map((_, i) =>
@ -103,6 +175,68 @@ tap.test('should stop port proxy', async () => {
});
// Cleanup
tap.test('should support optional source IP preservation in chained proxies', async () => {
// Test 1: Without IP preservation (default behavior)
const firstProxyDefault = new PortProxy({
fromPort: PROXY_PORT + 4,
toPort: PROXY_PORT + 5,
toHost: 'localhost',
domains: [],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1']
});
const secondProxyDefault = new PortProxy({
fromPort: PROXY_PORT + 5,
toPort: TEST_SERVER_PORT,
toHost: 'localhost',
domains: [],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1']
});
await secondProxyDefault.start();
await firstProxyDefault.start();
// This should work because we explicitly allow both IPv4 and IPv6 formats
const response1 = await createTestClient(PROXY_PORT + 4, TEST_DATA);
expect(response1).toEqual(`Echo: ${TEST_DATA}`);
await firstProxyDefault.stop();
await secondProxyDefault.stop();
// Test 2: With IP preservation
const firstProxyPreserved = new PortProxy({
fromPort: PROXY_PORT + 6,
toPort: PROXY_PORT + 7,
toHost: 'localhost',
domains: [],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1'],
preserveSourceIP: true
});
const secondProxyPreserved = new PortProxy({
fromPort: PROXY_PORT + 7,
toPort: TEST_SERVER_PORT,
toHost: 'localhost',
domains: [],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1'],
preserveSourceIP: true
});
await secondProxyPreserved.start();
await firstProxyPreserved.start();
// This should work with just IPv4 because source IP is preserved
const response2 = await createTestClient(PROXY_PORT + 6, TEST_DATA);
expect(response2).toEqual(`Echo: ${TEST_DATA}`);
await firstProxyPreserved.stop();
await secondProxyPreserved.stop();
});
tap.test('cleanup port proxy test environment', async () => {
await new Promise<void>((resolve) => testServer.close(() => resolve()));
});

View File

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

View File

@ -2,9 +2,10 @@
import * as http from 'http';
import * as https from 'https';
import * as net from 'net';
import * as tls from 'tls';
import * as url from 'url';
export { http, https, net, url };
export { http, https, net, tls, url };
// tsclass scope
import * as tsclass from '@tsclass/tsclass';
@ -21,7 +22,9 @@ import * as smartstring from '@push.rocks/smartstring';
export { lik, smartdelay, smartrequest, smartpromise, smartstring };
// third party scope
import prettyMs from 'pretty-ms';
import * as ws from 'ws';
import wsDefault from 'ws';
import { minimatch } from 'minimatch';
export { wsDefault, ws };
export { prettyMs, ws, wsDefault, minimatch };

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 * as fs from 'fs';
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 {
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 {
httpServer: plugins.http.Server;

View File

@ -1,63 +1,353 @@
import * as plugins from './smartproxy.plugins.js';
import * as net from 'net';
import * as plugins from './plugins.js';
export interface IDomainConfig {
domain: string; // glob pattern for domain
allowedIPs: string[]; // glob patterns for IPs allowed to access this domain
targetIP?: string; // Optional target IP for this domain
}
export interface IProxySettings extends plugins.tls.TlsOptions {
// Port configuration
fromPort: number;
toPort: number;
toHost?: string; // Target host to proxy to, defaults to 'localhost'
// Domain and security settings
domains: IDomainConfig[];
sniEnabled?: boolean;
defaultAllowedIPs?: string[]; // Optional default IP patterns if no matching domain found
preserveSourceIP?: boolean; // Whether to preserve the client's source IP when proxying
}
/**
* Extract SNI (Server Name Indication) from a TLS ClientHello packet.
* Returns the server name if found, or undefined.
*/
function extractSNI(buffer: Buffer): string | undefined {
let offset = 0;
// We need at least 5 bytes for the record header.
if (buffer.length < 5) {
return undefined;
}
// TLS record header
const recordType = buffer.readUInt8(0);
if (recordType !== 22) { // 22 = handshake
return undefined;
}
// Read record length
const recordLength = buffer.readUInt16BE(3);
if (buffer.length < 5 + recordLength) {
// Not all data arrived yet; in production you might need to accumulate more data.
return undefined;
}
offset = 5;
// Handshake message type should be 1 for ClientHello.
const handshakeType = buffer.readUInt8(offset);
if (handshakeType !== 1) {
return undefined;
}
// Skip handshake header (1 byte type + 3 bytes length)
offset += 4;
// Skip client version (2 bytes) and random (32 bytes)
offset += 2 + 32;
// Session ID
const sessionIDLength = buffer.readUInt8(offset);
offset += 1 + sessionIDLength;
// Cipher suites
const cipherSuitesLength = buffer.readUInt16BE(offset);
offset += 2 + cipherSuitesLength;
// Compression methods
const compressionMethodsLength = buffer.readUInt8(offset);
offset += 1 + compressionMethodsLength;
// Extensions length
if (offset + 2 > buffer.length) {
return undefined;
}
const extensionsLength = buffer.readUInt16BE(offset);
offset += 2;
const extensionsEnd = offset + extensionsLength;
// Iterate over extensions
while (offset + 4 <= extensionsEnd) {
const extensionType = buffer.readUInt16BE(offset);
const extensionLength = buffer.readUInt16BE(offset + 2);
offset += 4;
// Check for SNI extension (type 0)
if (extensionType === 0x0000) {
// SNI extension: first 2 bytes are the SNI list length.
if (offset + 2 > buffer.length) {
return undefined;
}
const sniListLength = buffer.readUInt16BE(offset);
offset += 2;
const sniListEnd = offset + sniListLength;
// Loop through the list; typically there is one entry.
while (offset + 3 < sniListEnd) {
const nameType = buffer.readUInt8(offset);
offset++;
const nameLen = buffer.readUInt16BE(offset);
offset += 2;
if (nameType === 0) { // host_name
if (offset + nameLen > buffer.length) {
return undefined;
}
const serverName = buffer.toString('utf8', offset, offset + nameLen);
return serverName;
}
offset += nameLen;
}
break;
} else {
offset += extensionLength;
}
}
return undefined;
}
export class PortProxy {
netServer: plugins.net.Server;
fromPort: number;
toPort: number;
settings: IProxySettings;
// Track active incoming connections
private activeConnections: Set<plugins.net.Socket> = new Set();
// Record start times for incoming connections
private incomingConnectionTimes: Map<plugins.net.Socket, number> = new Map();
// Record start times for outgoing connections
private outgoingConnectionTimes: Map<plugins.net.Socket, number> = new Map();
private connectionLogger: NodeJS.Timeout | null = null;
constructor(fromPortArg: number, toPortArg: number) {
this.fromPort = fromPortArg;
this.toPort = toPortArg;
constructor(settings: IProxySettings) {
this.settings = {
...settings,
toHost: settings.toHost || 'localhost'
};
}
public async start() {
const cleanUpSockets = (from: plugins.net.Socket, to: plugins.net.Socket) => {
// Adjusted cleanUpSockets to allow an optional outgoing socket.
const cleanUpSockets = (from: plugins.net.Socket, to?: plugins.net.Socket) => {
from.end();
to.end();
from.removeAllListeners();
to.removeAllListeners();
from.unpipe();
to.unpipe();
from.destroy();
to.destroy();
if (to) {
to.end();
to.removeAllListeners();
to.unpipe();
to.destroy();
}
};
this.netServer = net
.createServer((from) => {
const to = net.createConnection({
host: 'localhost',
port: this.toPort,
const normalizeIP = (ip: string): string[] => {
// Handle IPv4-mapped IPv6 addresses
if (ip.startsWith('::ffff:')) {
const ipv4 = ip.slice(7); // Remove '::ffff:' prefix
return [ip, ipv4];
}
// Handle IPv4 addresses by adding IPv4-mapped IPv6 variant
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) {
return [ip, `::ffff:${ip}`];
}
return [ip];
};
const isAllowed = (value: string, patterns: string[]): boolean => {
// Expand patterns to include both IPv4 and IPv6 variants
const expandedPatterns = patterns.flatMap(normalizeIP);
// Check if any variant of the IP matches any expanded pattern
return normalizeIP(value).some(ip =>
expandedPatterns.some(pattern => plugins.minimatch(ip, pattern))
);
};
const findMatchingDomain = (serverName: string): IDomainConfig | undefined => {
return this.settings.domains.find(config => plugins.minimatch(serverName, config.domain));
};
// Create a plain net server for TLS passthrough.
this.netServer = plugins.net.createServer((socket: plugins.net.Socket) => {
const remoteIP = socket.remoteAddress || '';
// Record start time for the incoming connection.
this.activeConnections.add(socket);
this.incomingConnectionTimes.set(socket, Date.now());
console.log(`New connection from ${remoteIP}. Active connections: ${this.activeConnections.size}`);
// Flag to detect if we've received the first data chunk.
let initialDataReceived = false;
// 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}`);
}
});
// Flag to ensure cleanup happens only once.
let connectionClosed = false;
const cleanupOnce = () => {
if (!connectionClosed) {
connectionClosed = true;
cleanUpSockets(socket, to || undefined);
this.incomingConnectionTimes.delete(socket);
if (to) {
this.outgoingConnectionTimes.delete(to);
}
if (this.activeConnections.has(socket)) {
this.activeConnections.delete(socket);
console.log(`Connection from ${remoteIP} terminated. Active connections: ${this.activeConnections.size}`);
}
}
};
// Declare the outgoing connection as possibly null.
let to: plugins.net.Socket | null = null;
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.
const isDefaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
if (!isDefaultAllowed && serverName) {
const domainConfig = findMatchingDomain(serverName);
if (!domainConfig) {
console.log(`Connection rejected: No matching domain config for ${serverName} from ${remoteIP}`);
socket.end();
cleanupOnce();
return;
}
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
console.log(`Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
socket.end();
cleanupOnce();
return;
}
} else if (!isDefaultAllowed && !serverName) {
console.log(`Connection rejected: No SNI and IP ${remoteIP} not in default allowed list`);
socket.end();
cleanupOnce();
return;
} else {
console.log(`Connection allowed: IP ${remoteIP} is in default allowed list`);
}
// Determine target host.
const domainConfig = serverName ? findMatchingDomain(serverName) : undefined;
const targetHost = domainConfig?.targetIP || this.settings.toHost!;
// Create connection options.
const connectionOptions: plugins.net.NetConnectOpts = {
host: targetHost,
port: this.settings.toPort,
};
if (this.settings.preserveSourceIP) {
connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
}
// Establish outgoing connection.
to = plugins.net.connect(connectionOptions);
// Record start time for the outgoing connection.
if (to) {
this.outgoingConnectionTimes.set(to, Date.now());
}
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`);
// Push back the initial chunk if provided.
if (initialChunk) {
socket.unshift(initialChunk);
}
socket.setTimeout(120000);
// Since 'to' is not null here, we can use the non-null assertion.
socket.pipe(to!);
to!.pipe(socket);
// Attach error and close handlers for both sockets.
socket.on('error', handleError('incoming'));
to!.on('error', handleError('outgoing'));
socket.on('close', handleClose('incoming'));
to!.on('close', handleClose('outgoing'));
socket.on('timeout', () => {
console.log(`Timeout on incoming side from ${remoteIP}`);
cleanupOnce();
});
from.setTimeout(120000);
from.pipe(to);
to.pipe(from);
from.on('error', () => {
cleanUpSockets(from, to);
to!.on('timeout', () => {
console.log(`Timeout on outgoing side from ${remoteIP}`);
cleanupOnce();
});
to.on('error', () => {
cleanUpSockets(from, to);
socket.on('end', handleClose('incoming'));
to!.on('end', handleClose('outgoing'));
};
// For SNI-enabled connections, peek at the first chunk.
if (this.settings.sniEnabled) {
socket.once('data', (chunk: Buffer) => {
initialDataReceived = true;
// Try to extract the server name from the ClientHello.
const serverName = extractSNI(chunk) || '';
console.log(`Received connection from ${remoteIP} with SNI: ${serverName}`);
setupConnection(serverName, chunk);
});
from.on('close', () => {
cleanUpSockets(from, to);
});
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);
});
})
.listen(this.fromPort);
console.log(`PortProxy -> OK: Now listening on port ${this.fromPort}`);
} else {
// For non-SNI connections, simply check defaultAllowedIPs.
initialDataReceived = true;
if (!this.settings.defaultAllowedIPs || !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
console.log(`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
socket.end();
cleanupOnce();
return;
}
setupConnection('');
}
})
.on('error', (err: Error) => {
console.log(`Server Error: ${err.message}`);
})
.listen(this.settings.fromPort, () => {
console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`);
});
// Log active connection count and longest running connections every 10 seconds.
this.connectionLogger = setInterval(() => {
const now = Date.now();
let maxIncoming = 0;
for (const startTime of this.incomingConnectionTimes.values()) {
const duration = now - startTime;
if (duration > maxIncoming) {
maxIncoming = duration;
}
}
let maxOutgoing = 0;
for (const startTime of this.outgoingConnectionTimes.values()) {
const duration = now - startTime;
if (duration > maxOutgoing) {
maxOutgoing = duration;
}
}
console.log(`(Interval Log) Active connections: ${this.activeConnections.size}. Longest running incoming: ${plugins.prettyMs(maxIncoming)}, outgoing: ${plugins.prettyMs(maxOutgoing)}`);
}, 10000);
}
public async stop() {
@ -65,6 +355,10 @@ export class PortProxy {
this.netServer.close(() => {
done.resolve();
});
if (this.connectionLogger) {
clearInterval(this.connectionLogger);
this.connectionLogger = null;
}
await done.promise;
}
}
}