Compare commits

...

22 Commits

Author SHA1 Message Date
3ab483d164 3.21.0 2025-03-03 01:42:16 +00:00
fcd80dc56b feat(PortProxy): Enhancements to connection management in PortProxy 2025-03-03 01:42:16 +00:00
8ddffcd6e5 3.20.2 2025-03-01 20:31:50 +00:00
a5a7781c17 fix(PortProxy): Enhance connection cleanup handling in PortProxy 2025-03-01 20:31:50 +00:00
d647e77cdf 3.20.1 2025-03-01 17:32:31 +00:00
9161336197 fix(PortProxy): Improve IP allowance check for forced domains 2025-03-01 17:32:31 +00:00
2e63d13dd4 3.20.0 2025-03-01 17:19:27 +00:00
af6ed735d5 feat(PortProxy): Enhance PortProxy with advanced connection cleanup and logging 2025-03-01 17:19:27 +00:00
7d38f29ef3 3.19.0 2025-03-01 13:17:05 +00:00
0df26d4367 feat(PortProxy): Enhance PortProxy with default blocked IPs 2025-03-01 13:17:05 +00:00
f9a6e2d748 3.18.2 2025-02-27 21:25:03 +00:00
1cb6302750 fix(portproxy): Fixed typographical errors in comments within PortProxy class. 2025-02-27 21:25:03 +00:00
f336f25535 3.18.1 2025-02-27 21:19:34 +00:00
5d6b707440 fix(PortProxy): Refactor and enhance PortProxy test cases and handling 2025-02-27 21:19:34 +00:00
622ad2ff20 3.18.0 2025-02-27 20:59:29 +00:00
dd23efd28d feat(PortProxy): Add SNI-based renegotiation handling in PortProxy 2025-02-27 20:59:29 +00:00
0ddf68a919 3.17.1 2025-02-27 20:10:26 +00:00
ec08ca51f5 fix(PortProxy): Fix handling of SNI re-negotiation in PortProxy 2025-02-27 20:10:26 +00:00
29688d1379 3.17.0 2025-02-27 19:57:28 +00:00
c83f6fa278 feat(smartproxy): Enhance description clarity and improve SNI handling with domain locking. 2025-02-27 19:57:27 +00:00
60333b0a59 3.16.9 2025-02-27 15:46:14 +00:00
1aa409907b fix(portproxy): Extend domain input validation to support string arrays in port proxy configurations. 2025-02-27 15:46:14 +00:00
7 changed files with 944 additions and 520 deletions

View File

