Compare commits

...

10 Commits

6 changed files with 158 additions and 111 deletions

View File

@ -1,5 +1,39 @@
# Changelog
## 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.
- 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.

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.6",
"version": "3.17.1",
"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

@ -3,6 +3,6 @@
*/
export const commitinfo = {
name: '@push.rocks/smartproxy',
version: '3.16.6',
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.1',
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.'
}

View File

@ -2,9 +2,9 @@ import * as plugins from './plugins.js';
/** Domain configuration with perdomain 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
}
@ -211,18 +211,26 @@ export class PortProxy {
*/
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 => plugins.minimatch(serverName, config.domain)) : undefined);
const defaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
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 && !forcedDomain) {
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) {
console.log(`Connection allowed: IP ${remoteIP} is in default allowed list`);
}
const targetHost = domainConfig?.targetIP || this.settings.targetIP!;
const connectionOptions: plugins.net.NetConnectOpts = {
@ -239,7 +247,7 @@ export class PortProxy {
console.log(
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${forcedDomain.domain})` : ''}`
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${Array.isArray(forcedDomain.domain) ? forcedDomain.domain.join(', ') : forcedDomain.domain})` : ''}`
);
if (initialChunk) {
@ -311,9 +319,8 @@ export class PortProxy {
};
// --- PORT RANGE-BASED HANDLING ---
// If the local port is one of the globally listened ports, we may have port-based rules.
if (this.settings.globalPortRanges && this.settings.globalPortRanges.length > 0) {
// If forwardAllGlobalRanges is enabled, always forward using the global targetIP.
// 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.`);
@ -334,13 +341,12 @@ export class PortProxy {
domain => domain.portRanges && domain.portRanges.length > 0 && isPortInRanges(localPort, domain.portRanges)
);
if (forcedDomain) {
const defaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
if (!defaultAllowed && !isAllowed(remoteIP, forcedDomain.allowedIPs)) {
console.log(`Connection from ${remoteIP} rejected: IP not allowed for domain ${forcedDomain.domain} on port ${localPort}.`);
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 ${forcedDomain.domain}.`);
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;
}