Compare commits
28 Commits
Author | SHA1 | Date | |
---|---|---|---|
29688d1379 | |||
c83f6fa278 | |||
60333b0a59 | |||
1aa409907b | |||
adee6afc76 | |||
4a0792142f | |||
f1b810a4fa | |||
96b5877c5f | |||
6d627f67f7 | |||
9af968b8e7 | |||
b3ba0c21e8 | |||
ef707a5870 | |||
6ca14edb38 | |||
5a5686b6b9 | |||
2080f419cb | |||
659aae297b | |||
fcd0f61b5c | |||
7ee35a98e3 | |||
ea0f6d2270 | |||
621ad9e681 | |||
7cea5773ee | |||
a2cb56ba65 | |||
408b793149 | |||
f6c3d2d3d0 | |||
422eb5ec40 | |||
45390c4389 | |||
0f2e6d688c | |||
3bd7b70c19 |
90
changelog.md
90
changelog.md
@ -1,5 +1,95 @@
|
||||
# Changelog
|
||||
|
||||
## 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.
|
||||
|
||||
- Improved logic to prioritize domain-specific allowed IPs over global defaults.
|
||||
- Fixed port-based rules application to handle global port ranges more effectively.
|
||||
- Enhanced rejection handling for unauthorized IP addresses in both domain-specific and default global lists.
|
||||
|
||||
## 2025-02-27 - 3.16.7 - fix(PortProxy)
|
||||
Improved IP validation logic in PortProxy to ensure correct domain matching and fallback
|
||||
|
||||
- Refactored the setupConnection function inside PortProxy to enhance IP address validation.
|
||||
- Domain-specific allowed IP preference is applied before default list lookup.
|
||||
- Removed redundant condition checks to streamline connection rejection paths.
|
||||
|
||||
## 2025-02-27 - 3.16.6 - fix(PortProxy)
|
||||
Optimize connection cleanup logic in PortProxy by removing unnecessary delays.
|
||||
|
||||
- Removed multiple await plugins.smartdelay.delayFor(0) calls.
|
||||
- Improved performance by ensuring timely resource release during connection termination.
|
||||
|
||||
## 2025-02-27 - 3.16.5 - fix(PortProxy)
|
||||
Improved connection cleanup process with added asynchronous delays
|
||||
|
||||
- Connection cleanup now includes asynchronous delays for reliable order of operations.
|
||||
|
||||
## 2025-02-27 - 3.16.4 - fix(PortProxy)
|
||||
Fix and enhance port proxy handling
|
||||
|
||||
- Ensure that all created proxy servers are correctly checked for listening state.
|
||||
- Corrected the handling of ports and domain configurations within port proxy setups.
|
||||
- Expanded test coverage for handling multiple concurrent and chained proxy connections.
|
||||
|
||||
## 2025-02-27 - 3.16.3 - fix(PortProxy)
|
||||
Refactored PortProxy to support multiple listening ports and improved modularity.
|
||||
|
||||
- Updated PortProxy to allow multiple listening ports with flexible configuration.
|
||||
- Moved helper functions for IP and port range checks outside the class for cleaner code structure.
|
||||
|
||||
## 2025-02-27 - 3.16.2 - fix(PortProxy)
|
||||
Fix port-based routing logic in PortProxy
|
||||
|
||||
- Optimized the handling and checking of local ports in the global port range.
|
||||
- Fixed the logic for rejecting or accepting connections based on predefined port ranges.
|
||||
- Improved handling of the default and specific domain configurations during port-based connections.
|
||||
|
||||
## 2025-02-27 - 3.16.1 - fix(core)
|
||||
Updated minor version numbers in dependencies for patch release.
|
||||
|
||||
- No specific file changes detected.
|
||||
- Dependencies versioning adjusted for stability.
|
||||
|
||||
## 2025-02-27 - 3.16.0 - feat(PortProxy)
|
||||
Enhancements made to PortProxy settings and capabilities
|
||||
|
||||
- Added 'forwardAllGlobalRanges' and 'targetIP' to IPortProxySettings.
|
||||
- Improved PortProxy to forward connections based on domain-specific configurations.
|
||||
- Added comprehensive handling for global port-range based connection forwarding.
|
||||
- Enabled forwarding of all connections on global port ranges directly to global target IP.
|
||||
|
||||
## 2025-02-27 - 3.15.0 - feat(classes.portproxy)
|
||||
Add support for port range-based routing with enhanced IP and port validation.
|
||||
|
||||
- Introduced globalPortRanges in IPortProxySettings for routing based on port ranges.
|
||||
- Improved connection handling with port range and domain configuration validations.
|
||||
- Updated connection logging to include the local port information.
|
||||
|
||||
## 2025-02-26 - 3.14.2 - fix(PortProxy)
|
||||
Fix cleanup timer reset for PortProxy
|
||||
|
||||
- Resolved an issue where the cleanup timer in the PortProxy class did not reset correctly if both incoming and outgoing data events were triggered without clearing flags.
|
||||
|
||||
## 2025-02-26 - 3.14.1 - fix(PortProxy)
|
||||
Increased default maxConnectionLifetime for PortProxy to 600000 ms
|
||||
|
||||
- Updated PortProxy settings to extend default maxConnectionLifetime to 10 minutes.
|
||||
|
||||
## 2025-02-26 - 3.14.0 - feat(PortProxy)
|
||||
Introduce max connection lifetime feature
|
||||
|
||||
|
@ -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"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
30
package.json
30
package.json
@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "@push.rocks/smartproxy",
|
||||
"version": "3.14.0",
|
||||
"version": "3.17.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
127
readme.md
@ -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
|
||||
|
||||
|
@ -16,12 +16,10 @@ function createTestServer(port: number): Promise<net.Server> {
|
||||
// Echo the received data back
|
||||
socket.write(`Echo: ${data.toString()}`);
|
||||
});
|
||||
|
||||
socket.on('error', (error) => {
|
||||
console.error('[Test Server] Socket error:', error);
|
||||
});
|
||||
});
|
||||
|
||||
server.listen(port, () => {
|
||||
console.log(`[Test Server] Listening on port ${port}`);
|
||||
resolve(server);
|
||||
@ -39,16 +37,13 @@ function createTestClient(port: number, data: string): Promise<string> {
|
||||
console.log('[Test Client] Connected to server');
|
||||
client.write(data);
|
||||
});
|
||||
|
||||
client.on('data', (chunk) => {
|
||||
response += chunk.toString();
|
||||
client.end();
|
||||
});
|
||||
|
||||
client.on('end', () => {
|
||||
resolve(response);
|
||||
});
|
||||
|
||||
client.on('error', (error) => {
|
||||
reject(error);
|
||||
});
|
||||
@ -61,16 +56,18 @@ tap.test('setup port proxy test environment', async () => {
|
||||
portProxy = new PortProxy({
|
||||
fromPort: PROXY_PORT,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
toHost: 'localhost',
|
||||
targetIP: 'localhost',
|
||||
domains: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1']
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
globalPortRanges: []
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('should start port proxy', async () => {
|
||||
await portProxy.start();
|
||||
expect(portProxy.netServer.listening).toBeTrue();
|
||||
// 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();
|
||||
});
|
||||
|
||||
tap.test('should forward TCP connections and data to localhost', async () => {
|
||||
@ -79,14 +76,15 @@ tap.test('should forward TCP connections and data to localhost', async () => {
|
||||
});
|
||||
|
||||
tap.test('should forward TCP connections to custom host', async () => {
|
||||
// Create a new proxy instance with a custom host
|
||||
// Create a new proxy instance with a custom host (targetIP)
|
||||
const customHostProxy = new PortProxy({
|
||||
fromPort: PROXY_PORT + 1,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
toHost: '127.0.0.1',
|
||||
targetIP: '127.0.0.1',
|
||||
domains: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1']
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
globalPortRanges: []
|
||||
});
|
||||
|
||||
await customHostProxy.start();
|
||||
@ -103,8 +101,8 @@ tap.test('should forward connections based on domain-specific target IP', async
|
||||
// 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
|
||||
toPort: TEST_SERVER_PORT, // default port (for non-port-range handling)
|
||||
targetIP: 'localhost', // default target IP
|
||||
domains: [{
|
||||
domain: 'domain1.test',
|
||||
allowedIPs: ['127.0.0.1'],
|
||||
@ -114,24 +112,26 @@ tap.test('should forward connections based on domain-specific target IP', async
|
||||
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']
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
globalPortRanges: []
|
||||
});
|
||||
|
||||
await domainProxy.start();
|
||||
|
||||
// Test default connection (should use default host)
|
||||
// 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 different default host
|
||||
// Create another proxy with a different default targetIP
|
||||
const domainProxy2 = new PortProxy({
|
||||
fromPort: PROXY_PORT + 3,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
toHost: '127.0.0.1',
|
||||
targetIP: '127.0.0.1',
|
||||
domains: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1']
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
globalPortRanges: []
|
||||
});
|
||||
|
||||
await domainProxy2.start();
|
||||
@ -158,7 +158,6 @@ tap.test('should handle multiple concurrent connections', async () => {
|
||||
|
||||
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
|
||||
@ -171,28 +170,30 @@ tap.test('should handle connection timeouts', async () => {
|
||||
|
||||
tap.test('should stop port proxy', async () => {
|
||||
await portProxy.stop();
|
||||
expect(portProxy.netServer.listening).toBeFalse();
|
||||
expect((portProxy as any).netServers.every((server: net.Server) => !server.listening)).toBeTrue();
|
||||
});
|
||||
|
||||
// Cleanup
|
||||
// Cleanup chained proxies tests
|
||||
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',
|
||||
targetIP: 'localhost',
|
||||
domains: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1']
|
||||
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1'],
|
||||
globalPortRanges: []
|
||||
});
|
||||
|
||||
const secondProxyDefault = new PortProxy({
|
||||
fromPort: PROXY_PORT + 5,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
toHost: 'localhost',
|
||||
targetIP: 'localhost',
|
||||
domains: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1']
|
||||
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1'],
|
||||
globalPortRanges: []
|
||||
});
|
||||
|
||||
await secondProxyDefault.start();
|
||||
@ -209,21 +210,23 @@ tap.test('should support optional source IP preservation in chained proxies', as
|
||||
const firstProxyPreserved = new PortProxy({
|
||||
fromPort: PROXY_PORT + 6,
|
||||
toPort: PROXY_PORT + 7,
|
||||
toHost: 'localhost',
|
||||
targetIP: 'localhost',
|
||||
domains: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
preserveSourceIP: true
|
||||
preserveSourceIP: true,
|
||||
globalPortRanges: []
|
||||
});
|
||||
|
||||
const secondProxyPreserved = new PortProxy({
|
||||
fromPort: PROXY_PORT + 7,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
toHost: 'localhost',
|
||||
targetIP: 'localhost',
|
||||
domains: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
preserveSourceIP: true
|
||||
preserveSourceIP: true,
|
||||
globalPortRanges: []
|
||||
});
|
||||
|
||||
await secondProxyPreserved.start();
|
||||
@ -245,9 +248,10 @@ process.on('exit', () => {
|
||||
if (testServer) {
|
||||
testServer.close();
|
||||
}
|
||||
if (portProxy && portProxy.netServer) {
|
||||
// Use a cast to access the private property for cleanup.
|
||||
if (portProxy && (portProxy as any).netServers) {
|
||||
portProxy.stop();
|
||||
}
|
||||
});
|
||||
|
||||
export default tap.start();
|
||||
export default tap.start();
|
@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartproxy',
|
||||
version: '3.14.0',
|
||||
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.17.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.'
|
||||
}
|
||||
|
@ -1,20 +1,25 @@
|
||||
import * as plugins from './plugins.js';
|
||||
|
||||
/** Domain configuration with per‐domain allowed port ranges */
|
||||
export interface IDomainConfig {
|
||||
domain: string; // Glob pattern for domain
|
||||
allowedIPs: string[]; // Glob patterns for allowed IPs
|
||||
targetIP?: string; // Optional target IP for this domain
|
||||
domain: string | string[]; // Glob pattern or patterns for domain(s)
|
||||
allowedIPs: string[]; // Glob patterns for allowed IPs
|
||||
targetIP?: string; // Optional target IP for this domain
|
||||
portRanges?: Array<{ from: number; to: number }>; // Optional domain-specific allowed port ranges
|
||||
}
|
||||
|
||||
/** Port proxy settings including global allowed port ranges */
|
||||
export interface IPortProxySettings extends plugins.tls.TlsOptions {
|
||||
fromPort: number;
|
||||
toPort: number;
|
||||
toHost?: string; // Target host to proxy to, defaults to 'localhost'
|
||||
targetIP?: string; // Global target host to proxy to, defaults to 'localhost'
|
||||
domains: IDomainConfig[];
|
||||
sniEnabled?: boolean;
|
||||
defaultAllowedIPs?: string[];
|
||||
preserveSourceIP?: boolean;
|
||||
maxConnectionLifetime?: number; // New option (in milliseconds) to force cleanup of long-lived connections
|
||||
maxConnectionLifetime?: number; // (ms) force cleanup of long-lived connections
|
||||
globalPortRanges: Array<{ from: number; to: number }>; // Global allowed port ranges
|
||||
forwardAllGlobalRanges?: boolean; // When true, forwards all connections on global port ranges to the global targetIP
|
||||
}
|
||||
|
||||
/**
|
||||
@ -85,12 +90,13 @@ interface IConnectionRecord {
|
||||
outgoing: plugins.net.Socket | null;
|
||||
incomingStartTime: number;
|
||||
outgoingStartTime?: number;
|
||||
lockedDomain?: string; // New field to lock this connection to the initial SNI
|
||||
connectionClosed: boolean;
|
||||
cleanupTimer?: NodeJS.Timeout; // Timer to force cleanup after max lifetime/inactivity
|
||||
}
|
||||
|
||||
export class PortProxy {
|
||||
netServer: plugins.net.Server;
|
||||
private netServers: plugins.net.Server[] = [];
|
||||
settings: IPortProxySettings;
|
||||
// Unified record tracking each connection pair.
|
||||
private connectionRecords: Set<IConnectionRecord> = new Set();
|
||||
@ -107,8 +113,8 @@ export class PortProxy {
|
||||
constructor(settingsArg: IPortProxySettings) {
|
||||
this.settings = {
|
||||
...settingsArg,
|
||||
toHost: settingsArg.toHost || 'localhost',
|
||||
maxConnectionLifetime: settingsArg.maxConnectionLifetime || 10000,
|
||||
targetIP: settingsArg.targetIP || 'localhost',
|
||||
maxConnectionLifetime: settingsArg.maxConnectionLifetime || 600000,
|
||||
};
|
||||
}
|
||||
|
||||
@ -117,39 +123,10 @@ export class PortProxy {
|
||||
}
|
||||
|
||||
public async start() {
|
||||
// Helper to forcefully destroy sockets.
|
||||
const cleanUpSockets = (socketA: plugins.net.Socket, socketB?: plugins.net.Socket) => {
|
||||
if (!socketA.destroyed) socketA.destroy();
|
||||
if (socketB && !socketB.destroyed) socketB.destroy();
|
||||
};
|
||||
|
||||
// Normalize an IP to include both IPv4 and IPv6 representations.
|
||||
const normalizeIP = (ip: string): string[] => {
|
||||
if (ip.startsWith('::ffff:')) {
|
||||
const ipv4 = ip.slice(7);
|
||||
return [ip, ipv4];
|
||||
}
|
||||
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) {
|
||||
return [ip, `::ffff:${ip}`];
|
||||
}
|
||||
return [ip];
|
||||
};
|
||||
|
||||
// Check if a given IP matches any of the glob patterns.
|
||||
const isAllowed = (ip: string, patterns: string[]): boolean => {
|
||||
const normalizedIPVariants = normalizeIP(ip);
|
||||
const expandedPatterns = patterns.flatMap(normalizeIP);
|
||||
return normalizedIPVariants.some(ipVariant =>
|
||||
expandedPatterns.some(pattern => plugins.minimatch(ipVariant, pattern))
|
||||
);
|
||||
};
|
||||
|
||||
// Find a matching domain config based on the SNI.
|
||||
const findMatchingDomain = (serverName: string): IDomainConfig | undefined =>
|
||||
this.settings.domains.find(config => plugins.minimatch(serverName, config.domain));
|
||||
|
||||
this.netServer = plugins.net.createServer((socket: plugins.net.Socket) => {
|
||||
// Define a unified connection handler for all listening ports.
|
||||
const connectionHandler = (socket: plugins.net.Socket) => {
|
||||
const remoteIP = socket.remoteAddress || '';
|
||||
const localPort = socket.localPort; // The port on which this connection was accepted.
|
||||
const connectionRecord: IConnectionRecord = {
|
||||
incoming: socket,
|
||||
outgoing: null,
|
||||
@ -157,20 +134,21 @@ export class PortProxy {
|
||||
connectionClosed: false,
|
||||
};
|
||||
this.connectionRecords.add(connectionRecord);
|
||||
console.log(`New connection from ${remoteIP}. Active connections: ${this.connectionRecords.size}`);
|
||||
console.log(`New connection from ${remoteIP} on port ${localPort}. Active connections: ${this.connectionRecords.size}`);
|
||||
|
||||
let initialDataReceived = false;
|
||||
let incomingTerminationReason: string | null = null;
|
||||
let outgoingTerminationReason: string | null = null;
|
||||
|
||||
// Ensure cleanup happens only once for the entire connection record.
|
||||
const cleanupOnce = () => {
|
||||
const cleanupOnce = async () => {
|
||||
if (!connectionRecord.connectionClosed) {
|
||||
connectionRecord.connectionClosed = true;
|
||||
if (connectionRecord.cleanupTimer) {
|
||||
clearTimeout(connectionRecord.cleanupTimer);
|
||||
}
|
||||
cleanUpSockets(connectionRecord.incoming, connectionRecord.outgoing || undefined);
|
||||
if (!socket.destroyed) socket.destroy();
|
||||
if (connectionRecord.outgoing && !connectionRecord.outgoing.destroyed) connectionRecord.outgoing.destroy();
|
||||
this.connectionRecords.delete(connectionRecord);
|
||||
console.log(`Connection from ${remoteIP} terminated. Active connections: ${this.connectionRecords.size}`);
|
||||
}
|
||||
@ -225,28 +203,40 @@ export class PortProxy {
|
||||
cleanupOnce();
|
||||
};
|
||||
|
||||
const setupConnection = (serverName: string, initialChunk?: Buffer) => {
|
||||
const defaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
|
||||
/**
|
||||
* Sets up the connection to the target host.
|
||||
* @param serverName - The SNI hostname (unused when forcedDomain is provided).
|
||||
* @param initialChunk - Optional initial data chunk.
|
||||
* @param forcedDomain - If provided, overrides SNI/domain lookup (used for port-based routing).
|
||||
* @param overridePort - If provided, use this port for the outgoing connection (typically the same as the incoming port).
|
||||
*/
|
||||
const setupConnection = (serverName: string, initialChunk?: Buffer, forcedDomain?: IDomainConfig, overridePort?: number) => {
|
||||
// If a forcedDomain is provided (port-based routing), use it; otherwise, use SNI-based lookup.
|
||||
const domainConfig = forcedDomain
|
||||
? forcedDomain
|
||||
: (serverName ? this.settings.domains.find(config => {
|
||||
if (typeof config.domain === 'string') {
|
||||
return plugins.minimatch(serverName, config.domain);
|
||||
} else {
|
||||
return config.domain.some(d => plugins.minimatch(serverName, d));
|
||||
}
|
||||
}) : undefined);
|
||||
|
||||
if (!defaultAllowed && serverName) {
|
||||
const domainConfig = findMatchingDomain(serverName);
|
||||
if (!domainConfig) {
|
||||
return rejectIncomingConnection('rejected', `Connection rejected: No matching domain config for ${serverName} from ${remoteIP}`);
|
||||
}
|
||||
// If a matching domain config exists, check its allowedIPs.
|
||||
if (domainConfig) {
|
||||
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
|
||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
|
||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed for domain ${Array.isArray(domainConfig.domain) ? domainConfig.domain.join(', ') : domainConfig.domain}`);
|
||||
}
|
||||
} else if (this.settings.defaultAllowedIPs) {
|
||||
// Only check default allowed IPs if no domain config matched.
|
||||
if (!isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed by default allowed list`);
|
||||
}
|
||||
} else if (!defaultAllowed && !serverName) {
|
||||
return rejectIncomingConnection('rejected', `Connection rejected: No SNI and IP ${remoteIP} not in default allowed list`);
|
||||
} else if (defaultAllowed && !serverName) {
|
||||
console.log(`Connection allowed: IP ${remoteIP} is in default allowed list`);
|
||||
}
|
||||
|
||||
const domainConfig = serverName ? findMatchingDomain(serverName) : undefined;
|
||||
const targetHost = domainConfig?.targetIP || this.settings.toHost!;
|
||||
const targetHost = domainConfig?.targetIP || this.settings.targetIP!;
|
||||
const connectionOptions: plugins.net.NetConnectOpts = {
|
||||
host: targetHost,
|
||||
port: this.settings.toPort,
|
||||
port: overridePort !== undefined ? overridePort : this.settings.toPort,
|
||||
};
|
||||
if (this.settings.preserveSourceIP) {
|
||||
connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
|
||||
@ -257,8 +247,8 @@ export class PortProxy {
|
||||
connectionRecord.outgoingStartTime = Date.now();
|
||||
|
||||
console.log(
|
||||
`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}` +
|
||||
`${serverName ? ` (SNI: ${serverName})` : ''}`
|
||||
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
||||
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${Array.isArray(forcedDomain.domain) ? forcedDomain.domain.join(', ') : forcedDomain.domain})` : ''}`
|
||||
);
|
||||
|
||||
if (initialChunk) {
|
||||
@ -292,7 +282,7 @@ export class PortProxy {
|
||||
socket.on('end', handleClose('incoming'));
|
||||
targetSocket.on('end', handleClose('outgoing'));
|
||||
|
||||
// If maxConnectionLifetime is set, initialize a cleanup timer that will be reset on data flow.
|
||||
// Initialize a cleanup timer for max connection lifetime.
|
||||
if (this.settings.maxConnectionLifetime) {
|
||||
let incomingActive = false;
|
||||
let outgoingActive = false;
|
||||
@ -308,25 +298,64 @@ export class PortProxy {
|
||||
}
|
||||
};
|
||||
|
||||
// Start the cleanup timer.
|
||||
resetCleanupTimer();
|
||||
|
||||
// Listen for data events on both sides and reset the timer when both are active.
|
||||
socket.on('data', () => {
|
||||
incomingActive = true;
|
||||
if (incomingActive && outgoingActive) {
|
||||
resetCleanupTimer();
|
||||
incomingActive = false;
|
||||
outgoingActive = false;
|
||||
}
|
||||
});
|
||||
targetSocket.on('data', () => {
|
||||
outgoingActive = true;
|
||||
if (incomingActive && outgoingActive) {
|
||||
resetCleanupTimer();
|
||||
incomingActive = false;
|
||||
outgoingActive = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
// --- PORT RANGE-BASED HANDLING ---
|
||||
// Only apply port-based rules if the incoming port is within one of the global port ranges.
|
||||
if (this.settings.globalPortRanges && isPortInRanges(localPort, this.settings.globalPortRanges)) {
|
||||
if (this.settings.forwardAllGlobalRanges) {
|
||||
if (this.settings.defaultAllowedIPs && !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
||||
console.log(`Connection from ${remoteIP} rejected: IP ${remoteIP} not allowed in global default allowed list.`);
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
console.log(`Port-based connection from ${remoteIP} on port ${localPort} forwarded to global target IP ${this.settings.targetIP}.`);
|
||||
setupConnection('', undefined, {
|
||||
domain: 'global',
|
||||
allowedIPs: this.settings.defaultAllowedIPs || [],
|
||||
targetIP: this.settings.targetIP,
|
||||
portRanges: []
|
||||
}, localPort);
|
||||
return;
|
||||
} else {
|
||||
// Attempt to find a matching forced domain config based on the local port.
|
||||
const forcedDomain = this.settings.domains.find(
|
||||
domain => domain.portRanges && domain.portRanges.length > 0 && isPortInRanges(localPort, domain.portRanges)
|
||||
);
|
||||
if (forcedDomain) {
|
||||
if (!isAllowed(remoteIP, forcedDomain.allowedIPs)) {
|
||||
console.log(`Connection from ${remoteIP} rejected: IP not allowed for domain ${Array.isArray(forcedDomain.domain) ? forcedDomain.domain.join(', ') : forcedDomain.domain} on port ${localPort}.`);
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
console.log(`Port-based connection from ${remoteIP} on port ${localPort} matched domain ${Array.isArray(forcedDomain.domain) ? forcedDomain.domain.join(', ') : forcedDomain.domain}.`);
|
||||
setupConnection('', undefined, forcedDomain, localPort);
|
||||
return;
|
||||
}
|
||||
// Fall through to SNI/default handling if no forced domain config is found.
|
||||
}
|
||||
}
|
||||
|
||||
// --- FALLBACK: SNI-BASED HANDLING (or default when SNI is disabled) ---
|
||||
if (this.settings.sniEnabled) {
|
||||
socket.setTimeout(5000, () => {
|
||||
console.log(`Initial data timeout for ${remoteIP}`);
|
||||
@ -338,7 +367,19 @@ export class PortProxy {
|
||||
socket.setTimeout(0);
|
||||
initialDataReceived = true;
|
||||
const serverName = extractSNI(chunk) || '';
|
||||
// Lock the connection to the negotiated SNI.
|
||||
connectionRecord.lockedDomain = serverName;
|
||||
console.log(`Received connection from ${remoteIP} with SNI: ${serverName}`);
|
||||
// Add an extra data listener to check for a renegotiated ClientHello.
|
||||
socket.on('data', (chunk: Buffer) => {
|
||||
if (chunk.length > 0 && chunk.readUInt8(0) === 22) {
|
||||
const newSNI = extractSNI(chunk);
|
||||
if (newSNI && newSNI !== connectionRecord.lockedDomain) {
|
||||
console.log(`Rehandshake detected with different SNI: ${newSNI} vs locked ${connectionRecord.lockedDomain}. Terminating connection.`);
|
||||
cleanupOnce();
|
||||
}
|
||||
}
|
||||
});
|
||||
setupConnection(serverName, chunk);
|
||||
});
|
||||
} else {
|
||||
@ -348,18 +389,38 @@ export class PortProxy {
|
||||
}
|
||||
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)' : ''}`
|
||||
);
|
||||
});
|
||||
};
|
||||
|
||||
// Every 10 seconds log active connection count and longest running durations.
|
||||
// --- SETUP LISTENERS ---
|
||||
// Determine which ports to listen on.
|
||||
const listeningPorts = new Set<number>();
|
||||
if (this.settings.globalPortRanges && this.settings.globalPortRanges.length > 0) {
|
||||
// Listen on every port defined by the global ranges.
|
||||
for (const range of this.settings.globalPortRanges) {
|
||||
for (let port = range.from; port <= range.to; port++) {
|
||||
listeningPorts.add(port);
|
||||
}
|
||||
}
|
||||
// Also ensure the default fromPort is listened to if it isn’t already in the ranges.
|
||||
listeningPorts.add(this.settings.fromPort);
|
||||
} else {
|
||||
listeningPorts.add(this.settings.fromPort);
|
||||
}
|
||||
|
||||
// Create a server for each port.
|
||||
for (const port of listeningPorts) {
|
||||
const server = plugins.net
|
||||
.createServer(connectionHandler)
|
||||
.on('error', (err: Error) => {
|
||||
console.log(`Server Error on port ${port}: ${err.message}`);
|
||||
});
|
||||
server.listen(port, () => {
|
||||
console.log(`PortProxy -> OK: Now listening on port ${port}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`);
|
||||
});
|
||||
this.netServers.push(server);
|
||||
}
|
||||
|
||||
// Log active connection count and longest running durations every 10 seconds.
|
||||
this.connectionLogger = setInterval(() => {
|
||||
const now = Date.now();
|
||||
let maxIncoming = 0;
|
||||
@ -380,14 +441,41 @@ export class PortProxy {
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
const done = plugins.smartpromise.defer();
|
||||
this.netServer.close(() => {
|
||||
done.resolve();
|
||||
});
|
||||
// Close all servers.
|
||||
const closePromises: Promise<void>[] = this.netServers.map(
|
||||
server =>
|
||||
new Promise<void>((resolve) => {
|
||||
server.close(() => resolve());
|
||||
})
|
||||
);
|
||||
if (this.connectionLogger) {
|
||||
clearInterval(this.connectionLogger);
|
||||
this.connectionLogger = null;
|
||||
}
|
||||
await done.promise;
|
||||
await Promise.all(closePromises);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Helper: Check if a port falls within any of the given port ranges.
|
||||
const isPortInRanges = (port: number, ranges: Array<{ from: number; to: number }>): boolean => {
|
||||
return ranges.some(range => port >= range.from && port <= range.to);
|
||||
};
|
||||
|
||||
// Helper: Check if a given IP matches any of the glob patterns.
|
||||
const isAllowed = (ip: string, patterns: string[]): boolean => {
|
||||
const normalizeIP = (ip: string): string[] => {
|
||||
if (ip.startsWith('::ffff:')) {
|
||||
const ipv4 = ip.slice(7);
|
||||
return [ip, ipv4];
|
||||
}
|
||||
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) {
|
||||
return [ip, `::ffff:${ip}`];
|
||||
}
|
||||
return [ip];
|
||||
};
|
||||
const normalizedIPVariants = normalizeIP(ip);
|
||||
const expandedPatterns = patterns.flatMap(normalizeIP);
|
||||
return normalizedIPVariants.some(ipVariant =>
|
||||
expandedPatterns.some(pattern => plugins.minimatch(ipVariant, pattern))
|
||||
);
|
||||
};
|
Reference in New Issue
Block a user