@ -1,5 +1,81 @@
# Changelog
## 2025-03-03 - 3.21.0 - feat(PortProxy)
Enhancements to connection management in PortProxy
- Introduced a unique ID for each connection record for improved tracking.
- Enhanced cleanup mechanism for connections with dual states: initiated and executed.
- Implemented shutdown process handling to ensure graceful connection closure.
- Added logging for better tracing of connection activities and states.
- Improved connection setup with explicit timeouts and data flow management.
- Integrated inactivity and parity checks to monitor connection health.
## 2025-03-01 - 3.20.2 - fix(PortProxy)
Enhance connection cleanup handling in PortProxy
- Add checks to ensure timers are reset only if outgoing socket is active
- Prevent setting outgoingActive if the connection is already closed
## 2025-03-01 - 3.20.1 - fix(PortProxy)
Improve IP allowance check for forced domains
- Enhanced IP allowance check logic by incorporating blocked IPs and default allowed IPs for forced domains within port proxy configurations.
## 2025-03-01 - 3.20.0 - feat(PortProxy)
Enhance PortProxy with advanced connection cleanup and logging
- Introduced `cleanupConnection` method for improved connection management.
- Added logging for connection cleanup including special conditions.
- Implemented parity check to clean up connections when outgoing side closes but incoming remains active.
- Improved logging during interval checks for active connections and their durations.
## 2025-03-01 - 3.19.0 - feat(PortProxy)
Enhance PortProxy with default blocked IPs
- Introduced defaultBlockedIPs in IPortProxySettings to handle globally blocked IPs.
- Added logic for merging domain-specific and default allowed and blocked IPs for effective IP filtering.
- Refactored helper functions for IP and port range checks to improve modularity in PortProxy.
## 2025-02-27 - 3.18.2 - fix(portproxy)
Fixed typographical errors in comments within PortProxy class.
- Corrected typographical errors in comments within the PortProxy class.
## 2025-02-27 - 3.18.1 - fix(PortProxy)
Refactor and enhance PortProxy test cases and handling
- Refactored test cases in test/test.portproxy.ts for clarity and added coverage.
- Improved TCP server helper functions for better flexibility.
- Fixed issues with domain handling in PortProxy configuration.
- Introduced round-robin logic for multi-IP domains in PortProxy.
- Ensured proper cleanup and stopping of test servers in the test suite.
## 2025-02-27 - 3.18.0 - feat(PortProxy)
Add SNI-based renegotiation handling in PortProxy
- Introduced a new field 'lockedDomain' in IConnectionRecord to store initial SNI.
- Enhanced connection management by enforcing termination if rehandshake is detected with different SNI.
## 2025-02-27 - 3.17.1 - fix(PortProxy)
Fix handling of SNI re-negotiation in PortProxy
- Removed connection locking to the initially negotiated SNI
- Improved handling of SNI during renegotiation in PortProxy
## 2025-02-27 - 3.17.0 - feat(smartproxy)
Enhance description clarity and improve SNI handling with domain locking.
- Improved package description in package.json, readme.md, and npmextra.json for better clarity and keyword optimization.
- Enhanced SNI handling in PortProxy by adding domain locking and extra checks to terminate connections if a different SNI is detected post-handshake.
- Refactored readme.md to better explain the usage and functionalities of the proxy features including SSL redirection, WebSocket handling, and dynamic routing.
## 2025-02-27 - 3.16.9 - fix(portproxy)
Extend domain input validation to support string arrays in port proxy configurations.
- Modify IDomainConfig interface to allow domain specification as string array.
- Update connection setup logic to handle multiple domain patterns.
- Enhance domain rejection logging to include all domain patterns.
## 2025-02-27 - 3.16.8 - fix(PortProxy)
Fix IP filtering for domain and global default allowed lists and improve port-based routing logic.

View File

@ -5,26 +5,26 @@
"githost": "code.foss.global",
"gitscope": "push.rocks",
"gitrepo": "smartproxy",
"description": "A robust and versatile proxy package designed to handle high workloads, offering features like SSL redirection, port proxying, WebSocket support, and customizable routing and authentication.",
"description": "A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.",
"npmPackagename": "@push.rocks/smartproxy",
"license": "MIT",
"projectDomain": "push.rocks",
"keywords": [
"proxy",
"network traffic",
"high workload",
"http",
"https",
"websocket",
"network routing",
"ssl redirect",
"port mapping",
"reverse proxy",
"authentication",
"network",
"traffic management",
"SSL",
"TLS",
"WebSocket",
"port proxying",
"dynamic routing",
"sni",
"port forwarding",
"real-time applications"
"authentication",
"real-time applications",
"high workload",
"HTTPS",
"reverse proxy",
"server",
"network security"
]
}
},

View File

