fix(routing): unify route based architecture

This commit is contained in:
2025-05-13 12:48:41 +00:00
parent fe632bde67
commit fcc8cf9caa
46 changed files with 7943 additions and 1332 deletions

116
readme.md
View File

@ -7,6 +7,7 @@ A unified high-performance proxy toolkit for Node.js, with **SmartProxy** as the
- **Flexible Matching Patterns**: Route by port, domain, path, client IP, and TLS version
- **Advanced SNI Handling**: Smart TCP/SNI-based forwarding with IP filtering
- **Multiple Action Types**: Forward (with TLS modes), redirect, or block traffic
- **Dynamic Port Management**: Add or remove listening ports at runtime without restart
- **Security Features**: IP allowlists, connection limits, timeouts, and more
## Project Architecture Overview
@ -211,12 +212,18 @@ proxy.on('certificate', evt => {
await proxy.start();
// Dynamically add new routes later
await proxy.addRoutes([
await proxy.updateRoutes([
...proxy.settings.routes,
createHttpsTerminateRoute('new-domain.com', { host: 'localhost', port: 9000 }, {
certificate: 'auto'
})
]);
// Dynamically add or remove port listeners
await proxy.addListeningPort(8081);
await proxy.removeListeningPort(8081);
console.log('Currently listening on ports:', proxy.getListeningPorts());
// Later, gracefully shut down
await proxy.stop();
```
@ -557,12 +564,37 @@ Available helper functions:
})
```
8. **Dynamic Port Management**
```typescript
// Start the proxy with initial configuration
const proxy = new SmartProxy({
routes: [
createHttpRoute('example.com', { host: 'localhost', port: 8080 })
]
});
await proxy.start();
// Dynamically add a new port listener
await proxy.addListeningPort(8081);
// Add a route for the new port
const currentRoutes = proxy.settings.routes;
const newRoute = createHttpRoute('api.example.com', { host: 'api-server', port: 3000 });
newRoute.match.ports = 8081; // Override the default port
// Update routes - will automatically sync port listeners
await proxy.updateRoutes([...currentRoutes, newRoute]);
// Later, remove a port listener when needed
await proxy.removeListeningPort(8081);
```
## Other Components
While SmartProxy provides a unified API for most needs, you can also use individual components:
### NetworkProxy
For HTTP/HTTPS reverse proxy with TLS termination and WebSocket support:
For HTTP/HTTPS reverse proxy with TLS termination and WebSocket support. Now with native route-based configuration support:
```typescript
import { NetworkProxy } from '@push.rocks/smartproxy';
@ -570,9 +602,49 @@ import * as fs from 'fs';
const proxy = new NetworkProxy({ port: 443 });
await proxy.start();
// Modern route-based configuration (recommended)
await proxy.updateRouteConfigs([
{
match: {
ports: 443,
domains: 'example.com'
},
action: {
type: 'forward',
target: {
host: '127.0.0.1',
port: 3000
},
tls: {
mode: 'terminate',
certificate: {
cert: fs.readFileSync('cert.pem', 'utf8'),
key: fs.readFileSync('key.pem', 'utf8')
}
},
advanced: {
headers: {
'X-Forwarded-By': 'NetworkProxy'
},
urlRewrite: {
pattern: '^/old/(.*)$',
target: '/new/$1',
flags: 'g'
}
},
websocket: {
enabled: true,
pingInterval: 30000
}
}
}
]);
// Legacy configuration (for backward compatibility)
await proxy.updateProxyConfigs([
{
hostName: 'example.com',
hostName: 'legacy.example.com',
destinationIps: ['127.0.0.1'],
destinationPorts: [3000],
publicKey: fs.readFileSync('cert.pem', 'utf8'),
@ -1084,18 +1156,34 @@ createRedirectRoute({
- Socket opts: `noDelay`, `keepAlive`, `enableKeepAliveProbes`
- `certProvisionFunction` (callback) - Custom certificate provisioning
#### SmartProxy Dynamic Port Management Methods
- `async addListeningPort(port: number)` - Add a new port listener without changing routes
- `async removeListeningPort(port: number)` - Remove a port listener without changing routes
- `getListeningPorts()` - Get all ports currently being listened on
- `async updateRoutes(routes: IRouteConfig[])` - Update routes and automatically adjust port listeners
### NetworkProxy (INetworkProxyOptions)
- `port` (number, required)
- `backendProtocol` ('http1'|'http2', default 'http1')
- `maxConnections` (number, default 10000)
- `keepAliveTimeout` (ms, default 120000)
- `headersTimeout` (ms, default 60000)
- `cors` (object)
- `connectionPoolSize` (number, default 50)
- `logLevel` ('error'|'warn'|'info'|'debug')
- `acme` (IAcmeOptions)
- `useExternalPort80Handler` (boolean)
- `portProxyIntegration` (boolean)
- `port` (number, required) - Main port to listen on
- `backendProtocol` ('http1'|'http2', default 'http1') - Protocol to use with backend servers
- `maxConnections` (number, default 10000) - Maximum concurrent connections
- `keepAliveTimeout` (ms, default 120000) - Connection keep-alive timeout
- `headersTimeout` (ms, default 60000) - Timeout for receiving complete headers
- `cors` (object) - Cross-Origin Resource Sharing configuration
- `connectionPoolSize` (number, default 50) - Size of the connection pool for backend servers
- `logLevel` ('error'|'warn'|'info'|'debug') - Logging verbosity level
- `acme` (IAcmeOptions) - ACME certificate configuration
- `useExternalPort80Handler` (boolean) - Use external port 80 handler for ACME challenges
- `portProxyIntegration` (boolean) - Integration with other proxies
#### NetworkProxy Enhanced Features
NetworkProxy now supports full route-based configuration including:
- Advanced request and response header manipulation
- URL rewriting with RegExp pattern matching
- Template variable resolution for dynamic values (e.g. `{domain}`, `{clientIp}`)
- Function-based dynamic target resolution
- Security features (IP filtering, rate limiting, authentication)
- WebSocket configuration with path rewriting, custom headers, ping control, and size limits
- Context-aware CORS configuration
### Port80Handler (IAcmeOptions)
- `enabled` (boolean, default true)