2025-08-14 14:30:54 +00:00
# @push.rocks/smartproxy 🚀
2025-02-03 23:41:13 +01:00
2026-02-09 10:55:46 +00:00
**A high-performance, Rust-powered proxy toolkit for Node.js** — unified route-based configuration for SSL/TLS termination, HTTP/HTTPS reverse proxying, WebSocket support, load balancing, custom protocol handlers, and kernel-level NFTables forwarding.
2025-05-09 22:58:42 +00:00
2026-01-30 09:22:41 +00:00
## 📦 Installation
```bash
npm install @push .rocks/smartproxy
# or
pnpm add @push .rocks/smartproxy
```
## Issue Reporting and Security
For reporting bugs, issues, or security vulnerabilities, please visit [community.foss.global/ ](https://community.foss.global/ ). This is the central community hub for all issue reporting. Developers who sign and comply with our contribution agreement and go through identification can also get a [code.foss.global/ ](https://code.foss.global/ ) account to submit Pull Requests directly.
2025-08-14 14:30:54 +00:00
## 🎯 What is SmartProxy?
2025-05-03 13:19:23 +00:00
2026-02-09 10:55:46 +00:00
SmartProxy is a production-ready proxy solution that takes the complexity out of traffic management. Under the hood, all networking — TCP, TLS, HTTP reverse proxy, connection tracking, security enforcement, and NFTables — is handled by a **Rust engine ** for maximum performance, while you configure everything through a clean TypeScript API with full type safety.
Whether you're building microservices, deploying edge infrastructure, or need a battle-tested reverse proxy with automatic Let's Encrypt certificates, 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
2026-01-30 09:22:41 +00:00
| Feature | Description |
|---------|-------------|
2026-02-09 10:55:46 +00:00
| 🦀 **Rust-Powered Engine ** | All networking handled by a high-performance Rust binary via IPC |
2026-01-30 09:22:41 +00:00
| 🔀 **Unified Route-Based Config ** | Clean match/action patterns for intuitive traffic routing |
| 🔒 **Automatic SSL/TLS ** | Zero-config HTTPS with Let's Encrypt ACME integration |
2026-02-09 10:55:46 +00:00
| 🎯 **Flexible Matching ** | Route by port, domain, path, client IP, TLS version, headers, or custom logic |
2026-01-30 09:22:41 +00:00
| 🚄 **High-Performance ** | Choose between user-space or kernel-level (NFTables) forwarding |
2026-02-09 10:55:46 +00:00
| ⚖️ **Load Balancing ** | Round-robin, least-connections, IP-hash with health checks |
| 🛡️ **Enterprise Security ** | IP filtering, rate limiting, basic auth, JWT auth, connection limits |
2026-01-30 09:22:41 +00:00
| 🔌 **WebSocket Support ** | First-class WebSocket proxying with ping/pong keep-alive |
2026-02-09 10:55:46 +00:00
| 🎮 **Custom Protocols ** | Socket handlers for implementing any protocol in TypeScript |
2026-01-30 09:22:41 +00:00
| 📊 **Live Metrics ** | Real-time throughput, connection counts, and performance data |
| 🔧 **Dynamic Management ** | Add/remove ports and routes at runtime without restarts |
2026-02-09 10:55:46 +00:00
| 🔄 **PROXY Protocol ** | Full PROXY protocol v1/v2 support for preserving client information |
2025-05-03 13:19:23 +00:00
2025-08-14 14:30:54 +00:00
## 🚀 Quick Start
2025-05-09 22:58:42 +00:00
2026-01-30 09:22:41 +00:00
Get 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: {
2026-02-09 10:55:46 +00:00
email: 'ssl@yourdomain .com',
useProduction: true
2025-05-18 18:29:59 +00:00
},
2025-05-10 00:01:02 +00:00
routes: [
2026-02-09 10:55:46 +00:00
// Complete HTTPS setup in one call! ✨
2026-01-30 09:22:41 +00:00
...createCompleteHttpsServer('app.example.com', {
host: 'localhost',
port: 3000
2025-08-14 14:30:54 +00:00
}, {
2026-02-09 10:55:46 +00:00
certificate: 'auto' // Automatic Let's Encrypt cert 🎩
2025-08-14 14:30:54 +00:00
})
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
2026-01-30 09:22:41 +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
{
2026-01-30 09:22:41 +00:00
name: 'api-route',
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
}
```
2026-01-30 09:22:41 +00:00
Every route consists of:
2026-02-09 10:55:46 +00:00
- **Match** — What traffic to capture (ports, domains, paths, IPs, headers)
- **Action** — What to do with it (`forward` or `socket-handler` )
- **Security** (optional) — IP allow/block lists, rate limits, authentication
- **Headers** (optional) — Request/response header manipulation with template variables
- **Name/Priority** (optional) — For identification and ordering
2026-01-30 09:22:41 +00:00
### 🔄 TLS Modes
SmartProxy supports three TLS handling modes:
| Mode | Description | Use Case |
|------|-------------|----------|
2026-02-09 10:55:46 +00:00
| `passthrough` | Forward encrypted traffic as-is (SNI-based routing) | Backend handles TLS |
| `terminate` | Decrypt at proxy, forward plain HTTP to backend | Standard reverse proxy |
2026-01-30 09:22:41 +00:00
| `terminate-and-reencrypt` | Decrypt, then re-encrypt to backend | Zero-trust environments |
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
2026-01-30 09:22:41 +00:00
### 🌐 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: [
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
2026-02-09 10:55:46 +00:00
import { SmartProxy, createLoadBalancerRoute } from '@push .rocks/smartproxy';
const proxy = new SmartProxy({
routes: [
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-08-14 14:30:54 +00:00
}
2026-02-09 10:55:46 +00:00
)
]
});
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
2026-02-09 10:55:46 +00:00
import { SmartProxy, createWebSocketRoute } from '@push .rocks/smartproxy';
2025-08-14 14:30:54 +00:00
2026-02-09 10:55:46 +00:00
const proxy = new SmartProxy({
routes: [
createWebSocketRoute(
'ws.example.com',
{ host: 'websocket-server', port: 8080 },
{
path: '/socket',
useTls: true,
certificate: 'auto',
pingInterval: 30000,
pingTimeout: 10000
}
)
]
});
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
2026-02-09 10:55:46 +00:00
import { SmartProxy, createApiGatewayRoute, addRateLimiting } from '@push .rocks/smartproxy';
2025-06-12 16:59:25 +00:00
2026-02-09 10:55:46 +00:00
let apiRoute = createApiGatewayRoute(
2025-08-14 14:30:54 +00:00
'api.example.com',
'/api',
{ host: 'api-backend', port: 8080 },
{
useTls: true,
certificate: 'auto',
addCorsHeaders: true
}
);
2025-06-12 16:59:25 +00:00
2026-02-09 10:55:46 +00:00
// Add rate limiting — 100 requests per minute per IP
apiRoute = addRateLimiting(apiRoute, {
2025-08-14 14:30:54 +00:00
maxRequests: 100,
2026-01-30 09:22:41 +00:00
window: 60,
2025-08-14 14:30:54 +00:00
keyBy: 'ip'
});
2026-02-09 10:55:46 +00:00
const proxy = new SmartProxy({ routes: [apiRoute] });
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
2026-02-09 10:55:46 +00:00
SmartProxy lets you implement any protocol with full socket control. Routes with JavaScript socket handlers are automatically relayed from the Rust engine back to your TypeScript code:
2026-01-30 09:22:41 +00:00
2025-06-12 16:59:25 +00:00
```typescript
2026-02-09 10:55:46 +00:00
import { SmartProxy, createSocketHandlerRoute, SocketHandlers } from '@push .rocks/smartproxy';
2025-06-12 16:59:25 +00:00
2026-01-30 09:22:41 +00:00
// Use pre-built handlers
2025-08-14 14:30:54 +00:00
const echoRoute = createSocketHandlerRoute(
2026-01-30 09:22:41 +00:00
'echo.example.com',
7777,
2025-08-14 14:30:54 +00:00
SocketHandlers.echo
);
2026-01-30 09:22:41 +00:00
// Or create your own custom protocol
2025-08-14 14:30:54 +00:00
const customRoute = createSocketHandlerRoute(
'custom.example.com',
9999,
async (socket, context) => {
console.log(`Connection from ${context.clientIp}` );
socket.write('Welcome to my custom protocol!\n');
2026-01-30 09:22:41 +00:00
2025-08-14 14:30:54 +00:00
socket.on('data', (data) => {
const command = data.toString().trim();
2026-01-30 09:22:41 +00:00
switch (command) {
case 'PING': socket.write('PONG\n'); break;
case 'TIME': socket.write(`${new Date().toISOString()}\n` ); break;
case 'QUIT': socket.end('Goodbye!\n'); break;
default: socket.write(`Unknown: ${command}\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
);
2026-02-09 10:55:46 +00:00
const proxy = new SmartProxy({ routes: [echoRoute, customRoute] });
2025-06-12 16:59:25 +00:00
```
2026-01-30 09:22:41 +00:00
**Pre-built Socket Handlers:**
| Handler | Description |
|---------|-------------|
2026-02-09 10:55:46 +00:00
| `SocketHandlers.echo` | Echo server — returns everything sent |
2026-01-30 09:22:41 +00:00
| `SocketHandlers.proxy(host, port)` | TCP proxy to another server |
| `SocketHandlers.lineProtocol(handler)` | Line-based text protocol |
| `SocketHandlers.httpResponse(code, body)` | Simple HTTP response |
2026-02-09 10:55:46 +00:00
| `SocketHandlers.httpRedirect(url, code)` | HTTP redirect with template variables (`{domain}` , `{path}` , `{port}` , `{clientIp}` ) |
2026-01-30 09:22:41 +00:00
| `SocketHandlers.httpServer(handler)` | Full HTTP request/response handling |
2026-02-09 10:55:46 +00:00
| `SocketHandlers.httpBlock(status, message)` | HTTP block response |
2026-01-30 09:22:41 +00:00
| `SocketHandlers.block(message)` | Block with optional message |
2025-08-14 14:30:54 +00:00
### ⚡ High-Performance NFTables Forwarding
2025-06-12 16:59:25 +00:00
2026-01-30 09:22:41 +00:00
For ultra-low latency on Linux, use kernel-level forwarding (requires root):
2025-06-12 16:59:25 +00:00
```typescript
2026-02-09 10:55:46 +00:00
import { SmartProxy, createNfTablesTerminateRoute } from '@push .rocks/smartproxy';
2025-06-12 16:59:25 +00:00
2026-02-09 10:55:46 +00:00
const proxy = new SmartProxy({
routes: [
createNfTablesTerminateRoute(
'fast.example.com',
{ host: 'backend', port: 8080 },
{
ports: 443,
certificate: 'auto',
preserveSourceIP: true, // Backend sees real client IP
maxRate: '1gbps' // QoS rate limiting
}
)
]
});
```
### 🔒 SNI Passthrough (TLS Passthrough)
Forward encrypted traffic to backends without terminating TLS — the proxy routes based on the SNI hostname alone:
```typescript
import { SmartProxy, createHttpsPassthroughRoute } from '@push .rocks/smartproxy';
const proxy = new SmartProxy({
routes: [
createHttpsPassthroughRoute('secure.example.com', {
host: 'backend-that-handles-tls',
port: 8443
})
]
});
2025-06-12 16:59:25 +00:00
```
2025-08-14 14:30:54 +00:00
## 🔧 Advanced Features
### 🎯 Dynamic Routing
2026-02-09 10:55:46 +00:00
Route traffic based on runtime conditions using function-based host/port resolution:
2025-08-14 14:30:54 +00:00
2025-06-12 16:59:25 +00:00
```typescript
2026-02-09 10:55:46 +00:00
const proxy = new SmartProxy({
routes: [{
name: 'dynamic-backend',
match: {
ports: 443,
domains: 'app.example.com'
},
action: {
type: 'forward',
targets: [{
host: (context) => {
return context.path?.startsWith('/premium')
? 'premium-backend'
: 'standard-backend';
},
port: 8080
}],
tls: { mode: 'terminate', certificate: 'auto' }
}
}]
});
2025-06-12 16:59:25 +00:00
```
2026-02-09 10:55:46 +00:00
> **Note:** Routes with dynamic functions (host/port callbacks) are automatically relayed through the TypeScript socket handler server, since JavaScript functions can't be serialized to Rust.
2025-08-14 14:30:54 +00:00
### 🔒 Security Controls
2026-01-30 09:22:41 +00:00
Comprehensive per-route security options:
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
{
2026-01-30 09:22:41 +00:00
name: 'secure-api',
match: { ports: 443, domains: 'api.example.com' },
action: {
type: 'forward',
2026-02-09 10:55:46 +00:00
targets: [{ host: 'api-backend', port: 8080 }],
tls: { mode: 'terminate', certificate: 'auto' }
2026-01-30 09:22:41 +00:00
},
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'],
2026-01-30 09:22:41 +00:00
2025-08-14 14:30:54 +00:00
// Connection limits
maxConnections: 1000,
2026-01-30 09:22:41 +00:00
2025-08-14 14:30:54 +00:00
// Rate limiting
rateLimit: {
2026-02-09 10:55:46 +00:00
enabled: true,
2025-08-14 14:30:54 +00:00
maxRequests: 100,
2026-02-09 10:55:46 +00:00
window: 60
},
// Authentication
basicAuth: { users: [{ username: 'admin', password: 'secret' }] },
jwtAuth: { secret: 'your-jwt-secret', algorithm: 'HS256' }
2025-07-21 12:23:22 +00:00
}
}
```
2025-06-12 16:59:25 +00:00
2026-02-09 10:55:46 +00:00
**Security modifier helpers** let you add security to any existing route:
```typescript
import { addRateLimiting, addBasicAuth, addJwtAuth } from '@push .rocks/smartproxy';
let route = createHttpsTerminateRoute('api.example.com', { host: 'backend', port: 8080 });
route = addRateLimiting(route, { maxRequests: 100, window: 60, keyBy: 'ip' });
route = addBasicAuth(route, { users: [{ username: 'admin', password: 'secret' }] });
```
2025-08-14 14:30:54 +00:00
### 📊 Runtime Management
Control your proxy without restarts:
2025-06-12 16:59:25 +00:00
```typescript
2026-01-30 09:22:41 +00:00
// Dynamic port management
2025-08-14 14:30:54 +00:00
await proxy.addListeningPort(8443);
await proxy.removeListeningPort(8080);
2026-02-09 10:55:46 +00:00
const ports = await proxy.getListeningPorts();
2025-08-14 14:30:54 +00:00
2026-02-09 10:55:46 +00:00
// Update routes on the fly (atomic, mutex-locked)
2025-08-14 14:30:54 +00:00
await proxy.updateRoutes([...newRoutes]);
2026-02-09 10:55:46 +00:00
// Get real-time metrics
2025-08-14 14:30:54 +00:00
const metrics = proxy.getMetrics();
2026-02-09 10:55:46 +00:00
console.log(`Active connections: ${metrics.connections.active()}` );
console.log(`Requests/sec: ${metrics.throughput.requestsPerSecond()}` );
// Get detailed statistics from the Rust engine
const stats = await proxy.getStatistics();
2025-08-14 14:30:54 +00:00
// Certificate management
2026-02-09 10:55:46 +00:00
await proxy.provisionCertificate('my-route-name');
await proxy.renewCertificate('my-route-name');
const certStatus = await proxy.getCertificateStatus('my-route-name');
// NFTables status
const nftStatus = await proxy.getNfTablesStatus();
2025-06-12 16:59:25 +00:00
```
2025-08-14 14:30:54 +00:00
### 🔄 Header Manipulation
2026-01-30 09:22:41 +00:00
Transform requests and responses with template variables:
2025-08-14 14:30:54 +00:00
2025-06-12 16:59:25 +00:00
```typescript
{
action: {
2026-01-30 09:22:41 +00:00
type: 'forward',
2026-02-09 10:55:46 +00:00
targets: [{ host: 'backend', port: 8080 }]
},
headers: {
request: {
'X-Real-IP': '{clientIp}',
'X-Request-ID': '{uuid}',
'X-Forwarded-Proto': 'https'
},
response: {
'Strict-Transport-Security': 'max-age=31536000',
'X-Frame-Options': 'DENY'
2025-06-12 16:59:25 +00:00
}
}
}
```
2026-02-09 10:55:46 +00:00
### 🔀 PROXY Protocol Support
Preserve original client information through proxy chains:
```typescript
const proxy = new SmartProxy({
// Accept PROXY protocol from trusted load balancers
acceptProxyProtocol: true,
proxyIPs: ['10.0.0.1', '10.0.0.2'],
// Forward PROXY protocol to backends
sendProxyProtocol: true,
routes: [...]
});
```
### 🏗️ Custom Certificate Provisioning
Supply your own certificates or integrate with external certificate providers:
```typescript
const proxy = new SmartProxy({
certProvisionFunction: async (domain: string) => {
// Return 'http01' to let the built-in ACME handle it
if (domain.endsWith('.example.com')) return 'http01';
// Or return a static certificate object
return {
publicKey: myPemCert,
privateKey: myPemKey,
};
},
certProvisionFallbackToAcme: true, // Fall back to ACME if callback fails
routes: [...]
});
```
2025-08-14 14:30:54 +00:00
## 🏛️ Architecture
2025-06-12 16:59:25 +00:00
2026-02-09 10:55:46 +00:00
SmartProxy uses a hybrid **Rust + TypeScript ** architecture:
2025-06-12 16:59:25 +00:00
2025-07-21 12:23:22 +00:00
```
2026-02-09 10:55:46 +00:00
┌─────────────────────────────────────────────────────┐
│ Your Application │
│ (TypeScript — routes, config, socket handlers) │
└──────────────────┬──────────────────────────────────┘
│ IPC (JSON over stdin/stdout)
┌──────────────────▼──────────────────────────────────┐
│ Rust Proxy Engine │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌──────────┐ │
│ │ TCP/TLS │ │ HTTP │ │ Route │ │ ACME │ │
│ │ Listener│ │ Reverse │ │ Matcher │ │ Cert Mgr │ │
│ │ │ │ Proxy │ │ │ │ │ │
│ └─────────┘ └─────────┘ └─────────┘ └──────────┘ │
│ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌──────────┐ │
│ │ Security│ │ Metrics │ │ Connec- │ │ NFTables │ │
│ │ Enforce │ │ Collect │ │ tion │ │ Mgr │ │
│ │ │ │ │ │ Tracker │ │ │ │
│ └─────────┘ └─────────┘ └─────────┘ └──────────┘ │
└──────────────────┬──────────────────────────────────┘
│ Unix Socket Relay
┌──────────────────▼──────────────────────────────────┐
│ TypeScript Socket Handler Server │
│ (for JS-defined socket handlers & dynamic routes) │
└─────────────────────────────────────────────────────┘
2025-08-14 14:30:54 +00:00
```
2026-02-09 10:55:46 +00:00
- **Rust Engine** handles all networking, TLS, HTTP proxying, connection management, security, and metrics
- **TypeScript** provides the npm API, configuration types, route helpers, validation, and socket handler callbacks
- **IPC** — JSON commands/events over stdin/stdout for seamless cross-language communication
- **Socket Relay** — a Unix domain socket server for routes requiring TypeScript-side handling (socket handlers, dynamic host/port functions)
2025-08-14 14:30:54 +00:00
## 🎯 Route Configuration Reference
### Match Criteria
2025-06-12 16:59:25 +00:00
```typescript
2025-08-14 14:30:54 +00:00
interface IRouteMatch {
2026-02-09 10:55:46 +00:00
ports: number | number[] | Array<{ from: number; to: number }>; // Port(s) to listen on
domains?: string | string[]; // 'example.com', '*.example.com'
path?: string; // '/api/*', '/users/:id'
clientIp?: string[]; // ['10.0.0.0/8', '192.168.*']
tlsVersion?: string[]; // ['TLSv1.2', 'TLSv1.3']
headers?: Record<string, string | RegExp>; // Match by HTTP headers
2025-08-14 14:30:54 +00:00
}
2025-06-12 16:59:25 +00:00
```
2025-08-14 14:30:54 +00:00
### Action Types
2026-01-30 09:22:41 +00:00
| Type | Description |
|------|-------------|
2026-02-09 10:55:46 +00:00
| `forward` | Proxy to one or more backend targets (with optional TLS, WebSocket, load balancing) |
| `socket-handler` | Custom socket handling function in TypeScript |
### Target Options
```typescript
interface IRouteTarget {
host: string | string[] | ((context: IRouteContext) => string);
port: number | 'preserve' | ((context: IRouteContext) => number);
tls?: { ... }; // Per-target TLS override
priority?: number; // Target priority
match?: ITargetMatch; // Sub-match within a route (by port, path, headers, method)
}
```
2026-01-30 09:22:41 +00:00
### TLS Options
2025-06-12 16:59:25 +00:00
```typescript
2026-01-30 09:22:41 +00:00
interface IRouteTls {
mode: 'passthrough' | 'terminate' | 'terminate-and-reencrypt';
2026-02-09 10:55:46 +00:00
certificate: 'auto' | {
key: string;
cert: string;
ca?: string;
keyFile?: string;
certFile?: string;
};
acme?: {
email: string;
useProduction?: boolean;
challengePort?: number;
renewBeforeDays?: number;
};
versions?: string[];
ciphers?: string[];
honorCipherOrder?: boolean;
sessionTimeout?: number;
}
```
### WebSocket Options
```typescript
interface IRouteWebSocket {
enabled: boolean;
pingInterval?: number; // ms between pings
pingTimeout?: number; // ms to wait for pong
maxPayloadSize?: number; // Maximum frame payload
subprotocols?: string[]; // Allowed subprotocols
allowedOrigins?: string[]; // CORS origins
}
```
### Load Balancing Options
```typescript
interface IRouteLoadBalancing {
algorithm: 'round-robin' | 'least-connections' | 'ip-hash';
healthCheck?: {
path: string;
interval: number; // ms
timeout: number; // ms
unhealthyThreshold?: number;
healthyThreshold?: number;
2025-08-14 14:30:54 +00:00
};
}
2025-06-12 16:59:25 +00:00
```
2026-01-30 09:22:41 +00:00
## 🛠️ Helper Functions Reference
2026-02-09 10:55:46 +00:00
All helpers are fully typed and return `IRouteConfig` or `IRouteConfig[]` :
2026-01-30 09:22:41 +00:00
```typescript
import {
// HTTP/HTTPS
2026-02-09 10:55:46 +00:00
createHttpRoute, // Plain HTTP route
createHttpsTerminateRoute, // HTTPS with TLS termination
createHttpsPassthroughRoute, // SNI passthrough (no termination)
createHttpToHttpsRedirect, // HTTP → HTTPS redirect
createCompleteHttpsServer, // HTTPS + redirect combo (returns IRouteConfig[])
2026-01-30 09:22:41 +00:00
// Load Balancing
2026-02-09 10:55:46 +00:00
createLoadBalancerRoute, // Multi-backend with health checks
createSmartLoadBalancer, // Dynamic domain-based backend selection
2026-01-30 09:22:41 +00:00
// API & WebSocket
2026-02-09 10:55:46 +00:00
createApiRoute, // API route with path matching
createApiGatewayRoute, // API gateway with CORS
createWebSocketRoute, // WebSocket-enabled route
2026-01-30 09:22:41 +00:00
// Custom Protocols
2026-02-09 10:55:46 +00:00
createSocketHandlerRoute, // Custom socket handler
SocketHandlers, // Pre-built handlers (echo, proxy, block, etc.)
2026-01-30 09:22:41 +00:00
2026-02-09 10:55:46 +00:00
// NFTables (Linux, requires root)
createNfTablesRoute, // Kernel-level packet forwarding
createNfTablesTerminateRoute, // NFTables + TLS termination
createCompleteNfTablesHttpsServer, // NFTables HTTPS + redirect combo
2026-01-30 09:22:41 +00:00
// Dynamic Routing
2026-02-09 10:55:46 +00:00
createPortMappingRoute, // Port mapping with context
createOffsetPortMappingRoute, // Simple port offset
createDynamicRoute, // Dynamic host/port via functions
2026-01-30 09:22:41 +00:00
// Security Modifiers
2026-02-09 10:55:46 +00:00
addRateLimiting, // Add rate limiting to any route
addBasicAuth, // Add basic auth to any route
addJwtAuth, // Add JWT auth to any route
// Route Utilities
mergeRouteConfigs, // Deep-merge two route configs
findMatchingRoutes, // Find routes matching criteria
findBestMatchingRoute, // Find best matching route
cloneRoute, // Deep-clone a route
generateRouteId, // Generate deterministic route ID
RouteValidator, // Validate route configurations
2026-01-30 09:22:41 +00:00
} from '@push .rocks/smartproxy';
```
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
2026-02-09 10:55:46 +00:00
class SmartProxy extends EventEmitter {
2026-01-30 09:22:41 +00:00
constructor(options: ISmartProxyOptions);
2025-08-14 14:30:54 +00:00
// Lifecycle
2025-07-21 12:23:22 +00:00
start(): Promise<void>;
stop(): Promise<void>;
2026-01-30 09:22:41 +00:00
2026-02-09 10:55:46 +00:00
// Route Management (atomic, mutex-locked)
2025-07-21 12:23:22 +00:00
updateRoutes(routes: IRouteConfig[]): Promise<void>;
2026-01-30 09:22:41 +00:00
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>;
2026-02-09 10:55:46 +00:00
getListeningPorts(): Promise<number[]>;
2026-01-30 09:22:41 +00:00
2026-02-09 10:55:46 +00:00
// Monitoring & Metrics
getMetrics(): IMetrics; // Sync — returns cached metrics adapter
getStatistics(): Promise<any>; // Async — queries Rust engine
2026-01-30 09:22:41 +00:00
// Certificate Management
2026-02-09 10:55:46 +00:00
provisionCertificate(routeName: string): Promise<void>;
renewCertificate(routeName: string): Promise<void>;
getCertificateStatus(routeName: string): Promise<any>;
getEligibleDomainsForCertificates(): string[];
// NFTables
getNfTablesStatus(): Promise<Record<string, any>>;
// Events
on(event: 'error', handler: (err: Error) => void): this;
2025-06-09 15:14:13 +00:00
}
2025-06-22 23:10:56 +00:00
```
2025-06-13 17:22:31 +00:00
2026-01-30 09:22:41 +00:00
### Configuration Options
2025-06-22 23:10:56 +00:00
2025-08-14 14:30:54 +00:00
```typescript
2026-01-30 09:22:41 +00:00
interface ISmartProxyOptions {
2026-02-09 10:55:46 +00:00
routes: IRouteConfig[]; // Required: array of route configs
2026-01-30 09:22:41 +00:00
// ACME/Let's Encrypt
acme?: {
2026-02-09 10:55:46 +00:00
email: string; // Contact email for Let's Encrypt
useProduction?: boolean; // Use production servers (default: false)
port?: number; // HTTP-01 challenge port (default: 80)
renewThresholdDays?: number; // Days before expiry to renew (default: 30)
autoRenew?: boolean; // Enable auto-renewal (default: true)
certificateStore?: string; // Directory to store certs (default: './certs')
renewCheckIntervalHours?: number; // Renewal check interval (default: 24)
2026-01-30 09:22:41 +00:00
};
2026-02-09 10:55:46 +00:00
// Custom certificate provisioning
certProvisionFunction?: (domain: string) => Promise<ICert | 'http01'>;
certProvisionFallbackToAcme?: boolean; // Fall back to ACME on failure (default: true)
// Global defaults
2026-01-30 09:22:41 +00:00
defaults?: {
target?: { host: string; port: number };
2026-02-09 10:55:46 +00:00
security?: { ipAllowList?: string[]; ipBlockList?: string[]; maxConnections?: number };
};
// PROXY protocol
proxyIPs?: string[]; // Trusted proxy IPs
acceptProxyProtocol?: boolean; // Accept PROXY protocol headers
sendProxyProtocol?: boolean; // Send PROXY protocol to targets
// Timeouts
connectionTimeout?: number; // Backend connection timeout (default: 30s)
initialDataTimeout?: number; // Initial data/SNI timeout (default: 120s)
socketTimeout?: number; // Socket inactivity timeout (default: 1h)
maxConnectionLifetime?: number; // Max connection lifetime (default: 24h)
inactivityTimeout?: number; // Inactivity timeout (default: 4h)
gracefulShutdownTimeout?: number; // Shutdown grace period (default: 30s)
// Connection limits
maxConnectionsPerIP?: number; // Per-IP connection limit (default: 100)
connectionRateLimitPerMinute?: number; // Per-IP rate limit (default: 300/min)
// Keep-alive
keepAliveTreatment?: 'standard' | 'extended' | 'immortal';
keepAliveInactivityMultiplier?: number; // (default: 6)
extendedKeepAliveLifetime?: number; // (default: 7 days)
// Metrics
metrics?: {
enabled?: boolean;
sampleIntervalMs?: number;
retentionSeconds?: number;
2026-01-30 09:22:41 +00:00
};
// Behavior
2026-02-09 10:55:46 +00:00
enableDetailedLogging?: boolean; // Verbose connection logging
enableTlsDebugLogging?: boolean; // TLS handshake debug logging
// Rust binary
rustBinaryPath?: string; // Custom path to the Rust binary
2026-01-30 09:22:41 +00:00
}
2025-08-14 14:30:54 +00:00
```
2025-03-07 14:34:49 +00:00
2026-02-09 10:55:46 +00:00
### NfTablesProxy Class
A standalone class for managing nftables NAT rules directly (Linux only, requires root):
```typescript
import { NfTablesProxy } from '@push .rocks/smartproxy';
const nftProxy = new NfTablesProxy({
fromPorts: [80, 443],
toHost: 'backend-server',
toPorts: [8080, 8443],
protocol: 'tcp',
preserveSourceIP: true,
enableIPv6: true,
maxRate: '1gbps',
useIPSets: true
});
await nftProxy.start(); // Apply nftables rules
const status = nftProxy.getStatus();
await nftProxy.stop(); // Remove rules
```
## 🐛 Troubleshooting
### Certificate Issues
- ✅ Ensure domain DNS points to your server
- ✅ Port 80 must be accessible for ACME HTTP-01 challenges
- ✅ Check DNS propagation with `dig` or `nslookup`
- ✅ Verify the email in ACME configuration is valid
- ✅ Use `getCertificateStatus('route-name')` to check cert state
### Connection Problems
- ✅ Check route priorities (higher number = matched first)
- ✅ Verify security rules aren't blocking legitimate traffic
- ✅ Test with `curl -v` for detailed connection output
- ✅ Enable debug logging with `enableDetailedLogging: true`
### Rust Binary Not Found
SmartProxy searches for the Rust binary in this order:
1. `SMARTPROXY_RUST_BINARY` environment variable
2. Platform-specific npm package (`@push.rocks/smartproxy-linux-x64` , etc.)
3. Local dev build (`./rust/target/release/rustproxy` )
4. System PATH (`rustproxy` )
Set `rustBinaryPath` in options to override.
### Performance Tuning
- ✅ Use NFTables forwarding for high-traffic routes (Linux only)
- ✅ Enable connection keep-alive where appropriate
- ✅ Use `getMetrics()` and `getStatistics()` to identify bottlenecks
- ✅ Adjust `maxConnectionsPerIP` and `connectionRateLimitPerMinute` based on your workload
- ✅ Use `passthrough` TLS mode when backend can handle TLS directly
## 🏆 Best Practices
1. * * 📝 Use Helper Functions** — They provide sensible defaults and prevent common mistakes
2. * * 🎯 Set Route Priorities** — More specific routes should have higher priority values
3. * * 🔒 Enable Security** — Always use IP filtering and rate limiting for public-facing services
4. * * 📊 Monitor Metrics** — Use the built-in metrics to catch issues early
5. * * 🔄 Certificate Monitoring** — Set up alerts before certificates expire
6. * * 🛑 Graceful Shutdown** — Always call `proxy.stop()` for clean connection termination
7. * * ✅ Validate Routes** — Use `RouteValidator.validateRoutes()` to catch config errors before deployment
8. * * 🔀 Atomic Updates** — Use `updateRoutes()` for hot-reloading routes (mutex-locked, no downtime)
9. * * 🎮 Use Socket Handlers** — For protocols beyond HTTP, implement custom socket handlers instead of fighting the proxy model
2024-04-14 18:10:41 +02:00
## License and Legal Information
2026-01-30 09:22:41 +00:00
This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE ](./LICENSE ) file.
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
2026-01-30 09:22:41 +00: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 or third parties, 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 or the guidelines of the respective third-party owners, and any usage must be approved in writing. Third-party trademarks used herein are the property of their respective owners and used only in a descriptive manner, e.g. for an implementation of an API or similar.
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
2026-01-30 09:22:41 +00:00
Task Venture Capital GmbH
Registered at District Court Bremen HRB 35230 HB, Germany
2020-02-07 13:04:11 +00:00
2026-01-30 09:22:41 +00:00
For any legal inquiries or further information, please contact us via email at hello@task .vc.
2019-08-20 18:43:15 +02:00
2026-01-30 09:22:41 +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.