Compare commits

...

4 Commits

Author SHA1 Message Date
1d1e5062a6 v22.4.0
Some checks failed
Default (tags) / security (push) Successful in 38s
Default (tags) / test (push) Failing after 47s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-01-30 10:44:28 +00:00
c2dd7494d6 feat(smart-proxy): calculate when SNI is required for TLS routing and allow session tickets for single-target passthrough routes; add tests, docs, and npm metadata updates 2026-01-30 10:44:28 +00:00
ea3b8290d2 v22.3.0
Some checks failed
Default (tags) / security (push) Successful in 38s
Default (tags) / test (push) Failing after 47s
Default (tags) / release (push) Has been skipped
Default (tags) / metadata (push) Has been skipped
2026-01-30 09:22:41 +00:00
9b1adb1d7a feat(docs): update README with installation, improved feature table, expanded quick-start, ACME/email example, API options interface, and clarified licensing/trademark text 2026-01-30 09:22:41 +00:00
8 changed files with 728 additions and 194 deletions

View File

@@ -1,5 +1,25 @@
# Changelog # Changelog
## 2026-01-30 - 22.4.0 - feat(smart-proxy)
calculate when SNI is required for TLS routing and allow session tickets for single-target passthrough routes; add tests, docs, and npm metadata updates
- Add calculateSniRequirement() and isWildcardOnly() to determine when SNI is required for routing decisions
- Use the new calculation to allow TLS session tickets for single-route passthrough or wildcard-only domains and block them when SNI is required
- Replace previous heuristic in route-connection-handler with the new SNI-based logic
- Add comprehensive unit tests (test/test.sni-requirement.node.ts) covering multiple SNI scenarios
- Update readme.hints.md with Smart SNI Requirement documentation and adjust troubleshooting guidance
- Update npmextra.json keys, add release registries and adjust tsdoc/CI metadata
## 2026-01-30 - 22.3.0 - feat(docs)
update README with installation, improved feature table, expanded quick-start, ACME/email example, API options interface, and clarified licensing/trademark text
- Added Installation section with npm/pnpm commands
- Reformatted features into a markdown table for clarity
- Expanded Quick Start example and updated ACME email placeholder
- Added an ISmartProxyOptions interface example showing acme/defaults/behavior options
- Clarified license file path and expanded trademark/legal wording
- Minor editorial and formatting improvements throughout the README
## 2026-01-30 - 22.2.0 - feat(proxies) ## 2026-01-30 - 22.2.0 - feat(proxies)
introduce nftables command executor and utilities, default certificate provider, expanded route/socket helper modules, and security improvements introduce nftables command executor and utilities, default certificate provider, expanded route/socket helper modules, and security improvements

View File

@@ -1,5 +1,5 @@
{ {
"gitzone": { "@git.zone/cli": {
"projectType": "npm", "projectType": "npm",
"module": { "module": {
"githost": "code.foss.global", "githost": "code.foss.global",
@@ -26,13 +26,19 @@
"server", "server",
"network security" "network security"
] ]
},
"release": {
"registries": [
"https://verdaccio.lossless.digital",
"https://registry.npmjs.org"
],
"accessLevel": "public"
} }
}, },
"npmci": { "@git.zone/tsdoc": {
"npmGlobalTools": [],
"npmAccessLevel": "public"
},
"tsdoc": {
"legal": "\n## License and Legal Information\n\nThis 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. \n\n**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.\n\n### Trademarks\n\nThis 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.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy 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.\n" "legal": "\n## License and Legal Information\n\nThis 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. \n\n**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.\n\n### Trademarks\n\nThis 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.\n\n### Company Information\n\nTask Venture Capital GmbH \nRegistered at District court Bremen HRB 35230 HB, Germany\n\nFor any legal inquiries or if you require further information, please contact us via email at hello@task.vc.\n\nBy 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.\n"
},
"@ship.zone/szci": {
"npmGlobalTools": []
} }
} }

View File