@ -1,8 +1,8 @@
{
"name": "@push.rocks/smartproxy",
"version": "3.16.8",
"version": "3.21.0",
"private": false,
"description": "A robust and versatile proxy package designed to handle high workloads, offering features like SSL redirection, port proxying, WebSocket support, and customizable routing and authentication.",
"description": "A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.",
"main": "dist_ts/index.js",
"typings": "dist_ts/index.d.ts",
"type": "module",
@ -53,20 +53,20 @@
],
"keywords": [
"proxy",
"network traffic",
"high workload",
"http",
"https",
"websocket",
"network routing",
"ssl redirect",
"port mapping",
"reverse proxy",
"authentication",
"network",
"traffic management",
"SSL",
"TLS",
"WebSocket",
"port proxying",
"dynamic routing",
"sni",
"port forwarding",
"real-time applications"
"authentication",
"real-time applications",
"high workload",
"HTTPS",
"reverse proxy",
"server",
"network security"
],
"homepage": "https://code.foss.global/push.rocks/smartproxy#readme",
"repository": {

127
readme.md
View File

@ -1,6 +1,6 @@
# @push.rocks/smartproxy
A proxy for handling high workloads of proxying.
A robust and versatile proxy package designed to handle high workloads, offering features like SSL redirection, port proxying, WebSocket support, and customizable routing and authentication.
## Install
@ -14,19 +14,19 @@ This will add `@push.rocks/smartproxy` to your project's dependencies.
## Usage
`@push.rocks/smartproxy` is a comprehensive and versatile package designed to handle complex and high-volume proxying tasks efficiently. It includes features such as SSL redirection, port proxying, WebSocket support, and customizable routing and authentication mechanisms. This guide will provide a detailed walkthrough of how to harness these capabilities effectively.
`@push.rocks/smartproxy` is a comprehensive package that provides advanced functionalities for handling proxy tasks efficiently, including SSL redirection, port proxying, WebSocket support, and dynamic routing with authentication capabilities. Here is an extensive guide on how to utilize these features effectively, ensuring robust and secure proxy operations.
### Initial Setup
Before diving into specific features, let's start by configuring and setting up our basic proxy server:
Before exploring the advanced features of `smartproxy`, you need to set up a basic proxy server. This setup serves as the foundation for incorporating additional functionalities later on:
```typescript
import { NetworkProxy } from '@push.rocks/smartproxy';
// Instantiate the NetworkProxy with desired options
// Create an instance of NetworkProxy with the desired configuration
const myNetworkProxy = new NetworkProxy({ port: 443 });
// Define reverse proxy configurations
// Define reverse proxy configurations for the domains you wish to proxy
const proxyConfigs = [
{
destinationIp: '127.0.0.1',
@ -39,16 +39,16 @@ PRIVATE_KEY_CONTENT
CERTIFICATE_CONTENT
-----END CERTIFICATE-----`,
},
// More configurations can be added here
// Additional configurations can be added here
];
// Start the network proxy
// Start the network proxy to enable forwarding
await myNetworkProxy.start();
// Apply proxy configurations
// Apply the configurations you defined earlier
await myNetworkProxy.updateProxyConfigs(proxyConfigs);
// Optionally add default headers to all responses
// Optionally, you can set default headers to be included in all responses
await myNetworkProxy.addDefaultHeaders({
'X-Powered-By': 'smartproxy',
});
@ -56,44 +56,45 @@ await myNetworkProxy.addDefaultHeaders({
### Configuring SSL Redirection
One essential capability of a robust proxy server is ensuring that all HTTP traffic is redirected to secure HTTPS endpoints. This can be effortlessly accomplished using the `SslRedirect` class within `smartproxy`. This class listens on port 80 (HTTP) and redirects all incoming requests to HTTPS:
A critical feature of modern proxy servers is the ability to redirect HTTP traffic to secure HTTPS endpoints. The `SslRedirect` class in `smartproxy` simplifies this process by automatically redirecting requests from HTTP port 80 to HTTPS:
```typescript
import { SslRedirect } from '@push.rocks/smartproxy';
// Instantiate the SslRedirect for listening on port 80
// Create an SslRedirect instance to listen on port 80
const mySslRedirect = new SslRedirect(80);
// Start listening and redirect HTTP traffic to HTTPS
// Start the redirect to enforce HTTPS
await mySslRedirect.start();
// To stop redirection, you can use the following command:
// To stop HTTP redirection, use the following command:
await mySslRedirect.stop();
```
### Handling Complex Networking with Port Proxy
### Managing Port Proxying
Port proxying allows redirection of traffic from one port to another. This capability is crucial when dealing with services that need dynamic port forwarding, or when adapting to infrastructure changes without downtime. Smartproxy's `PortProxy` class handles this efficiently:
Port proxying is essential for forwarding traffic from one port to another, an important feature for services that require dynamic port changes without downtime. Smartproxy's `PortProxy` class efficiently handles these scenarios:
```typescript
import { PortProxy } from '@push.rocks/smartproxy';
// Create a PortProxy to directly forward traffic from port 5000 to 3000
// Set up a PortProxy to forward traffic from port 5000 to 3000
const myPortProxy = new PortProxy(5000, 3000);
// Initiate the port proxy
await myPortProxy.start();
// To stop the port proxy mechanism:
// To halt the port proxy, execute:
await myPortProxy.stop();
```
Additionally, smartproxy's port proxying can support intricate scenarios where different forwarding rules are configured based on domain names or allowed IPs:
For more intricate setups—such as forwarding based on specific domain rules or IP allowances—smartproxy allows detailed configurations:
```typescript
import { PortProxy } from '@push.rocks/smartproxy';
const myComplexPortProxy = new PortProxy({
// Configure complex port proxy rules
const advancedPortProxy = new PortProxy({
fromPort: 6000,
toPort: 3000,
domains: [
@ -102,57 +103,60 @@ const myComplexPortProxy = new PortProxy({
allowedIPs: ['192.168.0.*', '127.0.0.1'],
targetIP: '192.168.1.100'
}
// Define more domain-specific rules if needed
// Additional domain rules can be added as needed
],
sniEnabled: true, // if SNI (Server Name Indication) is desired
defaultAllowedIPs: ['*']);
sniEnabled: true, // Server Name Indication (SNI) support
defaultAllowedIPs: ['*'],
});
// Start listening for complex routing requests
await myComplexPortProxy.start();
// Activate the proxy with conditional rules
await advancedPortProxy.start();
```
### WebSocket Support and Load Handling
### WebSocket Handling
With the advent of real-time applications, efficient WebSocket handling in proxies is crucial. Smartproxy integrates WebSocket support seamlessly, enabling it to proxy WebSocket traffic while maintaining security and performance:
With real-time applications becoming more prevalent, effective WebSocket handling is crucial in a proxy server. Smartproxy natively incorporates WebSocket support to manage WebSocket traffic securely and efficiently:
```typescript
import { NetworkProxy } from '@push.rocks/smartproxy';
const wsProxy = new NetworkProxy({ port: 443 });
// Create a NetworkProxy instance for WebSocket traffic
const wsNetworkProxy = new NetworkProxy({ port: 443 });
// Assume reverse proxy configurations with WebSocket intentions
const wsProxyConfigs = [
// Define proxy configurations targeted for WebSocket traffic
const websocketConfig = [
{
destinationIp: '127.0.0.1',
destinationPort: '8080',
hostName: 'socket.example.com',
// Add further options such as keys for SSL if needed
// Include SSL details if necessary
}
];
// Start the network proxy with WebSocket capabilities
await wsProxy.start();
await wsProxy.updateProxyConfigs(wsProxyConfigs);
// Start the proxy and apply WebSocket settings
await wsNetworkProxy.start();
await wsNetworkProxy.updateProxyConfigs(websocketConfig);
// Ensure WebSocket connections remain alive
wsProxy.heartbeatInterval = setInterval(() => {
// logic for keeping connections alive and healthy
}, 60000); // Every 60 seconds
// Set heartbeat intervals to maintain WebSocket connections
wsNetworkProxy.heartbeatInterval = setInterval(() => {
// Logic for connection health checks
}, 60000); // every minute
// Gracefully handle server or connection errors to maintain uptime
wsProxy.httpsServer.on('error', (error) => console.log('Server Error:', error));
// Capture and handle server errors for resiliency
wsNetworkProxy.httpsServer.on('error', (error) => console.log('Server Error:', error));
```
### Comprehensive Routing and Advanced Features
### Advanced Routing and Custom Features
Smartproxy supports dynamic and customizable request routing based on the incoming request's destination. This feature enables extensive use-case scenarios, from simple API endpoint redirection to elaborate B2B service integrations:
Smartproxy shines with its dynamic routing capabilities, allowing for custom and advanced request routing based on the request's destination. This enables extensive flexibility, such as directing API requests or facilitating intricate B2B integrations:
```typescript
import { NetworkProxy } from '@push.rocks/smartproxy';
const dynamicRoutingProxy = new NetworkProxy({ port: 8443 });
dynamicRoutingProxy.router.setNewProxyConfigs([
// Instantiate a proxy with dynamic routing
const routeProxy = new NetworkProxy({ port: 8443 });
routeProxy.router.setNewProxyConfigs([
{
destinationIp: '192.168.1.150',
destinationPort: '80',
@ -165,57 +169,60 @@ dynamicRoutingProxy.router.setNewProxyConfigs([
}
]);
await dynamicRoutingProxy.start();
// Activate the routing proxy
await routeProxy.start();
```
For those dealing with high volume or regulatory needs, the integration of tools like `iptables` allows broad control over network traffic:
For those who require granular traffic control, integrating tools like `iptables` offers additional power over network management:
```typescript
import { IPTablesProxy } from '@push.rocks/smartproxy';
// Setting up iptables for advanced network management
const ipTablesProxy = new IPTablesProxy({
// Set up IPTables for sophisticated network traffic management
const iptablesProxy = new IPTablesProxy({
fromPort: 8081,
toPort: 8080,
deleteOnExit: true // clean rules upon server shutdown
deleteOnExit: true // Clean up rules when the server shuts down
});
// Begin routing with IPTables
await ipTablesProxy.start();
// Enable routing through IPTables
await iptablesProxy.start();
```
### Combining with HTTP and HTTPS Credentials
### Integrating SSL and HTTP/HTTPS Credentials
When undertaking proxy configurations, handling sensitive data like SSL certificates and keys securely is imperative:
Handling sensitive data like SSL keys and certificates securely is crucial in proxy configurations:
```typescript
import { loadDefaultCertificates } from '@push.rocks/smartproxy';
try {
const { privateKey, publicKey } = loadDefaultCertificates(); // adjust path as needed
console.log('Certificates loaded.');
// Use these certificates in your SSL-based configurations
const { privateKey, publicKey } = loadDefaultCertificates(); // Adjust path if necessary
console.log('SSL certificates loaded successfully.');
// Use these credentials in your configurations
} catch (error) {
console.error('Cannot load certificates:', error);
console.error('Error loading certificates:', error);
}
```
### Testing and Validation
Given these powerful capabilities, rigorous testing of configurations and functionality using frameworks like `tap` can ensure high-quality and reliable proxy configurations. Smartproxy integrates with Typescript test setups:
Smartproxy supports extensive testing to ensure your proxy configurations operate as expected. Leveraging `tap` alongside TypeScript testing frameworks supports quality assurance:
```typescript
import { expect, tap } from '@push.rocks/tapbundle';
import { NetworkProxy } from '@push.rocks/smartproxy';
tap.test('proxied request should return status 200', async () => {
// Your test logic here
tap.test('Check proxied request returns status 200', async () => {
// Testing logic
});
tap.start();
```
In summary, `@push.rocks/smartproxy` offers a plethora of solutions tailored to both common and sophisticated proxying needs. Whether you're seeking straightforward port forwarding, secure SSL redirection, WebSocket management, or robust network routing controls, smartproxy provides the right tools for efficient and effective proxy operations. Through its integration simplicity and versatile configurations, developers can ensure high performance and secure proxying across various environments and applications.
### Conclusion
`@push.rocks/smartproxy` is designed for both simple and complex proxying demands, offering tools for high-performance and secure proxy management across diverse environments. Its efficient configurations are capable of supporting SSL redirection, WebSocket traffic, dynamic routing, and other advanced functionalities, making it indispensable for developers seeking robust and adaptable proxy solutions. By integrating these capabilities with ease of use, `smartproxy` stands out as an essential tool in modern software architecture.
## License and Legal Information

View File

@ -8,31 +8,30 @@ const TEST_SERVER_PORT = 4000;
const PROXY_PORT = 4001;
const TEST_DATA = 'Hello through port proxy!';
// Helper function to create a test TCP server
function createTestServer(port: number): Promise<net.Server> {
// Helper: Creates a test TCP server that listens on a given port and host.
function createTestServer(port: number, host: string = 'localhost'): Promise<net.Server> {
return new Promise((resolve) => {
const server = net.createServer((socket) => {
socket.on('data', (data) => {
// Echo the received data back
// Echo the received data back with a prefix.
socket.write(`Echo: ${data.toString()}`);
});
socket.on('error', (error) => {
console.error('[Test Server] Socket error:', error);
console.error(`[Test Server] Socket error on ${host}:${port}:`, error);
});
});
server.listen(port, () => {
console.log(`[Test Server] Listening on port ${port}`);
server.listen(port, host, () => {
console.log(`[Test Server] Listening on ${host}:${port}`);
resolve(server);
});
});
}
// Helper function to create a test client connection
// Helper: Creates a test client connection.
function createTestClient(port: number, data: string): Promise<string> {
return new Promise((resolve, reject) => {
const client = new net.Socket();
let response = '';
client.connect(port, 'localhost', () => {
console.log('[Test Client] Connected to server');
client.write(data);
@ -41,47 +40,44 @@ function createTestClient(port: number, data: string): Promise<string> {
response += chunk.toString();
client.end();
});
client.on('end', () => {
resolve(response);
});
client.on('error', (error) => {
reject(error);
});
client.on('end', () => resolve(response));
client.on('error', (error) => reject(error));
});
}
// Setup test environment
// SETUP: Create a test server and a PortProxy instance.
tap.test('setup port proxy test environment', async () => {
testServer = await createTestServer(TEST_SERVER_PORT);
portProxy = new PortProxy({
fromPort: PROXY_PORT,
toPort: TEST_SERVER_PORT,
targetIP: 'localhost',
domains: [],
domainConfigs: [],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1'],
globalPortRanges: []
});
});
// Test that the proxy starts and its servers are listening.
tap.test('should start port proxy', async () => {
await portProxy.start();
// Since netServers is private, we cast to any to verify that all created servers are listening.
expect((portProxy as any).netServers.every((server: net.Server) => server.listening)).toBeTrue();
});
// Test basic TCP forwarding.
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}`);
});
// Test proxy with a custom target host.
tap.test('should forward TCP connections to custom host', async () => {
// Create a new proxy instance with a custom host (targetIP)
const customHostProxy = new PortProxy({
fromPort: PROXY_PORT + 1,
toPort: TEST_SERVER_PORT,
targetIP: '127.0.0.1',
domains: [],
domainConfigs: [],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1'],
globalPortRanges: []
@ -93,153 +89,151 @@ tap.test('should forward TCP connections to custom host', async () => {
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);
// Test forced domain routing via port-range configuration.
// In this test, we want to forward to a different IP (using '127.0.0.2')
// while keeping the same port. We create a test server on '127.0.0.2'.
tap.test('should forward connections based on domain-specific target IP (forced domain via port-range)', async () => {
const forcedProxyPort = PROXY_PORT + 2;
// Create a test server listening on '127.0.0.2' at forcedProxyPort.
const testServer2 = await createTestServer(forcedProxyPort, '127.0.0.2');
// Create a proxy with domain-specific target IPs
const domainProxy = new PortProxy({
fromPort: PROXY_PORT + 2,
toPort: TEST_SERVER_PORT, // default port (for non-port-range handling)
targetIP: 'localhost', // default target IP
domains: [{
domain: 'domain1.test',
fromPort: forcedProxyPort,
toPort: TEST_SERVER_PORT, // default target port (unused for forced domain)
targetIP: 'localhost',
domainConfigs: [{
domains: ['forced.test'],
allowedIPs: ['127.0.0.1'],
targetIP: '127.0.0.1'
}, {
domain: 'domain2.test',
allowedIPs: ['127.0.0.1'],
targetIP: 'localhost'
targetIPs: ['127.0.0.2'], // Use a different IP than the default.
portRanges: [{ from: forcedProxyPort, to: forcedProxyPort }]
}],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1'],
globalPortRanges: []
globalPortRanges: [{ from: forcedProxyPort, to: forcedProxyPort }]
});
await domainProxy.start();
// Test default connection (should use default targetIP)
const response1 = await createTestClient(PROXY_PORT + 2, TEST_DATA);
expect(response1).toEqual(`Echo: ${TEST_DATA}`);
// Create another proxy with a different default targetIP
const domainProxy2 = new PortProxy({
fromPort: PROXY_PORT + 3,
toPort: TEST_SERVER_PORT,
targetIP: '127.0.0.1',
domains: [],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1'],
globalPortRanges: []
});
await domainProxy2.start();
const response2 = await createTestClient(PROXY_PORT + 3, TEST_DATA);
expect(response2).toEqual(`Echo: ${TEST_DATA}`);
// When connecting to forcedProxyPort, forced domain handling triggers,
// so the proxy will connect to '127.0.0.2' on the same port.
const response = await createTestClient(forcedProxyPort, TEST_DATA);
expect(response).toEqual(`Echo: ${TEST_DATA}`);
await domainProxy.stop();
await domainProxy2.stop();
await new Promise<void>((resolve) => testServer2.close(() => resolve()));
});
// Test handling of multiple concurrent connections.
tap.test('should handle multiple concurrent connections', async () => {
const concurrentRequests = 5;
const requests = Array(concurrentRequests).fill(null).map((_, i) =>
const requests = Array(concurrentRequests).fill(null).map((_, i) =>
createTestClient(PROXY_PORT, `${TEST_DATA} ${i + 1}`)
);
const responses = await Promise.all(requests);
responses.forEach((response, i) => {
expect(response).toEqual(`Echo: ${TEST_DATA} ${i + 1}`);
});
});
// Test connection timeout handling.
tap.test('should handle connection timeouts', async () => {
const client = new net.Socket();
await new Promise<void>((resolve) => {
client.connect(PROXY_PORT, 'localhost', () => {
// Don't send any data, just wait for timeout
client.on('close', () => {
resolve();
});
// Do not send any data to trigger a timeout.
client.on('close', () => resolve());
});
});
});
// Test stopping the port proxy.
tap.test('should stop port proxy', async () => {
await portProxy.stop();
expect((portProxy as any).netServers.every((server: net.Server) => !server.listening)).toBeTrue();
});
// Cleanup chained proxies tests
// Test chained proxies with and without source IP preservation.
tap.test('should support optional source IP preservation in chained proxies', async () => {
// Test 1: Without IP preservation (default behavior)
// Chained proxies without IP preservation.
const firstProxyDefault = new PortProxy({
fromPort: PROXY_PORT + 4,
toPort: PROXY_PORT + 5,
targetIP: 'localhost',
domains: [],
domainConfigs: [],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1'],
globalPortRanges: []
});
const secondProxyDefault = new PortProxy({
fromPort: PROXY_PORT + 5,
toPort: TEST_SERVER_PORT,
targetIP: 'localhost',
domains: [],
domainConfigs: [],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1'],
globalPortRanges: []
});
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
// Chained proxies with IP preservation.
const firstProxyPreserved = new PortProxy({
fromPort: PROXY_PORT + 6,
toPort: PROXY_PORT + 7,
targetIP: 'localhost',
domains: [],
domainConfigs: [],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1'],
preserveSourceIP: true,
globalPortRanges: []
});
const secondProxyPreserved = new PortProxy({
fromPort: PROXY_PORT + 7,
toPort: TEST_SERVER_PORT,
targetIP: 'localhost',
domains: [],
domainConfigs: [],
sniEnabled: false,
defaultAllowedIPs: ['127.0.0.1'],
preserveSourceIP: true,
globalPortRanges: []
});
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();
});
// Test round-robin behavior for multiple target IPs in a domain config.
tap.test('should use round robin for multiple target IPs in domain config', async () => {
const domainConfig = {
domains: ['rr.test'],
allowedIPs: ['127.0.0.1'],
targetIPs: ['hostA', 'hostB']
} as any;
const proxyInstance = new PortProxy({
fromPort: 0,
toPort: 0,
targetIP: 'localhost',
domainConfigs: [domainConfig],
sniEnabled: false,
defaultAllowedIPs: [],
globalPortRanges: []
});
const firstTarget = (proxyInstance as any).getTargetIP(domainConfig);
const secondTarget = (proxyInstance as any).getTargetIP(domainConfig);
expect(firstTarget).toEqual('hostA');
expect(secondTarget).toEqual('hostB');
});
// CLEANUP: Tear down the test server.
tap.test('cleanup port proxy test environment', async () => {
await new Promise<void>((resolve) => testServer.close(() => resolve()));
});
@ -248,7 +242,6 @@ process.on('exit', () => {
if (testServer) {
testServer.close();
}
// Use a cast to access the private property for cleanup.
if (portProxy && (portProxy as any).netServers) {
portProxy.stop();
}

View File

@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartproxy',
version: '3.16.8',
description: 'A robust and versatile proxy package designed to handle high workloads, offering features like SSL redirection, port proxying, WebSocket support, and customizable routing and authentication.'
version: '3.21.0',
description: 'A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.'
}

File diff suppressed because it is too large Load Diff