2025-08-14 14:30:54 +00:00
# @push.rocks/smartproxy 🚀
2025-02-03 23:41:13 +01:00
2025-08-14 14:30:54 +00:00
**The Swiss Army Knife of Node.js Proxies** - A unified, high-performance proxy toolkit that handles everything from simple HTTP forwarding to complex enterprise routing scenarios.
2025-05-09 22:58:42 +00:00
2025-08-14 14:30:54 +00:00
## 🎯 What is SmartProxy?
2025-05-03 13:19:23 +00:00
2025-08-14 14:30:54 +00:00
SmartProxy is a modern, production-ready proxy solution that brings order to the chaos of traffic management. Whether you're building microservices, deploying edge infrastructure, or need a battle-tested reverse proxy, SmartProxy has you covered.
2025-05-09 22:11:56 +00:00
2025-08-14 14:30:54 +00:00
### ⚡ Key Features
2025-05-09 22:11:56 +00:00
2025-08-14 14:30:54 +00:00
- **🔀 Unified Route-Based Configuration** - Clean match/action patterns for intuitive traffic routing
- **🔒 Automatic SSL/TLS with Let's Encrypt** - Zero-config HTTPS with automatic certificate provisioning
- **🎯 Flexible Matching Patterns** - Route by port, domain, path, client IP, TLS version, or custom logic
- **🚄 High-Performance Forwarding** - Choose between user-space or kernel-level (NFTables) forwarding
- **⚖️ Built-in Load Balancing** - Distribute traffic across multiple backends with health checks
- **🛡️ Enterprise Security** - IP filtering, rate limiting, authentication, and connection limits
- **🔌 WebSocket Support** - First-class WebSocket proxying with ping/pong management
- **🎮 Custom Socket Handlers** - Implement any protocol with full socket control
- **📊 Dynamic Port Management** - Add/remove ports at runtime without restarts
- **🔧 Protocol Detection** - Smart protocol detection for mixed-mode operation
2025-05-09 22:58:42 +00:00
2025-08-14 14:30:54 +00:00
## 📦 Installation
2025-05-09 22:58:42 +00:00
2025-05-03 13:19:23 +00:00
```bash
npm install @push .rocks/smartproxy
```
2025-08-14 14:30:54 +00:00
## 🚀 Quick Start
2025-05-09 22:58:42 +00:00
2025-08-14 14:30:54 +00:00
Let's get you up and running in 30 seconds:
2025-05-09 22:58:42 +00:00
```typescript
2025-08-14 14:30:54 +00:00
import { SmartProxy, createCompleteHttpsServer } from '@push .rocks/smartproxy';
2025-05-10 00:01:02 +00:00
2025-08-14 14:30:54 +00:00
// Create a proxy with automatic HTTPS
2025-05-09 22:58:42 +00:00
const proxy = new SmartProxy({
2025-05-18 18:29:59 +00:00
acme: {
2025-08-14 14:30:54 +00:00
email: 'ssl@example .com', // Your email for Let's Encrypt
useProduction: true // Use Let's Encrypt production servers
2025-05-18 18:29:59 +00:00
},
2025-05-10 00:01:02 +00:00
routes: [
2025-08-14 14:30:54 +00:00
// Complete HTTPS setup with one line
...createCompleteHttpsServer('app.example.com', {
host: 'localhost',
port: 3000
}, {
certificate: 'auto' // Magic! 🎩
})
2025-05-19 17:39:35 +00:00
]
2025-05-09 22:58:42 +00:00
});
await proxy.start();
2025-08-14 14:30:54 +00:00
console.log('🚀 Proxy running with automatic HTTPS!');
2025-05-10 00:06:53 +00:00
```
2025-08-14 14:30:54 +00:00
## 📚 Core Concepts
2025-05-10 00:06:53 +00:00
2025-08-14 14:30:54 +00:00
### 🏗️ Route-Based Architecture
2025-05-10 00:06:53 +00:00
2025-08-14 14:30:54 +00:00
SmartProxy uses a powerful match/action pattern that makes routing predictable and maintainable:
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',
2025-08-14 14:30:54 +00:00
targets: [{ host: 'backend', port: 8080 }],
tls: { mode: 'terminate', certificate: 'auto' }
2025-07-21 12:23:22 +00:00
}
2025-05-10 00:06:53 +00:00
}
```
2025-08-14 14:30:54 +00:00
Every route has:
- **Match criteria** - What traffic to capture
- **Action** - What to do with it
- **Security** (optional) - Access controls and limits
- **Metadata** (optional) - Name, priority, tags
2025-05-10 00:06:53 +00:00
2025-08-14 14:30:54 +00:00
## 💡 Common Use Cases
2025-05-15 19:39:09 +00:00
2025-08-14 14:30:54 +00:00
### 🌐 Simple HTTP to HTTPS Redirect
2025-05-15 19:39:09 +00:00
2025-05-10 00:06:53 +00:00
```typescript
2025-08-14 14:30:54 +00:00
import { SmartProxy, createHttpToHttpsRedirect } from '@push .rocks/smartproxy';
2025-05-29 15:06:57 +00:00
2025-08-14 14:30:54 +00:00
const proxy = new SmartProxy({
routes: [
// Redirect all HTTP traffic to HTTPS
createHttpToHttpsRedirect(['example.com', '*.example.com'])
]
});
```
2025-05-29 15:06:57 +00:00
2025-08-14 14:30:54 +00:00
### ⚖️ Load Balancer with Health Checks
2025-05-10 00:06:53 +00:00
```typescript
2025-08-14 14:30:54 +00:00
import { createLoadBalancerRoute } from '@push .rocks/smartproxy';
2025-05-29 15:06:57 +00:00
2025-08-14 14:30:54 +00:00
const route = createLoadBalancerRoute(
'app.example.com',
[
{ host: 'server1.internal', port: 8080 },
{ host: 'server2.internal', port: 8080 },
{ host: 'server3.internal', port: 8080 }
],
{
tls: { mode: 'terminate', certificate: 'auto' },
loadBalancing: {
algorithm: 'round-robin',
healthCheck: {
path: '/health',
interval: 30000,
timeout: 5000
}
}
}
);
2025-05-29 15:06:57 +00:00
```
2025-08-14 14:30:54 +00:00
### 🔌 WebSocket Proxy
2025-05-29 15:06:57 +00:00
```typescript
2025-08-14 14:30:54 +00:00
import { createWebSocketRoute } from '@push .rocks/smartproxy';
const route = createWebSocketRoute(
'ws.example.com',
{ host: 'websocket-server', port: 8080 },
{
path: '/socket',
useTls: true,
certificate: 'auto',
pingInterval: 30000 // Keep connections alive
2025-07-21 12:23:22 +00:00
}
2025-08-14 14:30:54 +00:00
);
2025-05-10 00:06:53 +00:00
```
2025-08-14 14:30:54 +00:00
### 🚦 API Gateway with Rate Limiting
2025-05-10 00:06:53 +00:00
```typescript
2025-08-14 14:30:54 +00:00
import { createApiGatewayRoute, addRateLimiting } from '@push .rocks/smartproxy';
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
let route = createApiGatewayRoute(
'api.example.com',
'/api',
{ host: 'api-backend', port: 8080 },
{
useTls: true,
certificate: 'auto',
addCorsHeaders: true
}
);
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
// Add rate limiting
route = addRateLimiting(route, {
maxRequests: 100,
window: 60, // seconds
keyBy: 'ip'
});
2025-06-12 16:59:25 +00:00
```
2025-08-14 14:30:54 +00:00
### 🎮 Custom Protocol Handler
2025-06-12 16:59:25 +00:00
```typescript
2025-08-14 14:30:54 +00:00
import { createSocketHandlerRoute, SocketHandlers } from '@push .rocks/smartproxy';
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
// Pre-built handlers
const echoRoute = createSocketHandlerRoute(
'echo.example.com',
7777,
SocketHandlers.echo
);
// Custom handler
const customRoute = createSocketHandlerRoute(
'custom.example.com',
9999,
async (socket, context) => {
console.log(`Connection from ${context.clientIp}` );
socket.write('Welcome to my custom protocol!\n');
socket.on('data', (data) => {
const command = data.toString().trim();
if (command === 'HELLO') {
socket.write('World!\n');
} else if (command === 'EXIT') {
socket.end('Goodbye!\n');
2025-07-21 12:23:22 +00:00
}
2025-08-14 14:30:54 +00:00
});
2025-06-12 16:59:25 +00:00
}
2025-08-14 14:30:54 +00:00
);
2025-06-12 16:59:25 +00:00
```
2025-08-14 14:30:54 +00:00
### ⚡ High-Performance NFTables Forwarding
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
For ultra-low latency, use kernel-level forwarding (Linux only, requires root):
2025-06-12 16:59:25 +00:00
```typescript
2025-08-14 14:30:54 +00:00
import { createNfTablesTerminateRoute } from '@push .rocks/smartproxy';
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
const route = createNfTablesTerminateRoute(
'fast.example.com',
{ host: 'backend', port: 8080 },
{
ports: 443,
certificate: 'auto',
preserveSourceIP: true,
maxRate: '1gbps'
2025-06-12 16:59:25 +00:00
}
2025-08-14 14:30:54 +00:00
);
2025-06-12 16:59:25 +00:00
```
2025-08-14 14:30:54 +00:00
## 🔧 Advanced Features
### 🎯 Dynamic Routing
Route traffic based on runtime conditions:
2025-06-12 16:59:25 +00:00
```typescript
{
2025-08-14 14:30:54 +00:00
match: {
ports: 443,
customMatcher: async (context) => {
// Route based on time of day
const hour = new Date().getHours();
return hour >= 9 & & hour < 17 ; / / Business hours only
2025-06-12 16:59:25 +00:00
}
2025-08-14 14:30:54 +00:00
},
action: {
type: 'forward',
targets: [{
host: (context) => {
// Dynamic host selection
return context.path.startsWith('/premium')
? 'premium-backend'
: 'standard-backend';
},
port: 8080
}]
2025-06-12 16:59:25 +00:00
}
}
```
2025-08-14 14:30:54 +00:00
### 🔒 Security Controls
Comprehensive security options per route:
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
```typescript
2025-07-21 12:23:22 +00:00
{
security: {
2025-08-14 14:30:54 +00:00
// IP-based access control
ipAllowList: ['10.0.0.0/8', '192.168.*'],
ipBlockList: ['192.168.1.100'],
// Connection limits
maxConnections: 1000,
maxConnectionsPerIp: 10,
// Rate limiting
rateLimit: {
maxRequests: 100,
windowMs: 60000
},
// Authentication
2025-07-21 12:23:22 +00:00
authentication: {
type: 'jwt',
2025-08-14 14:30:54 +00:00
secret: process.env.JWT_SECRET,
2025-07-21 12:23:22 +00:00
algorithms: ['HS256']
}
}
}
```
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
### 📊 Runtime Management
Control your proxy without restarts:
2025-06-12 16:59:25 +00:00
```typescript
2025-08-14 14:30:54 +00:00
// Add/remove ports dynamically
await proxy.addListeningPort(8443);
await proxy.removeListeningPort(8080);
// Update routes on the fly
await proxy.updateRoutes([...newRoutes]);
// Monitor status
const status = proxy.getStatus();
const metrics = proxy.getMetrics();
// Certificate management
await proxy.renewCertificate('example.com');
const certInfo = proxy.getCertificateInfo('example.com');
2025-06-12 16:59:25 +00:00
```
2025-08-14 14:30:54 +00:00
### 🔄 Header Manipulation
Transform requests and responses:
2025-06-12 16:59:25 +00:00
```typescript
{
action: {
2025-07-21 12:23:22 +00:00
headers: {
request: {
2025-08-14 14:30:54 +00:00
'X-Real-IP': '{clientIp}', // Template variables
'X-Request-ID': '{uuid}',
'X-Custom': 'value'
2025-07-21 12:23:22 +00:00
},
response: {
'X-Powered-By': 'SmartProxy',
2025-08-14 14:30:54 +00:00
'Strict-Transport-Security': 'max-age=31536000',
'X-Frame-Options': 'DENY'
2025-07-21 12:23:22 +00:00
}
2025-06-12 16:59:25 +00:00
}
}
}
```
2025-08-14 14:30:54 +00:00
## 🏛️ Architecture
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
SmartProxy is built with a modular, extensible architecture:
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
```
2025-08-14 14:30:54 +00:00
SmartProxy
├── 📋 Route Manager # Route matching and prioritization
├── 🔌 Port Manager # Dynamic port lifecycle
├── 🔒 Certificate Manager # ACME/Let's Encrypt automation
├── 🚦 Connection Manager # Connection pooling and limits
├── 📊 Metrics Collector # Performance monitoring
├── 🛡️ Security Manager # Access control and rate limiting
└── 🔧 Protocol Detectors # Smart protocol identification
```
## 🎯 Route Configuration Reference
### Match Criteria
2025-06-12 16:59:25 +00:00
```typescript
2025-08-14 14:30:54 +00:00
interface IRouteMatch {
ports: number | number[] | string; // 80, [80, 443], '8000-8999'
domains?: string | string[]; // 'example.com', '*.example.com'
path?: string; // '/api/*', '/users/:id'
clientIp?: string | string[]; // '10.0.0.0/8', ['192.168.*']
protocol?: 'tcp' | 'udp' | 'http' | 'https' | 'ws' | 'wss';
tlsVersion?: string | string[]; // ['TLSv1.2', 'TLSv1.3']
customMatcher?: (context) => boolean; // Custom logic
}
2025-06-12 16:59:25 +00:00
```
2025-08-14 14:30:54 +00:00
### Action Types
2025-06-12 16:59:25 +00:00
```typescript
2025-08-14 14:30:54 +00:00
interface IRouteAction {
type: 'forward' | 'redirect' | 'block' | 'socket-handler';
// For 'forward'
targets?: Array< {
host: string | string[] | ((context) => string);
port: number | ((context) => number);
}>;
// For 'redirect'
redirectUrl?: string; // With {domain}, {path}, {clientIp} templates
redirectCode?: number; // 301, 302, etc.
// For 'socket-handler'
socketHandler?: (socket, context) => void | Promise< void > ;
// TLS options
tls?: {
mode: 'terminate' | 'passthrough' | 'terminate-and-reencrypt';
certificate: 'auto' | { key: string; cert: string };
};
// WebSocket options
websocket?: {
enabled: boolean;
pingInterval?: number;
pingTimeout?: number;
};
}
2025-06-12 16:59:25 +00:00
```
2025-08-14 14:30:54 +00:00
## 🐛 Troubleshooting
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
### Certificate Issues
- ✅ Ensure domain points to your server
- ✅ Port 80 must be accessible for ACME challenges
- ✅ Check DNS propagation with `nslookup`
- ✅ Verify email in ACME configuration
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
### Connection Problems
- ✅ Check route priorities (higher = matched first)
- ✅ Verify security rules aren't blocking
- ✅ Test with `curl -v` for detailed output
- ✅ Enable debug mode for verbose logging
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
### Performance Tuning
- ✅ Use NFTables for high-traffic routes
- ✅ Enable connection pooling
- ✅ Adjust keep-alive settings
- ✅ Monitor with built-in metrics
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
### Debug Mode
2025-06-12 16:59:25 +00:00
```typescript
2025-07-21 12:23:22 +00:00
const proxy = new SmartProxy({
2025-08-14 14:30:54 +00:00
debug: true, // Enable verbose logging
2025-07-21 12:23:22 +00:00
routes: [...]
});
2025-06-12 16:59:25 +00:00
```
2025-08-14 14:30:54 +00:00
## 🚀 Migration from v20.x to v21.x
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
No breaking changes! v21.x adds enhanced socket cleanup, improved connection tracking, and better process exit handling.
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
## 🏆 Best Practices
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
1. ** 📝 Use Helper Functions** - They provide sensible defaults and prevent errors
2. ** 🎯 Set Route Priorities** - More specific routes should have higher priority
3. ** 🔒 Always Enable Security** - Use IP filtering and rate limiting for public services
4. ** 📊 Monitor Performance** - Use metrics to identify bottlenecks
5. ** 🔄 Regular Certificate Checks** - Monitor expiration and renewal status
6. ** 🛑 Graceful Shutdown** - Always call `proxy.stop()` for clean shutdown
7. ** 🎮 Test Your Routes** - Use the route testing utilities before production
2025-06-12 16:59:25 +00:00
2025-08-14 14:30:54 +00:00
## 📖 API Documentation
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);
2025-08-14 14:30:54 +00:00
// Lifecycle
2025-07-21 12:23:22 +00:00
start(): Promise< void > ;
stop(): Promise< void > ;
2025-08-14 14:30:54 +00:00
// Route Management
2025-07-21 12:23:22 +00:00
updateRoutes(routes: IRouteConfig[]): Promise< void > ;
addRoute(route: IRouteConfig): Promise< void > ;
removeRoute(routeName: string): Promise< void > ;
findMatchingRoute(context: Partial< IRouteContext > ): IRouteConfig | null;
2025-08-14 14:30:54 +00:00
// Port Management
2025-07-21 12:23:22 +00:00
addListeningPort(port: number): Promise< void > ;
removeListeningPort(port: number): Promise< void > ;
getListeningPorts(): number[];
2025-08-14 14:30:54 +00:00
// Certificate Management
2025-07-21 12:23:22 +00:00
getCertificateInfo(domain: string): ICertificateInfo | null;
renewCertificate(domain: string): Promise< void > ;
2025-08-14 14:30:54 +00:00
// Monitoring
2025-07-21 12:23:22 +00:00
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-08-14 14:30:54 +00:00
### Helper Functions
2025-06-22 23:10:56 +00:00
2025-08-14 14:30:54 +00:00
All helper functions are fully typed and documented. Import them from the main package:
2025-06-22 23:10:56 +00:00
2025-08-14 14:30:54 +00:00
```typescript
import {
createHttpRoute,
createHttpsTerminateRoute,
createHttpsPassthroughRoute,
createHttpToHttpsRedirect,
createCompleteHttpsServer,
createLoadBalancerRoute,
createApiRoute,
createWebSocketRoute,
createSocketHandlerRoute,
createNfTablesRoute,
createPortMappingRoute,
createDynamicRoute,
createApiGatewayRoute,
addRateLimiting,
addBasicAuth,
addJwtAuth,
SocketHandlers
} from '@push .rocks/smartproxy';
```
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.