@@ -1,6 +1,6 @@
{ {
"name": "@push.rocks/smartproxy", "name": "@push.rocks/smartproxy",
"version": "22.2.0", "version": "22.4.0",
"private": false, "private": false,
"description": "A powerful proxy package with unified route-based configuration for high traffic management. Features include SSL/TLS support, flexible routing patterns, WebSocket handling, advanced security options, and automatic ACME certificate management.", "description": "A powerful proxy package with unified route-based configuration for high traffic management. Features include SSL/TLS support, flexible routing patterns, WebSocket handling, advanced security options, and automatic ACME certificate management.",
"main": "dist_ts/index.js", "main": "dist_ts/index.js",

View File

@@ -493,11 +493,28 @@ const lbRoute = createLoadBalancerRoute(
); );
``` ```
### Smart SNI Requirement (v22.3+)
SmartProxy automatically determines when SNI is required for routing. Session tickets (TLS resumption without SNI) are now allowed in more scenarios:
**SNI NOT required (session tickets allowed):**
- Single passthrough route with static target(s) and no domain restriction
- Single passthrough route with wildcard-only domain (`*` or `['*']`)
- TLS termination routes (`terminate` or `terminate-and-reencrypt`)
- Mixed terminate + passthrough routes (termination takes precedence)
**SNI IS required (session tickets blocked):**
- Multiple passthrough routes on the same port (need SNI to pick correct route)
- Route has dynamic host function (e.g., `host: (ctx) => ctx.domain === 'api.example.com' ? 'api-backend' : 'web-backend'`)
- Route has specific domain restriction (e.g., `domains: 'api.example.com'` or `domains: '*.example.com'`)
This allows simple single-target passthrough setups to work with TLS session resumption, improving performance for clients that reuse connections.
### Troubleshooting ### Troubleshooting
**"No SNI detected" errors**: **"No SNI detected" errors**:
- Client is using TLS session resumption without SNI - Client is using TLS session resumption without SNI
- Solution: Configure route for TLS termination (allows session resumption) - Solution: Configure route for TLS termination (allows session resumption), or ensure you have a single-target passthrough route with no domain restrictions
**"HttpProxy not available" errors**: **"HttpProxy not available" errors**:
- `useHttpProxy` not configured for the port - `useHttpProxy` not configured for the port

377
readme.md
View File

@@ -2,32 +2,40 @@
**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. **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.
## 📦 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.
## 🎯 What is SmartProxy? ## 🎯 What is SmartProxy?
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. 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.
### ⚡ Key Features ### ⚡ Key Features
- **🔀 Unified Route-Based Configuration** - Clean match/action patterns for intuitive traffic routing | Feature | Description |
- **🔒 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 | 🔀 **Unified Route-Based Config** | Clean match/action patterns for intuitive traffic routing |
- **🚄 High-Performance Forwarding** - Choose between user-space or kernel-level (NFTables) forwarding | 🔒 **Automatic SSL/TLS** | Zero-config HTTPS with Let's Encrypt ACME integration |
- **⚖️ Built-in Load Balancing** - Distribute traffic across multiple backends with health checks | 🎯 **Flexible Matching** | Route by port, domain, path, client IP, TLS version, or custom logic |
- **🛡️ Enterprise Security** - IP filtering, rate limiting, authentication, and connection limits | 🚄 **High-Performance** | Choose between user-space or kernel-level (NFTables) forwarding |
- **🔌 WebSocket Support** - First-class WebSocket proxying with ping/pong management | ⚖️ **Load Balancing** | Distribute traffic with health checks and multiple algorithms |
- **🎮 Custom Socket Handlers** - Implement any protocol with full socket control | 🛡️ **Enterprise Security** | IP filtering, rate limiting, authentication, connection limits |
- **📊 Dynamic Port Management** - Add/remove ports at runtime without restarts | 🔌 **WebSocket Support** | First-class WebSocket proxying with ping/pong keep-alive |
- **🔧 Protocol Detection** - Smart protocol detection for mixed-mode operation | 🎮 **Custom Protocols** | Socket handlers for implementing any protocol |
| 📊 **Live Metrics** | Real-time throughput, connection counts, and performance data |
## 📦 Installation | 🔧 **Dynamic Management** | Add/remove ports and routes at runtime without restarts |
```bash
npm install @push.rocks/smartproxy
```
## 🚀 Quick Start ## 🚀 Quick Start
Let's get you up and running in 30 seconds: Get up and running in 30 seconds:
```typescript ```typescript
import { SmartProxy, createCompleteHttpsServer } from '@push.rocks/smartproxy'; import { SmartProxy, createCompleteHttpsServer } from '@push.rocks/smartproxy';
@@ -35,11 +43,11 @@ import { SmartProxy, createCompleteHttpsServer } from '@push.rocks/smartproxy';
// Create a proxy with automatic HTTPS // Create a proxy with automatic HTTPS
const proxy = new SmartProxy({ const proxy = new SmartProxy({
acme: { acme: {
email: 'ssl@example.com', // Your email for Let's Encrypt email: 'ssl@yourdomain.com', // Your email for Let's Encrypt
useProduction: true // Use Let's Encrypt production servers useProduction: true // Use production servers
}, },
routes: [ routes: [
// Complete HTTPS setup with one line // Complete HTTPS setup in one line! ✨
...createCompleteHttpsServer('app.example.com', { ...createCompleteHttpsServer('app.example.com', {
host: 'localhost', host: 'localhost',
port: 3000 port: 3000
@@ -57,10 +65,11 @@ console.log('🚀 Proxy running with automatic HTTPS!');
### 🏗️ Route-Based Architecture ### 🏗️ Route-Based Architecture
SmartProxy uses a powerful match/action pattern that makes routing predictable and maintainable: SmartProxy uses a powerful **match/action** pattern that makes routing predictable and maintainable:
```typescript ```typescript
{ {
name: 'api-route',
match: { match: {
ports: 443, ports: 443,
domains: 'api.example.com', domains: 'api.example.com',
@@ -74,22 +83,31 @@ SmartProxy uses a powerful match/action pattern that makes routing predictable a
} }
``` ```
Every route has: Every route consists of:
- **Match criteria** - What traffic to capture - **Match** - What traffic to capture (ports, domains, paths, IPs)
- **Action** - What to do with it - **Action** - What to do with it (forward, redirect, block, socket-handler)
- **Security** (optional) - Access controls and limits - **Security** (optional) - Access controls, rate limits, authentication
- **Metadata** (optional) - Name, priority, tags - **Name/Priority** (optional) - For identification and ordering
### 🔄 TLS Modes
SmartProxy supports three TLS handling modes:
| Mode | Description | Use Case |
|------|-------------|----------|
| `passthrough` | Forward encrypted traffic as-is | Backend handles TLS |
| `terminate` | Decrypt at proxy, forward plain | Standard reverse proxy |
| `terminate-and-reencrypt` | Decrypt, then re-encrypt to backend | Zero-trust environments |
## 💡 Common Use Cases ## 💡 Common Use Cases
### 🌐 Simple HTTP to HTTPS Redirect ### 🌐 HTTP to HTTPS Redirect
```typescript ```typescript
import { SmartProxy, createHttpToHttpsRedirect } from '@push.rocks/smartproxy'; import { SmartProxy, createHttpToHttpsRedirect } from '@push.rocks/smartproxy';
const proxy = new SmartProxy({ const proxy = new SmartProxy({
routes: [ routes: [
// Redirect all HTTP traffic to HTTPS
createHttpToHttpsRedirect(['example.com', '*.example.com']) createHttpToHttpsRedirect(['example.com', '*.example.com'])
] ]
}); });
@@ -133,7 +151,8 @@ const route = createWebSocketRoute(
path: '/socket', path: '/socket',
useTls: true, useTls: true,
certificate: 'auto', certificate: 'auto',
pingInterval: 30000 // Keep connections alive pingInterval: 30000, // Keep connections alive
pingTimeout: 10000
} }
); );
``` ```
@@ -154,51 +173,64 @@ let route = createApiGatewayRoute(
} }
); );
// Add rate limiting // Add rate limiting - 100 requests per minute per IP
route = addRateLimiting(route, { route = addRateLimiting(route, {
maxRequests: 100, maxRequests: 100,
window: 60, // seconds window: 60,
keyBy: 'ip' keyBy: 'ip'
}); });
``` ```
### 🎮 Custom Protocol Handler ### 🎮 Custom Protocol Handler
SmartProxy lets you implement any protocol with full socket control:
```typescript ```typescript
import { createSocketHandlerRoute, SocketHandlers } from '@push.rocks/smartproxy'; import { createSocketHandlerRoute, SocketHandlers } from '@push.rocks/smartproxy';
// Pre-built handlers // Use pre-built handlers
const echoRoute = createSocketHandlerRoute( const echoRoute = createSocketHandlerRoute(
'echo.example.com', 'echo.example.com',
7777, 7777,
SocketHandlers.echo SocketHandlers.echo
); );
// Custom handler // Or create your own custom protocol
const customRoute = createSocketHandlerRoute( const customRoute = createSocketHandlerRoute(
'custom.example.com', 'custom.example.com',
9999, 9999,
async (socket, context) => { async (socket, context) => {
console.log(`Connection from ${context.clientIp}`); console.log(`Connection from ${context.clientIp}`);
socket.write('Welcome to my custom protocol!\n'); socket.write('Welcome to my custom protocol!\n');
socket.on('data', (data) => { socket.on('data', (data) => {
const command = data.toString().trim(); const command = data.toString().trim();
switch (command) {
if (command === 'HELLO') { case 'PING': socket.write('PONG\n'); break;
socket.write('World!\n'); case 'TIME': socket.write(`${new Date().toISOString()}\n`); break;
} else if (command === 'EXIT') { case 'QUIT': socket.end('Goodbye!\n'); break;
socket.end('Goodbye!\n'); default: socket.write(`Unknown: ${command}\n`);
} }
}); });
} }
); );
``` ```
**Pre-built Socket Handlers:**
| Handler | Description |
|---------|-------------|
| `SocketHandlers.echo` | Echo server - returns everything sent |
| `SocketHandlers.proxy(host, port)` | TCP proxy to another server |
| `SocketHandlers.lineProtocol(handler)` | Line-based text protocol |
| `SocketHandlers.httpResponse(code, body)` | Simple HTTP response |
| `SocketHandlers.httpRedirect(url, code)` | HTTP redirect with templates |
| `SocketHandlers.httpServer(handler)` | Full HTTP request/response handling |
| `SocketHandlers.block(message)` | Block with optional message |
### ⚡ High-Performance NFTables Forwarding ### ⚡ High-Performance NFTables Forwarding
For ultra-low latency, use kernel-level forwarding (Linux only, requires root): For ultra-low latency on Linux, use kernel-level forwarding (requires root):
```typescript ```typescript
import { createNfTablesTerminateRoute } from '@push.rocks/smartproxy'; import { createNfTablesTerminateRoute } from '@push.rocks/smartproxy';
@@ -209,8 +241,8 @@ const route = createNfTablesTerminateRoute(
{ {
ports: 443, ports: 443,
certificate: 'auto', certificate: 'auto',
preserveSourceIP: true, preserveSourceIP: true, // Backend sees real client IP
maxRate: '1gbps' maxRate: '1gbps' // QoS rate limiting
} }
); );
``` ```
@@ -223,20 +255,17 @@ Route traffic based on runtime conditions:
```typescript ```typescript
{ {
name: 'business-hours-only',
match: { match: {
ports: 443, ports: 443,
customMatcher: async (context) => { domains: 'internal.example.com'
// Route based on time of day
const hour = new Date().getHours();
return hour >= 9 && hour < 17; // Business hours only
}
}, },
action: { action: {
type: 'forward', type: 'forward',
targets: [{ targets: [{
host: (context) => { host: (context) => {
// Dynamic host selection // Dynamic host selection based on path
return context.path.startsWith('/premium') return context.path?.startsWith('/premium')
? 'premium-backend' ? 'premium-backend'
: 'standard-backend'; : 'standard-backend';
}, },
@@ -248,10 +277,16 @@ Route traffic based on runtime conditions:
### 🔒 Security Controls ### 🔒 Security Controls
Comprehensive security options per route: Comprehensive per-route security options:
```typescript ```typescript
{ {
name: 'secure-api',
match: { ports: 443, domains: 'api.example.com' },
action: {
type: 'forward',
targets: [{ host: 'api-backend', port: 8080 }]
},
security: { security: {
// IP-based access control // IP-based access control
ipAllowList: ['10.0.0.0/8', '192.168.*'], ipAllowList: ['10.0.0.0/8', '192.168.*'],
@@ -265,13 +300,6 @@ Comprehensive security options per route:
rateLimit: { rateLimit: {
maxRequests: 100, maxRequests: 100,
windowMs: 60000 windowMs: 60000
},
// Authentication
authentication: {
type: 'jwt',
secret: process.env.JWT_SECRET,
algorithms: ['HS256']
} }
} }
} }
@@ -282,7 +310,7 @@ Comprehensive security options per route:
Control your proxy without restarts: Control your proxy without restarts:
```typescript ```typescript
// Add/remove ports dynamically // Dynamic port management
await proxy.addListeningPort(8443); await proxy.addListeningPort(8443);
await proxy.removeListeningPort(8080); await proxy.removeListeningPort(8080);
@@ -291,25 +319,31 @@ await proxy.updateRoutes([...newRoutes]);
// Monitor status // Monitor status
const status = proxy.getStatus(); const status = proxy.getStatus();
console.log(`Active connections: ${status.activeConnections}`);
// Get detailed metrics
const metrics = proxy.getMetrics(); const metrics = proxy.getMetrics();
console.log(`Throughput: ${metrics.throughput.bytesPerSecond} bytes/sec`);
// Certificate management // Certificate management
await proxy.renewCertificate('example.com');
const certInfo = proxy.getCertificateInfo('example.com'); const certInfo = proxy.getCertificateInfo('example.com');
console.log(`Certificate expires: ${certInfo.expiresAt}`);
``` ```
### 🔄 Header Manipulation ### 🔄 Header Manipulation
Transform requests and responses: Transform requests and responses with template variables:
```typescript ```typescript
{ {
action: { action: {
type: 'forward',
targets: [{ host: 'backend', port: 8080 }],
headers: { headers: {
request: { request: {
'X-Real-IP': '{clientIp}', // Template variables 'X-Real-IP': '{clientIp}',
'X-Request-ID': '{uuid}', 'X-Request-ID': '{uuid}',
'X-Custom': 'value' 'X-Forwarded-Proto': 'https'
}, },
response: { response: {
'X-Powered-By': 'SmartProxy', 'X-Powered-By': 'SmartProxy',
@@ -327,13 +361,15 @@ SmartProxy is built with a modular, extensible architecture:
``` ```
SmartProxy SmartProxy
├── 📋 Route Manager # Route matching and prioritization ├── 📋 RouteManager # Route matching and prioritization
├── 🔌 Port Manager # Dynamic port lifecycle ├── 🔌 PortManager # Dynamic port lifecycle management
├── 🔒 Certificate Manager # ACME/Let's Encrypt automation ├── 🔒 SmartCertManager # ACME/Let's Encrypt automation
├── 🚦 Connection Manager # Connection pooling and limits ├── 🚦 ConnectionManager # Connection pooling and tracking
├── 📊 Metrics Collector # Performance monitoring ├── 📊 MetricsCollector # Real-time performance monitoring
├── 🛡️ Security Manager # Access control and rate limiting ├── 🛡️ SecurityManager # Access control and rate limiting
── 🔧 Protocol Detectors # Smart protocol identification ── 🔧 ProtocolDetector # Smart HTTP/TLS/WebSocket detection
├── ⚡ NFTablesManager # Kernel-level forwarding (Linux)
└── 🌐 HttpProxyBridge # HTTP/HTTPS request handling
``` ```
## 🎯 Route Configuration Reference ## 🎯 Route Configuration Reference
@@ -346,87 +382,115 @@ interface IRouteMatch {
domains?: string | string[]; // 'example.com', '*.example.com' domains?: string | string[]; // 'example.com', '*.example.com'
path?: string; // '/api/*', '/users/:id' path?: string; // '/api/*', '/users/:id'
clientIp?: string | string[]; // '10.0.0.0/8', ['192.168.*'] clientIp?: string | string[]; // '10.0.0.0/8', ['192.168.*']
protocol?: 'tcp' | 'udp' | 'http' | 'https' | 'ws' | 'wss';
tlsVersion?: string | string[]; // ['TLSv1.2', 'TLSv1.3'] tlsVersion?: string | string[]; // ['TLSv1.2', 'TLSv1.3']
customMatcher?: (context) => boolean; // Custom logic
} }
``` ```
### Action Types ### Action Types
| Type | Description |
|------|-------------|
| `forward` | Proxy to one or more backend targets |
| `redirect` | HTTP redirect with status code |
| `block` | Block the connection |
| `socket-handler` | Custom socket handling function |
### TLS Options
```typescript ```typescript
interface IRouteAction { interface IRouteTls {
type: 'forward' | 'redirect' | 'block' | 'socket-handler'; mode: 'passthrough' | 'terminate' | 'terminate-and-reencrypt';
certificate: 'auto' | { key: string; cert: string };
// For 'forward' // For terminate-and-reencrypt:
targets?: Array<{ reencrypt?: {
host: string | string[] | ((context) => string); host: string;
port: number | ((context) => number); port: number;
}>; ca?: string; // Custom CA for backend
// 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;
}; };
} }
``` ```
## 🛠️ Helper Functions Reference
All helpers are fully typed and documented:
```typescript
import {
// HTTP/HTTPS
createHttpRoute,
createHttpsTerminateRoute,
createHttpsPassthroughRoute,
createHttpToHttpsRedirect,
createCompleteHttpsServer,
// Load Balancing
createLoadBalancerRoute,
createSmartLoadBalancer,
// API & WebSocket
createApiRoute,
createApiGatewayRoute,
createWebSocketRoute,
// Custom Protocols
createSocketHandlerRoute,
SocketHandlers,
// NFTables (Linux)
createNfTablesRoute,
createNfTablesTerminateRoute,
createCompleteNfTablesHttpsServer,
// Dynamic Routing
createPortMappingRoute,
createOffsetPortMappingRoute,
createDynamicRoute,
// Security Modifiers
addRateLimiting,
addBasicAuth,
addJwtAuth
} from '@push.rocks/smartproxy';
```
## 🐛 Troubleshooting ## 🐛 Troubleshooting
### Certificate Issues ### Certificate Issues
- ✅ Ensure domain points to your server - ✅ Ensure domain DNS points to your server
- ✅ Port 80 must be accessible for ACME challenges - ✅ Port 80 must be accessible for ACME HTTP-01 challenges
- ✅ Check DNS propagation with `nslookup` - ✅ Check DNS propagation with `dig` or `nslookup`
- ✅ Verify email in ACME configuration - ✅ Verify the email in ACME configuration is valid
### Connection Problems ### Connection Problems
- ✅ Check route priorities (higher = matched first) - ✅ Check route priorities (higher number = matched first)
- ✅ Verify security rules aren't blocking - ✅ Verify security rules aren't blocking legitimate traffic
- ✅ Test with `curl -v` for detailed output - ✅ Test with `curl -v` for detailed connection output
- ✅ Enable debug mode for verbose logging - ✅ Enable debug logging for verbose output
### Performance Tuning ### Performance Tuning
- ✅ Use NFTables for high-traffic routes - ✅ Use NFTables forwarding for high-traffic routes (Linux only)
- ✅ Enable connection pooling - ✅ Enable connection keep-alive where appropriate
-Adjust keep-alive settings -Monitor metrics to identify bottlenecks
-Monitor with built-in metrics -Adjust `maxConnections` based on your server resources
### Debug Mode ### Debug Mode
```typescript ```typescript
const proxy = new SmartProxy({ const proxy = new SmartProxy({
debug: true, // Enable verbose logging enableDetailedLogging: true, // Verbose connection logging
routes: [...] routes: [...]
}); });
``` ```
## 🚀 Migration from v20.x to v21.x
No breaking changes! v21.x adds enhanced socket cleanup, improved connection tracking, and better process exit handling.
## 🏆 Best Practices ## 🏆 Best Practices
1. **📝 Use Helper Functions** - They provide sensible defaults and prevent errors 1. **📝 Use Helper Functions** - They provide sensible defaults and prevent common mistakes
2. **🎯 Set Route Priorities** - More specific routes should have higher priority 2. **🎯 Set Route Priorities** - More specific routes should have higher priority values
3. **🔒 Always Enable Security** - Use IP filtering and rate limiting for public services 3. **🔒 Enable Security** - Always use IP filtering and rate limiting for public services
4. **📊 Monitor Performance** - Use metrics to identify bottlenecks 4. **📊 Monitor Metrics** - Use the built-in metrics to identify issues early
5. **🔄 Regular Certificate Checks** - Monitor expiration and renewal status 5. **🔄 Certificate Monitoring** - Set up alerts for certificate expiration
6. **🛑 Graceful Shutdown** - Always call `proxy.stop()` for clean shutdown 6. **🛑 Graceful Shutdown** - Always call `proxy.stop()` for clean connection termination
7. **🎮 Test Your Routes** - Use the route testing utilities before production 7. **🔧 Test Routes** - Validate your route configurations before deploying to production
## 📖 API Documentation ## 📖 API Documentation
@@ -434,7 +498,7 @@ No breaking changes! v21.x adds enhanced socket cleanup, improved connection tra
```typescript ```typescript
class SmartProxy { class SmartProxy {
constructor(options: IRoutedSmartProxyOptions); constructor(options: ISmartProxyOptions);
// Lifecycle // Lifecycle
start(): Promise<void>; start(): Promise<void>;
@@ -442,66 +506,65 @@ class SmartProxy {
// Route Management // Route Management
updateRoutes(routes: IRouteConfig[]): Promise<void>; updateRoutes(routes: IRouteConfig[]): Promise<void>;
addRoute(route: IRouteConfig): Promise<void>;
removeRoute(routeName: string): Promise<void>;
findMatchingRoute(context: Partial<IRouteContext>): IRouteConfig | null;
// Port Management // Port Management
addListeningPort(port: number): Promise<void>; addListeningPort(port: number): Promise<void>;
removeListeningPort(port: number): Promise<void>; removeListeningPort(port: number): Promise<void>;
getListeningPorts(): number[]; getListeningPorts(): number[];
// Certificate Management
getCertificateInfo(domain: string): ICertificateInfo | null;
renewCertificate(domain: string): Promise<void>;
// Monitoring // Monitoring
getStatus(): IProxyStatus; getStatus(): IProxyStatus;
getMetrics(): IProxyMetrics; getMetrics(): IMetrics;
// Certificate Management
getCertificateInfo(domain: string): ICertStatus | null;
} }
``` ```
### Helper Functions ### Configuration Options
All helper functions are fully typed and documented. Import them from the main package:
```typescript ```typescript
import { interface ISmartProxyOptions {
createHttpRoute, routes: IRouteConfig[]; // Required: array of route configs
createHttpsTerminateRoute,
createHttpsPassthroughRoute, // ACME/Let's Encrypt
createHttpToHttpsRedirect, acme?: {
createCompleteHttpsServer, email: string; // Contact email
createLoadBalancerRoute, useProduction?: boolean; // Use production servers (default: false)
createApiRoute, port?: number; // Challenge port (default: 80)
createWebSocketRoute, renewThresholdDays?: number; // Days before expiry to renew (default: 30)
createSocketHandlerRoute, };
createNfTablesRoute,
createPortMappingRoute, // Defaults
createDynamicRoute, defaults?: {
createApiGatewayRoute, target?: { host: string; port: number };
addRateLimiting, security?: IRouteSecurity;
addBasicAuth, tls?: IRouteTls;
addJwtAuth, };
SocketHandlers
} from '@push.rocks/smartproxy'; // Behavior
enableDetailedLogging?: boolean;
gracefulShutdownTimeout?: number; // ms to wait for connections to close
}
``` ```
## License and Legal Information ## License and Legal Information
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. This repository contains open-source code licensed under the MIT License. A copy of the license can be found in the [LICENSE](./LICENSE) file.
**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. **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 ### Trademarks
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. 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.
### Company Information ### Company Information
Task Venture Capital GmbH Task Venture Capital GmbH
Registered at District court Bremen HRB 35230 HB, Germany Registered at District Court Bremen HRB 35230 HB, Germany
For any legal inquiries or if you require further information, please contact us via email at hello@task.vc. For any legal inquiries or further information, please contact us via email at hello@task.vc.
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. 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.

View File

@@ -0,0 +1,385 @@
/**
* Tests for smart SNI requirement calculation
*
* These tests verify that the calculateSniRequirement() method correctly determines
* when SNI (Server Name Indication) is required for routing decisions.
*/
import { expect, tap } from '@git.zone/tstest/tapbundle';
import { SmartProxy } from '../ts/proxies/smart-proxy/index.js';
import type { IRouteConfig } from '../ts/proxies/smart-proxy/models/route-types.js';
// Use unique high ports for each test to avoid conflicts
let testPort = 20000;
const getNextPort = () => testPort++;
// --------------------------------- Single Route, No Domain Restriction ---------------------------------
tap.test('SNI Requirement: Single passthrough, no domains, static target - should allow session tickets', async () => {
const port = getNextPort();
const routes: IRouteConfig[] = [{
name: 'passthrough-no-domains',
match: { ports: port },
action: {
type: 'forward',
targets: [{ host: 'backend-server', port: 9443 }],
tls: { mode: 'passthrough' }
}
}];
const proxy = new SmartProxy({ routes });
await proxy.start();
const routesOnPort = proxy.routeManager.getRoutesForPort(port);
expect(routesOnPort.length).toEqual(1);
expect(routesOnPort[0].action.tls?.mode).toEqual('passthrough');
expect(routesOnPort[0].match.domains).toBeUndefined();
expect(typeof routesOnPort[0].action.targets?.[0].host).toEqual('string');
await proxy.stop();
});
tap.test('SNI Requirement: Single passthrough, domains: "*", static target - should allow session tickets', async () => {
const port = getNextPort();
const routes: IRouteConfig[] = [{
name: 'passthrough-wildcard-domain',
match: { ports: port, domains: '*' },
action: {
type: 'forward',
targets: [{ host: 'backend-server', port: 9443 }],
tls: { mode: 'passthrough' }
}
}];
const proxy = new SmartProxy({ routes });
await proxy.start();
const routesOnPort = proxy.routeManager.getRoutesForPort(port);
expect(routesOnPort.length).toEqual(1);
expect(routesOnPort[0].match.domains).toEqual('*');
await proxy.stop();
});
tap.test('SNI Requirement: Single passthrough, domains: ["*"], static target - should allow session tickets', async () => {
const port = getNextPort();
const routes: IRouteConfig[] = [{
name: 'passthrough-wildcard-array',
match: { ports: port, domains: ['*'] },
action: {
type: 'forward',
targets: [{ host: 'backend-server', port: 9443 }],
tls: { mode: 'passthrough' }
}
}];
const proxy = new SmartProxy({ routes });
await proxy.start();
const routesOnPort = proxy.routeManager.getRoutesForPort(port);
expect(routesOnPort.length).toEqual(1);
expect(routesOnPort[0].match.domains).toEqual(['*']);
await proxy.stop();
});
// --------------------------------- Single Route, Specific Domain ---------------------------------
tap.test('SNI Requirement: Single passthrough, specific domain - should require SNI (block session tickets)', async () => {
const port = getNextPort();
const routes: IRouteConfig[] = [{
name: 'passthrough-specific-domain',
match: { ports: port, domains: 'api.example.com' },
action: {
type: 'forward',
targets: [{ host: 'backend-server', port: 9443 }],
tls: { mode: 'passthrough' }
}
}];
const proxy = new SmartProxy({ routes });
await proxy.start();
const routesOnPort = proxy.routeManager.getRoutesForPort(port);
expect(routesOnPort.length).toEqual(1);
expect(routesOnPort[0].match.domains).toEqual('api.example.com');
await proxy.stop();
});
tap.test('SNI Requirement: Single passthrough, multiple specific domains - should require SNI', async () => {
const port = getNextPort();
const routes: IRouteConfig[] = [{
name: 'passthrough-multiple-domains',
match: { ports: port, domains: ['a.example.com', 'b.example.com'] },
action: {
type: 'forward',
targets: [{ host: 'backend-server', port: 9443 }],
tls: { mode: 'passthrough' }
}
}];
const proxy = new SmartProxy({ routes });
await proxy.start();
const routesOnPort = proxy.routeManager.getRoutesForPort(port);
expect(routesOnPort.length).toEqual(1);
expect(routesOnPort[0].match.domains).toEqual(['a.example.com', 'b.example.com']);
await proxy.stop();
});
tap.test('SNI Requirement: Single passthrough, pattern domain - should require SNI', async () => {
const port = getNextPort();
const routes: IRouteConfig[] = [{
name: 'passthrough-pattern-domain',
match: { ports: port, domains: '*.example.com' },
action: {
type: 'forward',
targets: [{ host: 'backend-server', port: 9443 }],
tls: { mode: 'passthrough' }
}
}];
const proxy = new SmartProxy({ routes });
await proxy.start();
const routesOnPort = proxy.routeManager.getRoutesForPort(port);
expect(routesOnPort.length).toEqual(1);
expect(routesOnPort[0].match.domains).toEqual('*.example.com');
await proxy.stop();
});
// --------------------------------- Single Route, Dynamic Target ---------------------------------
tap.test('SNI Requirement: Single passthrough, dynamic host function - should require SNI', async () => {
const port = getNextPort();
const routes: IRouteConfig[] = [{
name: 'passthrough-dynamic-host',
match: { ports: port },
action: {
type: 'forward',
targets: [{
host: (context) => {
if (context.domain === 'api.example.com') return 'api-backend';
return 'web-backend';
},
port: 9443
}],
tls: { mode: 'passthrough' }
}
}];
const proxy = new SmartProxy({ routes });
await proxy.start();
const routesOnPort = proxy.routeManager.getRoutesForPort(port);
expect(routesOnPort.length).toEqual(1);
expect(typeof routesOnPort[0].action.targets?.[0].host).toEqual('function');
await proxy.stop();
});
// --------------------------------- Multiple Routes on Same Port ---------------------------------
tap.test('SNI Requirement: Multiple passthrough routes on same port - should require SNI', async () => {
const port = getNextPort();
const routes: IRouteConfig[] = [
{
name: 'passthrough-api',
match: { ports: port, domains: 'api.example.com' },
action: {
type: 'forward',
targets: [{ host: 'api-backend', port: 9443 }],
tls: { mode: 'passthrough' }
}
},
{
name: 'passthrough-web',
match: { ports: port, domains: 'web.example.com' },
action: {
type: 'forward',
targets: [{ host: 'web-backend', port: 9443 }],
tls: { mode: 'passthrough' }
}
}
];
const proxy = new SmartProxy({ routes });
await proxy.start();
const routesOnPort = proxy.routeManager.getRoutesForPort(port);
expect(routesOnPort.length).toEqual(2);
await proxy.stop();
});
// --------------------------------- TLS Termination Routes (route config only, no actual cert provisioning) ---------------------------------
tap.test('SNI Requirement: Terminate route config is correctly identified', async () => {
const port = getNextPort();
// Test route configuration without starting the proxy (avoids cert provisioning)
const routes: IRouteConfig[] = [{
name: 'terminate-route',
match: { ports: port, domains: 'secure.example.com' },
action: {
type: 'forward',
targets: [{ host: 'backend', port: 8080 }],
tls: {
mode: 'terminate',
certificate: 'auto'
}
}
}];
// Just verify route config is valid without starting (no ACME timeout)
const proxy = new SmartProxy({
routes,
acme: { email: 'test@example.com', useProduction: false }
});
// Check route manager directly (before start)
expect(routes[0].action.tls?.mode).toEqual('terminate');
expect(routes.length).toEqual(1);
});
tap.test('SNI Requirement: Mixed terminate + passthrough config is correctly identified', async () => {
const port = getNextPort();
const routes: IRouteConfig[] = [
{
name: 'terminate-secure',
match: { ports: port, domains: 'secure.example.com' },
action: {
type: 'forward',
targets: [{ host: 'secure-backend', port: 8080 }],
tls: { mode: 'terminate', certificate: 'auto' }
}
},
{
name: 'passthrough-raw',
match: { ports: port, domains: 'passthrough.example.com' },
action: {
type: 'forward',
targets: [{ host: 'passthrough-backend', port: 9443 }],
tls: { mode: 'passthrough' }
}
}
];
// Verify route configs without starting
const hasTerminate = routes.some(r => r.action.tls?.mode === 'terminate');
const hasPassthrough = routes.some(r => r.action.tls?.mode === 'passthrough');
expect(hasTerminate).toBeTrue();
expect(hasPassthrough).toBeTrue();
expect(routes.length).toEqual(2);
});
tap.test('SNI Requirement: terminate-and-reencrypt config is correctly identified', async () => {
const port = getNextPort();
const routes: IRouteConfig[] = [{
name: 'reencrypt-route',
match: { ports: port, domains: 'reencrypt.example.com' },
action: {
type: 'forward',
targets: [{ host: 'backend', port: 9443 }],
tls: {
mode: 'terminate-and-reencrypt',
certificate: 'auto'
}
}
}];
// Verify route config without starting
expect(routes[0].action.tls?.mode).toEqual('terminate-and-reencrypt');
});
// --------------------------------- Edge Cases ---------------------------------
tap.test('SNI Requirement: No routes on port - should not require SNI', async () => {
const routePort = getNextPort();
const queryPort = getNextPort();
const routes: IRouteConfig[] = [{
name: 'different-port-route',
match: { ports: routePort },
action: {
type: 'forward',
targets: [{ host: 'backend', port: 8080 }],
tls: { mode: 'passthrough' }
}
}];
const proxy = new SmartProxy({ routes });
await proxy.start();
const routesOnQueryPort = proxy.routeManager.getRoutesForPort(queryPort);
expect(routesOnQueryPort.length).toEqual(0);
await proxy.stop();
});
tap.test('SNI Requirement: Multiple static targets in single route - should not require SNI', async () => {
const port = getNextPort();
const routes: IRouteConfig[] = [{
name: 'multiple-static-targets',
match: { ports: port },
action: {
type: 'forward',
targets: [
{ host: 'backend1', port: 9443 },
{ host: 'backend2', port: 9443 }
],
tls: { mode: 'passthrough' }
}
}];
const proxy = new SmartProxy({ routes });
await proxy.start();
const routesOnPort = proxy.routeManager.getRoutesForPort(port);
expect(routesOnPort.length).toEqual(1);
expect(routesOnPort[0].action.targets?.length).toEqual(2);
expect(typeof routesOnPort[0].action.targets?.[0].host).toEqual('string');
expect(typeof routesOnPort[0].action.targets?.[1].host).toEqual('string');
await proxy.stop();
});
tap.test('SNI Requirement: Host array (load balancing) is still static - should not require SNI', async () => {
const port = getNextPort();
const routes: IRouteConfig[] = [{
name: 'host-array-static',
match: { ports: port },
action: {
type: 'forward',
targets: [{
host: ['backend1', 'backend2', 'backend3'],
port: 9443
}],
tls: { mode: 'passthrough' }
}
}];
const proxy = new SmartProxy({ routes });
await proxy.start();
const routesOnPort = proxy.routeManager.getRoutesForPort(port);
expect(routesOnPort.length).toEqual(1);
expect(Array.isArray(routesOnPort[0].action.targets?.[0].host)).toBeTrue();
await proxy.stop();
});
export default tap.start();

View File

@@ -3,6 +3,6 @@
*/ */
export const commitinfo = { export const commitinfo = {
name: '@push.rocks/smartproxy', name: '@push.rocks/smartproxy',
version: '22.2.0', version: '22.4.0',
description: 'A powerful proxy package with unified route-based configuration for high traffic management. Features include SSL/TLS support, flexible routing patterns, WebSocket handling, advanced security options, and automatic ACME certificate management.' description: 'A powerful proxy package with unified route-based configuration for high traffic management. Features include SSL/TLS support, flexible routing patterns, WebSocket handling, advanced security options, and automatic ACME certificate management.'
} }

View File

@@ -69,6 +69,58 @@ export class RouteConnectionHandler {
}; };
} }
/**
* Determines if SNI is required for routing decisions on this port.
*
* SNI is REQUIRED when:
* - Multiple routes exist on this port (need SNI to pick correct route)
* - Route has dynamic target function (needs ctx.domain)
* - Route has specific domain restriction (strict validation)
*
* SNI is NOT required when:
* - TLS termination mode (HttpProxy handles session resumption)
* - Single route with static target and no domain restriction (or wildcard)
*/
private calculateSniRequirement(port: number): boolean {
const routesOnPort = this.smartProxy.routeManager.getRoutesForPort(port);
// No routes = no SNI requirement (will fail routing anyway)
if (routesOnPort.length === 0) return false;
// Check if any route terminates TLS - if so, SNI not required
// (HttpProxy handles session resumption internally)
const hasTermination = routesOnPort.some(route =>
route.action.tls?.mode === 'terminate' ||
route.action.tls?.mode === 'terminate-and-reencrypt'
);
if (hasTermination) return false;
// Multiple routes = need SNI to pick the correct route
if (routesOnPort.length > 1) return true;
// Single route - check if it needs SNI for validation or routing
const route = routesOnPort[0];
// Dynamic host selection requires SNI (function receives ctx.domain)
const hasDynamicTarget = route.action.targets?.some(t => typeof t.host === 'function');
if (hasDynamicTarget) return true;
// Specific domain restriction requires SNI for strict validation
const hasSpecificDomain = route.match.domains && !this.isWildcardOnly(route.match.domains);
if (hasSpecificDomain) return true;
// Single route, static target(s), no domain restriction = SNI not required
return false;
}
/**
* Check if domains config is wildcard-only (matches everything)
*/
private isWildcardOnly(domains: string | string[]): boolean {
const domainList = Array.isArray(domains) ? domains : [domains];
return domainList.length === 1 && domainList[0] === '*';
}
/** /**
* Handle a new incoming connection * Handle a new incoming connection
*/ */
@@ -201,19 +253,10 @@ export class RouteConnectionHandler {
route.action.tls.mode === 'passthrough'); route.action.tls.mode === 'passthrough');
}); });
// Auto-calculate session ticket handling based on route configuration // Smart SNI requirement calculation
// If any route on this port terminates TLS, allow session tickets (HttpProxy handles resumption) // Determines if we need SNI for routing decisions on this port
// Otherwise, block session tickets (need SNI for passthrough routing) const needsSniForRouting = this.calculateSniRequirement(localPort);
const hasTlsTermination = allRoutes.some(route => { const allowSessionTicket = !needsSniForRouting;
const matchesPort = this.smartProxy.routeManager.getRoutesForPort(localPort).includes(route);
return matchesPort &&
route.action.type === 'forward' &&
route.action.tls &&
(route.action.tls.mode === 'terminate' ||
route.action.tls.mode === 'terminate-and-reencrypt');
});
const allowSessionTicket = hasTlsTermination;
// If no routes require TLS handling and it's not port 443, route immediately // If no routes require TLS handling and it's not port 443, route immediately
if (!needsTlsHandling && localPort !== 443) { if (!needsTlsHandling && localPort !== 443) {