2023-07-27 16:27:50 +02:00
# @push.rocks/smartproxy
2025-02-03 23:41:13 +01:00
2025-05-09 22:58:42 +00:00
A unified high-performance proxy toolkit for Node.js, with **SmartProxy** as the central API to handle all your proxy needs:
2025-05-10 00:01:02 +00:00
- **Unified Route-Based Configuration**: Match/action pattern for clean, consistent traffic routing
2025-05-09 22:58:42 +00:00
- **SSL/TLS Support**: Automatic HTTPS with Let's Encrypt certificate provisioning
2025-05-10 00:01:02 +00:00
- **Flexible Matching Patterns**: Route by port, domain, path, client IP, and TLS version
2025-05-09 22:58:42 +00:00
- **Advanced SNI Handling**: Smart TCP/SNI-based forwarding with IP filtering
2025-05-29 15:06:57 +00:00
- **Multiple Action Types**: Forward traffic or handle with custom socket handlers
2025-05-13 12:48:41 +00:00
- **Dynamic Port Management**: Add or remove listening ports at runtime without restart
2025-05-29 15:06:57 +00:00
- **Security Features**: Route-specific IP allowlists, blocklists, connection limits, and authentication
2025-05-15 19:39:09 +00:00
- **NFTables Integration**: High-performance kernel-level packet forwarding with Linux NFTables
2025-05-29 15:06:57 +00:00
- **Socket Handlers**: Custom socket handling for specialized protocols and use cases
2025-07-21 12:23:22 +00:00
- **Multiple Targets**: Load balancing and failover with support for multiple upstream targets
2025-05-03 13:19:23 +00:00
2025-05-09 22:11:56 +00:00
## Project Architecture Overview
2025-05-29 15:06:57 +00:00
SmartProxy has been restructured using a modern, modular architecture with a unified route-based configuration system:
2025-05-09 22:11:56 +00:00
```
/ts
├── /core # Core functionality
│ ├── /models # Data models and interfaces
│ ├── /utils # Shared utilities (IP validation, logging, etc.)
│ └── /events # Common event definitions
├── /forwarding # Forwarding system
│ ├── /handlers # Various forwarding handlers
│ │ ├── base-handler.ts # Abstract base handler
│ │ ├── http-handler.ts # HTTP-only handler
│ │ └── ... # Other handlers
│ ├── /config # Configuration models
│ └── /factory # Factory for creating handlers
├── /proxies # Different proxy implementations
│ ├── /smart-proxy # SmartProxy implementation
│ │ ├── /models # SmartProxy-specific interfaces
2025-05-10 00:01:02 +00:00
│ │ │ ├── route-types.ts # Route-based configuration types
│ │ │ └── interfaces.ts # SmartProxy interfaces
2025-05-29 15:06:57 +00:00
│ │ ├── certificate-manager.ts # SmartCertManager
2025-05-18 16:30:23 +00:00
│ │ ├── cert-store.ts # Certificate file storage
2025-05-10 00:01:02 +00:00
│ │ ├── route-helpers.ts # Helper functions for creating routes
│ │ ├── route-manager.ts # Route management system
2025-05-09 22:11:56 +00:00
│ │ ├── smart-proxy.ts # Main SmartProxy class
│ │ └── ... # Supporting classes
2025-05-19 17:28:05 +00:00
│ ├── /http-proxy # HttpProxy implementation (HTTP/HTTPS handling)
2025-05-09 22:11:56 +00:00
│ └── /nftables-proxy # NfTablesProxy implementation
├── /tls # TLS-specific functionality
│ ├── /sni # SNI handling components
│ └── /alerts # TLS alerts system
2025-05-29 15:06:57 +00:00
└── /routing # Routing functionality
└── /router # HTTP routing system
2025-05-09 22:11:56 +00:00
```
2025-05-09 22:58:42 +00:00
## Main Components
### Primary API (Recommended)
- **SmartProxy** (`ts/proxies/smart-proxy/smart-proxy.ts` )
The central unified API for all proxy needs, featuring:
2025-05-10 00:01:02 +00:00
- Route-based configuration with match/action pattern
- Flexible matching criteria (ports, domains, paths, client IPs)
2025-05-29 15:06:57 +00:00
- Multiple action types (forward, redirect, block, socket-handler)
2025-05-09 22:58:42 +00:00
- Automatic certificate management
- Advanced security controls
2025-05-29 15:06:57 +00:00
- Custom socket handling capabilities
2025-07-21 12:23:22 +00:00
- Load balancing with multiple targets
2025-05-09 22:58:42 +00:00
### Helper Functions
2025-05-29 15:06:57 +00:00
- **createHttpRoute**, **createHttpsTerminateRoute** , **createHttpsPassthroughRoute**
2025-05-10 00:01:02 +00:00
Helper functions to create different route configurations with clean syntax
2025-05-29 15:06:57 +00:00
- **createHttpToHttpsRedirect**
Helper function for HTTP to HTTPS redirects using socket handlers
- **createLoadBalancerRoute**, **createCompleteHttpsServer**
2025-05-10 00:01:02 +00:00
Helper functions for complex configurations
2025-05-29 15:06:57 +00:00
- **createSocketHandlerRoute**, **SocketHandlers**
Helper functions for custom socket handling
- **createNfTablesRoute**, **createNfTablesTerminateRoute** , **createCompleteNfTablesHttpsServer**
2025-05-15 19:39:09 +00:00
Helper functions for NFTables-based high-performance kernel-level routing
2025-05-29 15:06:57 +00:00
- **createPortMappingRoute**, **createOffsetPortMappingRoute** , **createDynamicRoute** , **createSmartLoadBalancer**
Helper functions for dynamic routing and port mapping
- **createApiGatewayRoute**, **addRateLimiting** , **addBasicAuth** , **addJwtAuth**
Helper functions for API gateway features and authentication
2025-05-09 22:58:42 +00:00
### Specialized Components
2025-05-03 13:19:23 +00:00
2025-05-19 17:28:05 +00:00
- **HttpProxy** (`ts/proxies/http-proxy/http-proxy.ts` )
2025-05-09 22:58:42 +00:00
HTTP/HTTPS reverse proxy with TLS termination and WebSocket support
2025-05-09 22:11:56 +00:00
- **NfTablesProxy** (`ts/proxies/nftables-proxy/nftables-proxy.ts` )
2025-05-09 22:58:42 +00:00
Low-level port forwarding using nftables NAT rules
2025-05-09 22:11:56 +00:00
- **SniHandler** (`ts/tls/sni/sni-handler.ts` )
2025-05-09 22:58:42 +00:00
Utilities for SNI extraction from TLS handshakes
### Core Utilities
- **ValidationUtils** (`ts/core/utils/validation-utils.ts` )
Domain, port, and configuration validation
- **IpUtils** (`ts/core/utils/ip-utils.ts` )
IP address validation and filtering with glob patterns
### Interfaces and Types
2025-05-10 00:01:02 +00:00
- `IRouteConfig` , `IRouteMatch` , `IRouteAction` (`ts/proxies/smart-proxy/models/route-types.ts` )
- `IRoutedSmartProxyOptions` (`ts/proxies/smart-proxy/models/route-types.ts` )
2025-05-19 17:28:05 +00:00
- `IHttpProxyOptions` (`ts/proxies/http-proxy/models/types.ts` )
2025-05-09 22:58:42 +00:00
- `INfTableProxySettings` (`ts/proxies/nftables-proxy/models/interfaces.ts` )
2025-05-03 13:19:23 +00:00
## Installation
Install via npm:
```bash
npm install @push .rocks/smartproxy
```
2025-05-10 15:09:58 +00:00
## Quick Start with SmartProxy
2025-05-09 22:58:42 +00:00
2025-07-21 12:23:22 +00:00
SmartProxy v20.0.0 provides a unified route-based configuration system with enhanced certificate management, NFTables integration for high-performance kernel-level routing, custom socket handling, and improved helper functions for common proxy setups.
**⚠️ Breaking Change in v20.0.0**: The route action configuration has changed from single `target` to `targets` array to support multiple upstream targets for load balancing and failover.
2025-05-09 22:58:42 +00:00
```typescript
2025-05-10 15:09:58 +00:00
import {
SmartProxy,
createHttpRoute,
createHttpsTerminateRoute,
createHttpsPassthroughRoute,
createHttpToHttpsRedirect,
createCompleteHttpsServer,
createLoadBalancerRoute,
createApiRoute,
createWebSocketRoute,
2025-05-29 15:06:57 +00:00
createSocketHandlerRoute,
2025-05-15 19:39:09 +00:00
createNfTablesRoute,
2025-05-29 15:06:57 +00:00
createNfTablesTerminateRoute,
createCompleteNfTablesHttpsServer,
createPortMappingRoute,
createOffsetPortMappingRoute,
createDynamicRoute,
createSmartLoadBalancer,
createApiGatewayRoute,
addRateLimiting,
addBasicAuth,
addJwtAuth,
SocketHandlers
2025-05-10 00:01:02 +00:00
} from '@push .rocks/smartproxy';
// Create a new SmartProxy instance with route-based configuration
2025-05-09 22:58:42 +00:00
const proxy = new SmartProxy({
2025-05-18 18:29:59 +00:00
// Global ACME settings for all routes with certificate: 'auto'
acme: {
2025-07-21 12:23:22 +00:00
email: 'ssl@example .com', // Required for Let's Encrypt
useProduction: false, // Use staging by default
renewThresholdDays: 30, // Renew 30 days before expiry
port: 80, // Port for HTTP-01 challenges (use 8080 for non-privileged)
autoRenew: true, // Enable automatic renewal
2025-05-19 17:39:35 +00:00
renewCheckIntervalHours: 24 // Check for renewals daily
2025-05-18 18:29:59 +00:00
},
2025-05-10 15:09:58 +00:00
// Define all your routing rules in a single array
2025-05-10 00:01:02 +00:00
routes: [
// Basic HTTP route - forward traffic from port 80 to internal service
2025-05-10 15:09:58 +00:00
createHttpRoute('api.example.com', { host: 'localhost', port: 3000 }),
2025-05-09 22:58:42 +00:00
2025-05-10 00:01:02 +00:00
// HTTPS route with TLS termination and automatic certificates
2025-05-10 15:09:58 +00:00
createHttpsTerminateRoute('secure.example.com', { host: 'localhost', port: 8080 }, {
2025-05-18 18:29:59 +00:00
certificate: 'auto' // Uses global ACME settings
2025-05-10 00:01:02 +00:00
}),
// HTTPS passthrough for legacy systems
2025-05-10 15:09:58 +00:00
createHttpsPassthroughRoute('legacy.example.com', { host: '192.168.1.10', port: 443 }),
// Redirect HTTP to HTTPS for all domains and subdomains
createHttpToHttpsRedirect(['example.com', '*.example.com']),
// Complete HTTPS server (creates both HTTPS route and HTTP redirect)
...createCompleteHttpsServer('complete.example.com', { host: 'localhost', port: 3000 }, {
certificate: 'auto'
2025-05-10 00:01:02 +00:00
}),
2025-05-10 15:09:58 +00:00
// API route with CORS headers
createApiRoute('api.service.com', '/v1', { host: 'api-backend', port: 8081 }, {
useTls: true,
certificate: 'auto',
addCorsHeaders: true
2025-05-10 00:01:02 +00:00
}),
2025-05-10 15:09:58 +00:00
// WebSocket route for real-time communication
createWebSocketRoute('ws.example.com', '/socket', { host: 'socket-server', port: 8082 }, {
useTls: true,
2025-05-10 00:01:02 +00:00
certificate: 'auto',
2025-05-10 15:09:58 +00:00
pingInterval: 30000
}),
// Load balancer with multiple backend servers
createLoadBalancerRoute(
'app.example.com',
['192.168.1.10', '192.168.1.11', '192.168.1.12'],
8080,
{
tls: {
mode: 'terminate',
certificate: 'auto'
2025-05-29 15:06:57 +00:00
}
2025-05-09 22:58:42 +00:00
}
2025-05-15 19:39:09 +00:00
),
2025-05-29 15:06:57 +00:00
// Custom socket handler for specialized protocols
createSocketHandlerRoute('telnet.example.com', 23, SocketHandlers.lineProtocol((line, socket) => {
console.log('Received:', line);
socket.write(`Echo: ${line}\n` );
})),
2025-05-15 19:39:09 +00:00
// High-performance NFTables route (requires root/sudo)
createNfTablesRoute('fast.example.com', { host: 'backend-server', port: 8080 }, {
ports: 80,
protocol: 'tcp',
preserveSourceIP: true,
ipAllowList: ['10.0.0.*']
}),
// NFTables HTTPS termination for ultra-fast TLS handling
createNfTablesTerminateRoute('secure-fast.example.com', { host: 'backend-ssl', port: 443 }, {
ports: 443,
certificate: 'auto',
maxRate: '100mbps'
2025-05-29 15:06:57 +00:00
}),
// Route with security configuration
{
name: 'secure-admin',
match: {
ports: 443,
domains: 'admin.example.com'
},
action: {
type: 'forward',
2025-07-21 12:23:22 +00:00
targets: [{ host: 'localhost', port: 8080 }], // Note: targets is an array
2025-05-29 15:06:57 +00:00
tls: {
mode: 'terminate',
certificate: 'auto'
}
},
security: {
ipAllowList: ['10.0.0.*', '192.168.1.*'],
ipBlockList: ['192.168.1.100'],
maxConnections: 100
}
}
2025-05-19 17:39:35 +00:00
]
2025-05-09 22:58:42 +00:00
});
// Start the proxy
await proxy.start();
2025-05-10 00:01:02 +00:00
// Dynamically add new routes later
2025-05-13 12:48:41 +00:00
await proxy.updateRoutes([
...proxy.settings.routes,
2025-05-10 15:09:58 +00:00
createHttpsTerminateRoute('new-domain.com', { host: 'localhost', port: 9000 }, {
2025-05-10 00:01:02 +00:00
certificate: 'auto'
})
2025-05-09 22:58:42 +00:00
]);
2025-05-13 12:48:41 +00:00
// Dynamically add or remove port listeners
await proxy.addListeningPort(8081);
await proxy.removeListeningPort(8081);
console.log('Currently listening on ports:', proxy.getListeningPorts());
2025-05-09 22:58:42 +00:00
// Later, gracefully shut down
await proxy.stop();
```
2025-05-10 00:01:02 +00:00
## Route-Based Configuration System
2025-05-09 22:58:42 +00:00
2025-05-29 15:06:57 +00:00
SmartProxy uses a unified route configuration system based on the `IRouteConfig` interface. This system follows a match/action pattern that makes routing more powerful, flexible, and declarative.
2025-05-10 00:06:53 +00:00
### IRouteConfig Interface
The `IRouteConfig` interface is the core building block of SmartProxy's configuration system. Each route definition consists of match criteria and an action to perform on matched traffic:
```typescript
interface IRouteConfig {
// What traffic to match (required)
match: IRouteMatch;
// What to do with matched traffic (required)
action: IRouteAction;
2025-05-29 15:06:57 +00:00
// Security configuration (optional)
security?: IRouteSecurity;
2025-05-10 00:06:53 +00:00
// Metadata (all optional)
name?: string; // Human-readable name for this route
description?: string; // Description of the route's purpose
priority?: number; // Controls matching order (higher = matched first)
tags?: string[]; // Arbitrary tags for categorization
2025-05-29 15:06:57 +00:00
enabled?: boolean; // Whether the route is active (default: true)
2025-05-10 00:06:53 +00:00
}
```
#### Match Criteria (IRouteMatch)
The `match` property defines criteria for identifying which incoming traffic should be handled by this route:
```typescript
interface IRouteMatch {
2025-07-21 12:23:22 +00:00
// Port(s) to match
ports: number | number[] | string; // Single port, array, or range like '8000-8999'
// Domain matching (optional - if not specified, matches all domains)
domains?: string | string[]; // Exact domains or patterns with wildcards
// Path matching (optional)
path?: string; // URL path pattern (supports wildcards)
// Client IP matching (optional)
clientIp?: string | string[]; // IP addresses or CIDR ranges
// Protocol matching (optional)
protocol?: 'tcp' | 'udp' | 'http' | 'https' | 'ws' | 'wss';
// TLS version matching (optional)
tlsVersion?: string | string[]; // e.g., ['TLSv1.2', 'TLSv1.3']
// Custom matcher function (optional)
customMatcher?: (context: IRouteContext) => boolean | Promise< boolean > ;
2025-05-10 00:06:53 +00:00
}
```
2025-07-21 12:23:22 +00:00
**Domain Matching Patterns:**
- Exact match: `example.com`
- Wildcard subdomain: `*.example.com`
- Multiple domains: `['example.com', '*.example.com', 'example.org']`
- All domains: omit the `domains` field
2025-05-10 00:06:53 +00:00
2025-07-21 12:23:22 +00:00
**Path Matching Patterns:**
- Exact path: `/api/users`
- Path prefix with wildcard: `/api/*`
- Path with parameter: `/api/users/:id`
- Multiple path segments: `/api/*/details`
2025-05-10 00:06:53 +00:00
2025-07-21 12:23:22 +00:00
#### Action Types (IRouteAction)
2025-05-10 00:06:53 +00:00
2025-07-21 12:23:22 +00:00
The `action` property defines what to do with matched traffic:
2025-05-10 00:06:53 +00:00
```typescript
interface IRouteAction {
// Action type (required)
2025-07-21 12:23:22 +00:00
type: 'forward' | 'redirect' | 'block' | 'socket-handler';
// For 'forward' type - array of upstream targets
targets?: IRouteTarget[];
// For 'redirect' type
redirectUrl?: string; // URL template with placeholders
redirectCode?: number; // HTTP status code (301, 302, etc.)
// For 'socket-handler' type
socketHandler?: (socket: net.Socket, context: IRouteContext) => void | Promise< void > ;
// TLS configuration (optional)
2025-05-10 00:06:53 +00:00
tls?: IRouteTls;
2025-05-29 15:06:57 +00:00
2025-07-21 12:23:22 +00:00
// WebSocket configuration (optional)
websocket?: {
enabled: boolean;
pingInterval?: number; // Milliseconds between pings
pingTimeout?: number; // Milliseconds to wait for pong
};
// Headers manipulation (optional)
headers?: {
request?: Record< string , string > ; // Headers to add to requests
response?: Record< string , string > ; // Headers to add to responses
2025-05-29 15:06:57 +00:00
};
2025-05-10 00:06:53 +00:00
}
```
2025-07-21 12:23:22 +00:00
**Forward Action with Multiple Targets:**
2025-05-29 15:06:57 +00:00
```typescript
2025-07-21 12:23:22 +00:00
{
type: 'forward',
targets: [
{ host: 'backend1.example.com', port: 8080 },
{ host: 'backend2.example.com', port: 8080 },
{ host: 'backend3.example.com', port: 8080 }
]
2025-05-29 15:06:57 +00:00
}
```
2025-07-21 12:23:22 +00:00
**Redirect Action:**
```typescript
{
type: 'redirect',
redirectUrl: 'https://{domain}/{path}', // Placeholders: {domain}, {path}, {clientIp}
redirectCode: 301
}
```
2025-05-18 18:29:59 +00:00
2025-07-21 12:23:22 +00:00
**Socket Handler Action:**
```typescript
{
type: 'socket-handler',
socketHandler: (socket, context) => {
// Custom logic for handling the socket
socket.write('Hello from custom handler\n');
socket.end();
}
}
```
2025-05-18 18:29:59 +00:00
2025-07-21 12:23:22 +00:00
### Route Examples
2025-05-18 18:29:59 +00:00
2025-07-21 12:23:22 +00:00
#### Basic HTTP Forwarding
2025-05-18 18:29:59 +00:00
```typescript
2025-07-21 12:23:22 +00:00
{
match: {
ports: 80,
domains: 'api.example.com'
2025-05-18 18:29:59 +00:00
},
2025-07-21 12:23:22 +00:00
action: {
type: 'forward',
targets: [{ host: 'localhost', port: 3000 }]
}
}
2025-05-18 18:29:59 +00:00
```
2025-07-21 12:23:22 +00:00
#### HTTPS with TLS Termination and Load Balancing
2025-05-18 18:29:59 +00:00
```typescript
{
2025-07-21 12:23:22 +00:00
match: {
ports: 443,
domains: ['secure.example.com', '*.secure.example.com']
},
2025-05-18 18:29:59 +00:00
action: {
type: 'forward',
2025-07-21 12:23:22 +00:00
targets: [
{ host: '10.0.0.10', port: 8080 },
{ host: '10.0.0.11', port: 8080 },
{ host: '10.0.0.12', port: 8080 }
],
2025-05-18 18:29:59 +00:00
tls: {
mode: 'terminate',
2025-07-21 12:23:22 +00:00
certificate: 'auto' // Automatic Let's Encrypt certificate
2025-05-18 18:29:59 +00:00
}
}
}
2025-05-29 15:06:57 +00:00
```
2025-07-21 12:23:22 +00:00
#### WebSocket Route
2025-05-10 00:06:53 +00:00
```typescript
2025-07-21 12:23:22 +00:00
{
match: {
ports: 443,
domains: 'ws.example.com',
path: '/socket/*'
},
action: {
type: 'forward',
targets: [{ host: 'websocket-server', port: 8080 }],
tls: {
mode: 'terminate',
certificate: 'auto'
},
websocket: {
enabled: true,
pingInterval: 30000,
pingTimeout: 5000
}
}
2025-05-10 00:06:53 +00:00
}
```
2025-07-21 12:23:22 +00:00
#### API Gateway with Security
2025-05-10 00:06:53 +00:00
```typescript
2025-07-21 12:23:22 +00:00
{
match: {
ports: 443,
domains: 'api.example.com',
path: '/v1/*'
},
action: {
type: 'forward',
targets: [{ host: 'api-backend', port: 8080 }],
tls: {
mode: 'terminate',
certificate: 'auto'
},
headers: {
request: {
'X-API-Version': 'v1',
'X-Real-IP': '{clientIp}'
},
response: {
'Access-Control-Allow-Origin': '*',
'X-Powered-By': 'SmartProxy'
}
}
},
security: {
ipAllowList: ['10.0.0.0/8', '172.16.0.0/12'],
rateLimit: {
maxRequests: 100,
windowMs: 60000
},
authentication: {
type: 'basic',
realm: 'API Access',
users: {
'apiuser': 'hashedpassword'
}
}
}
2025-05-10 00:06:53 +00:00
}
```
2025-07-21 12:23:22 +00:00
## NFTables Integration
2025-05-10 00:06:53 +00:00
2025-07-21 12:23:22 +00:00
SmartProxy includes high-performance kernel-level packet forwarding using Linux NFTables. This provides ultra-low latency forwarding by operating at the kernel level.
2025-05-15 19:39:09 +00:00
2025-07-21 12:23:22 +00:00
### Requirements
- Linux kernel with NFTables support
- Root/sudo privileges
- `nft` command-line tool installed
2025-05-15 19:39:09 +00:00
2025-07-21 12:23:22 +00:00
### NFTables Route Example
2025-05-10 00:06:53 +00:00
```typescript
2025-07-21 12:23:22 +00:00
// Basic NFTables forwarding
createNfTablesRoute('fast.example.com', { host: 'backend', port: 8080 }, {
ports: 80,
protocol: 'tcp',
preserveSourceIP: true
})
2025-05-10 00:06:53 +00:00
2025-07-21 12:23:22 +00:00
// NFTables with TLS termination
createNfTablesTerminateRoute('secure-fast.example.com', { host: 'backend', port: 8080 }, {
ports: 443,
certificate: 'auto',
maxRate: '100mbps'
})
2025-05-29 15:06:57 +00:00
```
2025-07-21 12:23:22 +00:00
## Socket Handlers
2025-05-29 15:06:57 +00:00
2025-07-21 12:23:22 +00:00
SmartProxy supports custom socket handlers for implementing specialized protocols or custom logic:
2025-05-29 15:06:57 +00:00
2025-07-21 12:23:22 +00:00
### Pre-built Socket Handlers
2025-05-10 00:06:53 +00:00
```typescript
2025-05-29 15:06:57 +00:00
// Echo server
2025-07-21 12:23:22 +00:00
createSocketHandlerRoute('echo.example.com', 7, SocketHandlers.echo)
2025-05-29 15:06:57 +00:00
2025-07-21 12:23:22 +00:00
// HTTP redirect
createHttpToHttpsRedirect('example.com')
2025-05-29 15:06:57 +00:00
// Line-based protocol
createSocketHandlerRoute('telnet.example.com', 23, SocketHandlers.lineProtocol((line, socket) => {
socket.write(`You said: ${line}\n` );
2025-07-21 12:23:22 +00:00
}))
2025-05-29 15:06:57 +00:00
2025-07-21 12:23:22 +00:00
// HTTP server for custom logic
createSocketHandlerRoute('custom.example.com', 8080, SocketHandlers.httpServer((req, res) => {
2025-05-29 15:06:57 +00:00
if (req.url === '/health') {
res.status(200);
res.send('OK');
} else {
res.status(404);
res.send('Not Found');
}
2025-07-21 12:23:22 +00:00
res.end();
2025-05-29 15:06:57 +00:00
}))
2025-07-21 12:23:22 +00:00
// Block connections
createSocketHandlerRoute('blocked.example.com', 443, SocketHandlers.block('Access Denied'))
2025-05-29 15:06:57 +00:00
2025-07-21 12:23:22 +00:00
// TCP proxy
createSocketHandlerRoute('proxy.example.com', 8080, SocketHandlers.proxy('internal-server', 3000))
2025-05-29 15:06:57 +00:00
```
2025-07-21 12:23:22 +00:00
### Custom Socket Handler
2025-05-29 15:06:57 +00:00
```typescript
2025-07-21 12:23:22 +00:00
{
match: {
ports: 9999,
domains: 'custom.example.com'
},
action: {
type: 'socket-handler',
socketHandler: async (socket, context) => {
console.log(`New connection from ${context.clientIp} to ${context.domain}` );
socket.write('Welcome to the custom protocol server\n');
socket.on('data', (data) => {
// Process incoming data
const command = data.toString().trim();
if (command === 'QUIT') {
socket.end('Goodbye\n');
} else {
socket.write(`Unknown command: ${command}\n` );
}
});
socket.on('error', (err) => {
console.error('Socket error:', err);
});
}
}
2025-05-10 00:06:53 +00:00
}
```
2025-07-21 12:23:22 +00:00
## Dynamic Port Management
2025-05-10 00:06:53 +00:00
2025-07-21 12:23:22 +00:00
SmartProxy allows you to dynamically add or remove listening ports without restarting:
2025-05-10 00:06:53 +00:00
```typescript
2025-07-21 12:23:22 +00:00
// Add a new listening port
await proxy.addListeningPort(8443);
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
// Remove a listening port
await proxy.removeListeningPort(8080);
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
// Get all currently listening ports
const ports = proxy.getListeningPorts(); // [80, 443, 8443]
2025-06-12 16:59:25 +00:00
```
2025-07-21 12:23:22 +00:00
## Certificate Management
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
SmartProxy includes automatic certificate management with Let's Encrypt support:
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
### Automatic Certificates (Let's Encrypt)
2025-06-12 16:59:25 +00:00
```typescript
{
action: {
2025-07-21 12:23:22 +00:00
tls: {
mode: 'terminate',
certificate: 'auto' // Automatic Let's Encrypt certificate
2025-06-12 16:59:25 +00:00
}
}
}
```
2025-07-21 12:23:22 +00:00
### Manual Certificates
2025-06-12 16:59:25 +00:00
```typescript
{
action: {
2025-07-21 12:23:22 +00:00
tls: {
mode: 'terminate',
certificate: {
key: fs.readFileSync('./certs/private.key', 'utf8'),
cert: fs.readFileSync('./certs/certificate.crt', 'utf8')
}
2025-06-12 16:59:25 +00:00
}
}
}
```
2025-07-21 12:23:22 +00:00
### Certificate Store
Certificates are automatically stored and managed:
- Auto certificates: `./certificates/{domain}/`
- Manual certificates: In-memory only
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
## Security Features
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
### IP-Based Access Control
2025-06-12 16:59:25 +00:00
```typescript
{
2025-07-21 12:23:22 +00:00
security: {
ipAllowList: ['10.0.0.0/8', '192.168.*', '::1'],
ipBlockList: ['192.168.1.100', '10.0.0.0/24']
2025-06-12 16:59:25 +00:00
}
}
```
2025-07-21 12:23:22 +00:00
### Connection Limits
2025-06-12 16:59:25 +00:00
```typescript
{
2025-07-21 12:23:22 +00:00
security: {
maxConnections: 1000, // Total connections
maxConnectionsPerIp: 10 // Per IP address
2025-06-12 16:59:25 +00:00
}
}
```
2025-07-21 12:23:22 +00:00
### Rate Limiting
2025-06-12 16:59:25 +00:00
```typescript
{
2025-07-21 12:23:22 +00:00
security: {
rateLimit: {
maxRequests: 100, // Maximum requests
windowMs: 60000 // Time window (1 minute)
2025-06-12 16:59:25 +00:00
}
}
}
```
2025-07-21 12:23:22 +00:00
### Authentication
2025-06-12 16:59:25 +00:00
```typescript
2025-07-21 12:23:22 +00:00
// Basic Authentication
2025-06-12 16:59:25 +00:00
{
2025-07-21 12:23:22 +00:00
security: {
authentication: {
type: 'basic',
realm: 'Protected Area',
users: {
'admin': 'hashedpassword'
2025-06-12 16:59:25 +00:00
}
}
}
}
2025-07-21 12:23:22 +00:00
// JWT Authentication
{
security: {
authentication: {
type: 'jwt',
secret: 'your-secret-key',
algorithms: ['HS256']
}
}
}
```
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
## Advanced Features
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
### Custom Route Matching
2025-06-12 16:59:25 +00:00
```typescript
{
2025-07-21 12:23:22 +00:00
match: {
ports: 443,
customMatcher: async (context) => {
// Custom logic to determine if route should match
const hour = new Date().getHours();
return hour >= 9 & & hour < 17 ; / / Only match during business hours
2025-06-12 16:59:25 +00:00
}
}
}
```
2025-07-21 12:23:22 +00:00
### Header Manipulation
2025-06-12 16:59:25 +00:00
```typescript
{
action: {
2025-07-21 12:23:22 +00:00
headers: {
request: {
'X-Real-IP': '{clientIp}',
'X-Forwarded-For': '{clientIp}',
'X-Custom-Header': 'value'
},
response: {
'X-Powered-By': 'SmartProxy',
'Strict-Transport-Security': 'max-age=31536000'
}
2025-06-12 16:59:25 +00:00
}
}
}
```
2025-07-21 12:23:22 +00:00
### Dynamic Target Selection
```typescript
{
action: {
type: 'forward',
targets: [
{
host: ['backend1.example.com', 'backend2.example.com'], // Round-robin
port: (context) => {
// Dynamic port based on path
return context.path.startsWith('/api/v1') ? 8081 : 8080;
}
}
]
}
}
```
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
## Complete Examples
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
### Multi-Domain HTTPS Server with Redirects
```typescript
const proxy = new SmartProxy({
acme: {
email: 'admin@example .com',
useProduction: true
},
routes: [
// HTTPS routes
...['example.com', 'app.example.com', 'api.example.com'].map(domain =>
createHttpsTerminateRoute(domain, { host: 'localhost', port: 3000 }, {
certificate: 'auto'
})
),
// HTTP to HTTPS redirects
createHttpToHttpsRedirect(['example.com', '*.example.com'])
]
});
```
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
### API Gateway with Multiple Services
2025-06-12 16:59:25 +00:00
```typescript
const proxy = new SmartProxy({
routes: [
2025-07-21 12:23:22 +00:00
// User service
createApiRoute('api.example.com', '/users', { host: 'user-service', port: 8081 }),
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
// Product service
createApiRoute('api.example.com', '/products', { host: 'product-service', port: 8082 }),
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
// Order service with authentication
2025-06-12 16:59:25 +00:00
{
2025-07-21 12:23:22 +00:00
match: {
ports: 443,
domains: 'api.example.com',
path: '/orders/*'
},
2025-06-12 16:59:25 +00:00
action: {
type: 'forward',
2025-07-21 12:23:22 +00:00
targets: [{ host: 'order-service', port: 8083 }],
2025-06-12 16:59:25 +00:00
tls: {
2025-07-21 12:23:22 +00:00
mode: 'terminate',
2025-06-12 16:59:25 +00:00
certificate: 'auto'
}
},
security: {
2025-07-21 12:23:22 +00:00
authentication: {
type: 'jwt',
secret: process.env.JWT_SECRET
2025-06-12 16:59:25 +00:00
}
}
}
]
});
```
2025-07-21 12:23:22 +00:00
### WebSocket Server with Load Balancing
2025-06-12 16:59:25 +00:00
```typescript
const proxy = new SmartProxy({
routes: [
{
2025-07-21 12:23:22 +00:00
match: {
ports: 443,
domains: 'ws.example.com'
},
2025-06-12 16:59:25 +00:00
action: {
type: 'forward',
2025-07-21 12:23:22 +00:00
targets: [
{ host: 'ws-server-1', port: 8080 },
{ host: 'ws-server-2', port: 8080 },
{ host: 'ws-server-3', port: 8080 }
],
tls: {
mode: 'terminate',
certificate: 'auto'
},
websocket: {
enabled: true,
pingInterval: 30000
2025-06-12 16:59:25 +00:00
}
}
}
]
});
```
2025-07-21 12:23:22 +00:00
## Troubleshooting
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
### Common Issues
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
#### Certificate Provisioning
- Ensure domains are publicly accessible
- Check firewall rules for port 80 (ACME challenges)
- Verify DNS resolution
- Check ACME email configuration
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
#### Connection Issues
- Verify route matching criteria
- Check security rules (IP lists, authentication)
- Ensure target servers are accessible
- Check for port conflicts
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
#### Performance Issues
- Consider using NFTables for high-traffic routes
- Adjust connection pool sizes
- Enable connection keep-alive
- Monitor resource usage
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
### Debug Mode
Enable detailed logging:
2025-06-12 16:59:25 +00:00
```typescript
2025-07-21 12:23:22 +00:00
const proxy = new SmartProxy({
debug: true,
routes: [...]
});
2025-06-12 16:59:25 +00:00
```
2025-07-21 12:23:22 +00:00
### Route Testing
Test route matching:
2025-06-12 16:59:25 +00:00
```typescript
2025-07-21 12:23:22 +00:00
const matchedRoute = proxy.findMatchingRoute({
port: 443,
domain: 'example.com',
path: '/api/users',
clientIp: '192.168.1.100'
});
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
console.log('Matched route:', matchedRoute?.name);
2025-06-12 16:59:25 +00:00
```
2025-07-21 12:23:22 +00:00
## Migration Guide
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
### From v19.x to v20.x
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
The main breaking change is the route action configuration:
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
**Before (v19.x):**
2025-06-12 16:59:25 +00:00
```typescript
{
action: {
type: 'forward',
2025-07-21 12:23:22 +00:00
target: { host: 'localhost', port: 8080 } // Single target
2025-06-12 16:59:25 +00:00
}
}
```
2025-07-21 12:23:22 +00:00
**After (v20.x):**
2025-06-12 16:59:25 +00:00
```typescript
{
action: {
type: 'forward',
2025-07-21 12:23:22 +00:00
targets: [{ host: 'localhost', port: 8080 }] // Array of targets
2025-06-12 16:59:25 +00:00
}
}
```
2025-07-21 12:23:22 +00:00
Helper functions have been updated to use the new format automatically.
2025-06-09 15:14:13 +00:00
2025-07-21 12:23:22 +00:00
## Best Practices
2025-06-09 15:14:13 +00:00
2025-07-21 12:23:22 +00:00
1. **Use Helper Functions** : They provide sensible defaults and reduce configuration errors
2. **Set Route Priorities** : Higher priority routes are matched first
3. **Use Specific Matches** : More specific routes should have higher priorities
4. **Enable Security Features** : Always use IP filtering and rate limiting for public services
5. **Monitor Performance** : Use debug logging and metrics to identify bottlenecks
6. **Regular Certificate Checks** : Monitor certificate expiration and renewal
7. **Graceful Shutdown** : Always call `proxy.stop()` for clean shutdown
2025-06-22 23:10:56 +00:00
2025-07-21 12:23:22 +00:00
## API Reference
2025-06-09 15:14:13 +00:00
2025-07-21 12:23:22 +00:00
### SmartProxy Class
2025-06-09 15:14:13 +00:00
2025-06-22 23:10:56 +00:00
```typescript
2025-07-21 12:23:22 +00:00
class SmartProxy {
constructor(options: IRoutedSmartProxyOptions);
// Lifecycle methods
start(): Promise< void > ;
stop(): Promise< void > ;
// Route management
updateRoutes(routes: IRouteConfig[]): Promise< void > ;
addRoute(route: IRouteConfig): Promise< void > ;
removeRoute(routeName: string): Promise< void > ;
findMatchingRoute(context: Partial< IRouteContext > ): IRouteConfig | null;
// Port management
addListeningPort(port: number): Promise< void > ;
removeListeningPort(port: number): Promise< void > ;
getListeningPorts(): number[];
// Certificate management
getCertificateInfo(domain: string): ICertificateInfo | null;
renewCertificate(domain: string): Promise< void > ;
// Status and monitoring
getStatus(): IProxyStatus;
getMetrics(): IProxyMetrics;
2025-06-09 15:14:13 +00:00
}
2025-06-22 23:10:56 +00:00
```
2025-06-13 17:22:31 +00:00
2025-07-21 12:23:22 +00:00
### Route Configuration Types
2025-06-13 17:22:31 +00:00
2025-07-21 12:23:22 +00:00
See the TypeScript definitions in:
- `ts/proxies/smart-proxy/models/route-types.ts`
- `ts/proxies/smart-proxy/models/interfaces.ts`
2025-06-13 17:22:31 +00:00
2025-07-21 12:23:22 +00:00
## Contributing
2025-06-22 23:10:56 +00:00
2025-07-21 12:23:22 +00:00
Contributions are welcome! Please follow these guidelines:
2025-06-22 23:10:56 +00:00
2025-07-21 12:23:22 +00:00
1. Fork the repository
2. Create a feature branch
3. Write tests for new functionality
4. Ensure all tests pass
5. Submit a pull request
2025-03-07 14:34:49 +00:00
2024-04-14 18:10:41 +02:00
## License and Legal Information
2025-02-25 00:56:01 +00:00
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license ](license ) file within this repository.
2024-04-14 18:10:41 +02:00
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
### Trademarks
2020-02-23 19:04:53 +00:00
2024-04-14 18:10:41 +02:00
This project is owned and maintained by Task Venture Capital GmbH. The names and logos associated with Task Venture Capital GmbH and any related products or services are trademarks of Task Venture Capital GmbH and are not included within the scope of the MIT license granted herein. Use of these trademarks must comply with Task Venture Capital GmbH's Trademark Guidelines, and any usage must be approved in writing by Task Venture Capital GmbH.
2020-02-23 19:04:53 +00:00
2024-04-14 18:10:41 +02:00
### Company Information
2020-02-07 13:04:11 +00:00
2024-04-14 18:10:41 +02:00
Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany
2020-02-07 13:04:11 +00:00
2024-04-14 18:10:41 +02:00
For any legal inquiries or if you require further information, please contact us via email at hello@task .vc.
2019-08-20 18:43:15 +02:00
2025-03-05 18:47:38 +00:00
By using this repository, you acknowledge that you have read this section, agree to comply with its terms, and understand that the licensing of the code does not imply endorsement by Task Venture Capital GmbH of any derivative works.