fix(documentation): Refactored readme for clarity and consistency, fixed documentation typos

This commit is contained in:
Philipp Kunz 2025-03-03 03:05:49 +00:00
parent 3748689c16
commit c0de8c59a2
4 changed files with 150 additions and 167 deletions

View File

@ -1,5 +1,13 @@
# Changelog # Changelog
## 2025-03-03 - 3.22.5 - fix(documentation)
Refactored readme for clarity and consistency, fixed documentation typos
- Updated readme to improve clarity and remove redundant information.
- Fixed minor documentation issues in the code comments.
- Reorganized readme structure for better readability.
- Improved sample code snippets for easier understanding.
## 2025-03-03 - 3.22.4 - fix(core) ## 2025-03-03 - 3.22.4 - fix(core)
Addressed minor issues in the core modules to improve stability and performance. Addressed minor issues in the core modules to improve stability and performance.

303
readme.md
View File

@ -1,228 +1,203 @@
# @push.rocks/smartproxy # @push.rocks/smartproxy
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. 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.
## Install ## Features
To install `@push.rocks/smartproxy`, run the following command in your project's root directory: - **HTTPS Reverse Proxy** - Route traffic to backend services based on hostname with TLS termination
- **WebSocket Support** - Full WebSocket proxying with heartbeat monitoring
- **TCP Port Forwarding** - Advanced port forwarding with SNI inspection and domain-based routing
- **HTTP to HTTPS Redirection** - Automatically redirect HTTP requests to HTTPS
- **Let's Encrypt Integration** - Automatic certificate management using ACME protocol
- **IP Filtering** - Control access with IP allow/block lists using glob patterns
- **IPTables Integration** - Direct manipulation of iptables for low-level port forwarding
- **Basic Authentication** - Support for basic auth on proxied routes
- **Connection Management** - Intelligent connection tracking and cleanup
## Installation
```bash ```bash
npm install @push.rocks/smartproxy --save npm install @push.rocks/smartproxy
``` ```
This will add `@push.rocks/smartproxy` to your project's dependencies.
## Usage ## Usage
`@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. ### Basic Reverse Proxy Setup
### Initial Setup
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 ```typescript
import { NetworkProxy } from '@push.rocks/smartproxy'; import { NetworkProxy } from '@push.rocks/smartproxy';
// Create an instance of NetworkProxy with the desired configuration // Create a reverse proxy listening on port 443
const myNetworkProxy = new NetworkProxy({ port: 443 }); const proxy = new NetworkProxy({
port: 443
});
// Define reverse proxy configurations for the domains you wish to proxy // Define reverse proxy configurations
const proxyConfigs = [ const proxyConfigs = [
{ {
destinationIp: '127.0.0.1',
destinationPort: '3000',
hostName: 'example.com', hostName: 'example.com',
privateKey: `-----BEGIN PRIVATE KEY----- destinationIp: '127.0.0.1',
PRIVATE_KEY_CONTENT destinationPort: 3000,
-----END PRIVATE KEY-----`, publicKey: 'your-cert-content',
publicKey: `-----BEGIN CERTIFICATE----- privateKey: 'your-key-content'
CERTIFICATE_CONTENT
-----END CERTIFICATE-----`,
}, },
// Additional configurations can be added here {
hostName: 'api.example.com',
destinationIp: '127.0.0.1',
destinationPort: 4000,
publicKey: 'your-cert-content',
privateKey: 'your-key-content',
// Optional basic auth
authentication: {
type: 'Basic',
user: 'admin',
pass: 'secret'
}
}
]; ];
// Start the network proxy to enable forwarding // Start the proxy and update configurations
await myNetworkProxy.start(); (async () => {
await proxy.start();
await proxy.updateProxyConfigs(proxyConfigs);
// Apply the configurations you defined earlier // Add default headers to all responses
await myNetworkProxy.updateProxyConfigs(proxyConfigs); await proxy.addDefaultHeaders({
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload'
// Optionally, you can set default headers to be included in all responses });
await myNetworkProxy.addDefaultHeaders({ })();
'X-Powered-By': 'smartproxy',
});
``` ```
### Configuring SSL Redirection ### HTTP to HTTPS Redirection
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 ```typescript
import { SslRedirect } from '@push.rocks/smartproxy'; import { SslRedirect } from '@push.rocks/smartproxy';
// Create an SslRedirect instance to listen on port 80 // Create and start HTTP to HTTPS redirect service on port 80
const mySslRedirect = new SslRedirect(80); const redirector = new SslRedirect(80);
redirector.start();
// Start the redirect to enforce HTTPS
await mySslRedirect.start();
// To stop HTTP redirection, use the following command:
await mySslRedirect.stop();
``` ```
### Managing Port Proxying ### TCP Port Forwarding with Domain-based Routing
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 ```typescript
import { PortProxy } from '@push.rocks/smartproxy'; import { PortProxy } from '@push.rocks/smartproxy';
// Set up a PortProxy to forward traffic from port 5000 to 3000 // Configure port proxy with domain-based routing
const myPortProxy = new PortProxy(5000, 3000); const portProxy = new PortProxy({
fromPort: 443,
// Initiate the port proxy toPort: 8443,
await myPortProxy.start(); targetIP: 'localhost', // Default target host
sniEnabled: true, // Enable SNI inspection
// To halt the port proxy, execute: globalPortRanges: [{ from: 443, to: 443 }],
await myPortProxy.stop(); defaultAllowedIPs: ['*'], // Allow all IPs by default
``` domainConfigs: [
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';
// Configure complex port proxy rules
const advancedPortProxy = new PortProxy({
fromPort: 6000,
toPort: 3000,
domains: [
{ {
domain: 'api.example.com', domains: ['example.com', '*.example.com'], // Glob patterns for matching domains
allowedIPs: ['192.168.0.*', '127.0.0.1'], allowedIPs: ['192.168.1.*'], // Restrict access by IP
targetIP: '192.168.1.100' blockedIPs: ['192.168.1.100'], // Block specific IPs
targetIPs: ['10.0.0.1', '10.0.0.2'], // Round-robin between multiple targets
portRanges: [{ from: 443, to: 443 }]
} }
// Additional domain rules can be added as needed
], ],
sniEnabled: true, // Server Name Indication (SNI) support maxConnectionLifetime: 3600000, // 1 hour in milliseconds
defaultAllowedIPs: ['*'], preserveSourceIP: true
}); });
// Activate the proxy with conditional rules portProxy.start();
await advancedPortProxy.start();
``` ```
### WebSocket Handling ### IPTables Port Forwarding
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';
// Create a NetworkProxy instance for WebSocket traffic
const wsNetworkProxy = new NetworkProxy({ port: 443 });
// Define proxy configurations targeted for WebSocket traffic
const websocketConfig = [
{
destinationIp: '127.0.0.1',
destinationPort: '8080',
hostName: 'socket.example.com',
// Include SSL details if necessary
}
];
// Start the proxy and apply WebSocket settings
await wsNetworkProxy.start();
await wsNetworkProxy.updateProxyConfigs(websocketConfig);
// Set heartbeat intervals to maintain WebSocket connections
wsNetworkProxy.heartbeatInterval = setInterval(() => {
// Logic for connection health checks
}, 60000); // every minute
// Capture and handle server errors for resiliency
wsNetworkProxy.httpsServer.on('error', (error) => console.log('Server Error:', error));
```
### Advanced Routing and Custom Features
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';
// Instantiate a proxy with dynamic routing
const routeProxy = new NetworkProxy({ port: 8443 });
routeProxy.router.setNewProxyConfigs([
{
destinationIp: '192.168.1.150',
destinationPort: '80',
hostName: 'dynamic.example.com',
authentication: {
type: 'Basic',
user: 'admin',
pass: 'password123'
}
}
]);
// Activate the routing proxy
await routeProxy.start();
```
For those who require granular traffic control, integrating tools like `iptables` offers additional power over network management:
```typescript ```typescript
import { IPTablesProxy } from '@push.rocks/smartproxy'; import { IPTablesProxy } from '@push.rocks/smartproxy';
// Set up IPTables for sophisticated network traffic management // Configure IPTables to forward from port 80 to 8080
const iptablesProxy = new IPTablesProxy({ const iptables = new IPTablesProxy({
fromPort: 8081, fromPort: 80,
toPort: 8080, toPort: 8080,
deleteOnExit: true // Clean up rules when the server shuts down toHost: 'localhost',
preserveSourceIP: true,
deleteOnExit: true // Automatically clean up rules on process exit
}); });
// Enable routing through IPTables iptables.start();
await iptablesProxy.start();
``` ```
### Integrating SSL and HTTP/HTTPS Credentials ### Automatic HTTPS Certificate Management
Handling sensitive data like SSL keys and certificates securely is crucial in proxy configurations:
```typescript ```typescript
import { loadDefaultCertificates } from '@push.rocks/smartproxy'; import { Port80Handler } from '@push.rocks/smartproxy';
try { // Create an ACME handler for Let's Encrypt
const { privateKey, publicKey } = loadDefaultCertificates(); // Adjust path if necessary const acmeHandler = new Port80Handler();
console.log('SSL certificates loaded successfully.');
// Use these credentials in your configurations // Add domains to manage certificates for
} catch (error) { acmeHandler.addDomain('example.com');
console.error('Error loading certificates:', error); acmeHandler.addDomain('api.example.com');
}
``` ```
### Testing and Validation ## Configuration Options
Smartproxy supports extensive testing to ensure your proxy configurations operate as expected. Leveraging `tap` alongside TypeScript testing frameworks supports quality assurance: ### NetworkProxy Options
```typescript | Option | Description | Default |
import { expect, tap } from '@push.rocks/tapbundle'; |----------------|---------------------------------------------------|---------|
import { NetworkProxy } from '@push.rocks/smartproxy'; | `port` | Port to listen on for HTTPS connections | - |
tap.test('Check proxied request returns status 200', async () => { ### PortProxy Settings
// Testing logic
});
tap.start(); | Option | Description | Default |
``` |--------------------------|--------------------------------------------------------|-------------|
| `fromPort` | Port to listen on | - |
| `toPort` | Destination port to forward to | - |
| `targetIP` | Default destination IP if not specified in domainConfig | 'localhost' |
| `sniEnabled` | Enable SNI inspection for TLS connections | false |
| `defaultAllowedIPs` | IP patterns allowed by default | - |
| `defaultBlockedIPs` | IP patterns blocked by default | - |
| `preserveSourceIP` | Preserve the original client IP | false |
| `maxConnectionLifetime` | Maximum time in ms to keep a connection open | 600000 |
| `globalPortRanges` | Array of port ranges to listen on | - |
| `forwardAllGlobalRanges` | Forward all global range connections to targetIP | false |
| `gracefulShutdownTimeout`| Time in ms to wait during shutdown | 30000 |
### Conclusion ### IPTablesProxy Settings
`@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. | Option | Description | Default |
|-------------------|---------------------------------------------|-------------|
| `fromPort` | Source port to forward from | - |
| `toPort` | Destination port to forward to | - |
| `toHost` | Destination host to forward to | 'localhost' |
| `preserveSourceIP`| Preserve the original client IP | false |
| `deleteOnExit` | Remove iptables rules when process exits | false |
## Advanced Features
### Connection Management and Monitoring
The `PortProxy` class includes built-in connection tracking and monitoring:
- Automatic cleanup of idle connections
- Timeouts for connections that exceed maximum lifetime
- Detailed logging of connection states
- Termination statistics
### WebSocket Support
The `NetworkProxy` class provides WebSocket support with:
- WebSocket connection proxying
- Automatic heartbeat monitoring
- Connection cleanup for inactive WebSockets
### SNI-based Routing
The `PortProxy` class can inspect the SNI (Server Name Indication) field in TLS handshakes to route connections based on the requested domain:
- Multiple backend targets per domain
- Round-robin load balancing
- Domain-specific allowed IP ranges
- Protection against SNI renegotiation attacks
## License and Legal Information ## License and Legal Information

View File

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

@ -663,7 +663,7 @@ export class PortProxy {
const checkInterval = setInterval(() => { const checkInterval = setInterval(() => {
if (this.connectionRecords.size === 0) { if (this.connectionRecords.size === 0) {
clearInterval(checkInterval); clearInterval(checkInterval);
resolve(); resolve(); // lets resolve here as early as we reach 0 remaining connections
} }
}, 1000); }, 1000);