Compare commits

...

14 Commits

7 changed files with 235 additions and 48 deletions

View File

@ -1,5 +1,53 @@
# Changelog
## 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.4.4",
"private": false,
"description": "a proxy for handling high workloads of proxying",
"main": "dist_ts/index.js",
@ -30,7 +30,9 @@
"@push.rocks/smartstring": "^4.0.15",
"@tsclass/tsclass": "^4.4.0",
"@types/ws": "^8.5.14",
"ws": "^8.18.0"
"ws": "^8.18.0",
"minimatch": "^9.0.3",
"@types/minimatch": "^5.1.2"
},
"files": [
"ts/**/*",

6
pnpm-lock.yaml generated
View File

@ -26,9 +26,15 @@ 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
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,28 @@ 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 handle multiple concurrent connections', async () => {
const concurrentRequests = 5;
const requests = Array(concurrentRequests).fill(null).map((_, i) =>

View File

@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartproxy',
version: '3.2.0',
version: '3.4.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';
@ -23,5 +24,6 @@ export { lik, smartdelay, smartrequest, smartpromise, smartstring };
// third party scope
import * as ws from 'ws';
import wsDefault from 'ws';
import { minimatch } from 'minimatch';
export { wsDefault, ws };
export { wsDefault, ws, minimatch };

View File

@ -1,14 +1,32 @@
import * as plugins from './smartproxy.plugins.js';
import * as net from 'net';
export class PortProxy {
netServer: plugins.net.Server;
export interface DomainConfig {
domain: string; // glob pattern for domain
allowedIPs: string[]; // glob patterns for IPs allowed to access this domain
}
export interface ProxySettings extends plugins.tls.TlsOptions {
// Port configuration
fromPort: number;
toPort: number;
toHost?: string; // Target host to proxy to, defaults to 'localhost'
constructor(fromPortArg: number, toPortArg: number) {
this.fromPort = fromPortArg;
this.toPort = toPortArg;
// Domain and security settings
domains: DomainConfig[];
sniEnabled?: boolean;
defaultAllowedIPs?: string[]; // Optional default IP patterns if no matching domain found
}
export class PortProxy {
netServer: plugins.net.Server | plugins.tls.Server;
settings: ProxySettings;
constructor(settings: ProxySettings) {
this.settings = {
...settings,
toHost: settings.toHost || 'localhost'
};
}
public async start() {
@ -22,42 +40,129 @@ export class PortProxy {
from.destroy();
to.destroy();
};
this.netServer = net
.createServer((from) => {
const to = net.createConnection({
host: 'localhost',
port: this.toPort,
});
from.setTimeout(120000);
from.pipe(to);
to.pipe(from);
from.on('error', () => {
cleanUpSockets(from, to);
});
to.on('error', () => {
cleanUpSockets(from, to);
});
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);
});
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 (ip.match(/^\d{1,3}(\.\d{1,3}){3}$/)) {
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): DomainConfig | undefined => {
return this.settings.domains.find(config => plugins.minimatch(serverName, config.domain));
};
const server = this.settings.sniEnabled
? plugins.tls.createServer({
...this.settings,
SNICallback: (serverName: string, cb: (err: Error | null, ctx?: plugins.tls.SecureContext) => void) => {
console.log(`SNI request for domain: ${serverName}`);
const domainConfig = findMatchingDomain(serverName);
if (!domainConfig) {
// Always allow SNI for default IPs, even if domain doesn't match
console.log(`SNI domain ${serverName} not found, will check IP during connection`);
}
// Create context with the provided TLS settings
const ctx = plugins.tls.createSecureContext(this.settings);
cb(null, ctx);
}
})
: plugins.net.createServer();
const handleConnection = (from: plugins.net.Socket | plugins.tls.TLSSocket) => {
const remoteIP = from.remoteAddress || '';
let serverName = '';
// First check if this IP is in the default allowed list
const isDefaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
if (this.settings.sniEnabled && from instanceof plugins.tls.TLSSocket) {
serverName = (from as any).servername || '';
console.log(`TLS Connection from ${remoteIP} for domain: ${serverName}`);
}
// If IP is in defaultAllowedIPs, allow the connection regardless of SNI
if (isDefaultAllowed) {
console.log(`Connection allowed: IP ${remoteIP} is in default allowed list`);
} else if (this.settings.sniEnabled && serverName) {
// For SNI connections that aren't in default list, check domain-specific rules
const domainConfig = findMatchingDomain(serverName);
if (!domainConfig) {
console.log(`Connection rejected: No matching domain config for ${serverName} from IP ${remoteIP}`);
from.end();
return;
}
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
console.log(`Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
from.end();
return;
}
} else {
// Non-SNI connection and not in default list
console.log(`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
from.end();
return;
}
const to = plugins.net.createConnection({
host: this.settings.toHost!,
port: this.settings.toPort,
});
console.log(`Connection established: ${remoteIP} -> ${this.settings.toHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`);
from.setTimeout(120000);
from.pipe(to);
to.pipe(from);
from.on('error', () => {
cleanUpSockets(from, to);
});
to.on('error', () => {
cleanUpSockets(from, to);
});
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);
});
};
this.netServer = server
.on('connection', handleConnection)
.on('secureConnection', handleConnection)
.on('tlsClientError', (err, tlsSocket) => {
console.log(`TLS Client Error: ${err.message}`);
})
.listen(this.fromPort);
console.log(`PortProxy -> OK: Now listening on port ${this.fromPort}`);
.on('error', (err) => {
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 enabled)' : ''}`);
}
public async stop() {