@push.rocks/smartproxy 13.1.2 → 15.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/dist_ts/00_commitinfo_data.js +3 -3
  2. package/dist_ts/proxies/smart-proxy/index.d.ts +5 -3
  3. package/dist_ts/proxies/smart-proxy/index.js +9 -5
  4. package/dist_ts/proxies/smart-proxy/models/index.d.ts +2 -0
  5. package/dist_ts/proxies/smart-proxy/models/index.js +2 -1
  6. package/dist_ts/proxies/smart-proxy/models/interfaces.d.ts +82 -15
  7. package/dist_ts/proxies/smart-proxy/models/interfaces.js +10 -1
  8. package/dist_ts/proxies/smart-proxy/models/route-types.d.ts +133 -0
  9. package/dist_ts/proxies/smart-proxy/models/route-types.js +2 -0
  10. package/dist_ts/proxies/smart-proxy/route-connection-handler.d.ts +55 -0
  11. package/dist_ts/proxies/smart-proxy/route-connection-handler.js +804 -0
  12. package/dist_ts/proxies/smart-proxy/route-helpers.d.ts +127 -0
  13. package/dist_ts/proxies/smart-proxy/route-helpers.js +196 -0
  14. package/dist_ts/proxies/smart-proxy/route-manager.d.ts +103 -0
  15. package/dist_ts/proxies/smart-proxy/route-manager.js +483 -0
  16. package/dist_ts/proxies/smart-proxy/smart-proxy.d.ts +19 -8
  17. package/dist_ts/proxies/smart-proxy/smart-proxy.js +239 -46
  18. package/package.json +2 -2
  19. package/readme.md +863 -423
  20. package/readme.plan.md +311 -250
  21. package/ts/00_commitinfo_data.ts +2 -2
  22. package/ts/proxies/smart-proxy/index.ts +20 -4
  23. package/ts/proxies/smart-proxy/models/index.ts +4 -0
  24. package/ts/proxies/smart-proxy/models/interfaces.ts +91 -13
  25. package/ts/proxies/smart-proxy/models/route-types.ts +184 -0
  26. package/ts/proxies/smart-proxy/route-connection-handler.ts +1117 -0
  27. package/ts/proxies/smart-proxy/route-helpers.ts +344 -0
  28. package/ts/proxies/smart-proxy/route-manager.ts +587 -0
  29. package/ts/proxies/smart-proxy/smart-proxy.ts +300 -69
package/readme.md CHANGED
@@ -1,16 +1,17 @@
1
1
  # @push.rocks/smartproxy
2
2
 
3
- A high-performance proxy toolkit for Node.js, offering:
4
- - HTTP/HTTPS reverse proxy with TLS termination and WebSocket support
5
- - Automatic ACME certificate management (HTTP-01)
6
- - Low-level port forwarding via nftables
7
- - HTTP-to-HTTPS and custom URL redirects
8
- - Advanced TCP/SNI-based proxying with IP filtering and rules
9
- - Unified forwarding configuration system for all proxy types
3
+ A unified high-performance proxy toolkit for Node.js, with **SmartProxy** as the central API to handle all your proxy needs:
4
+
5
+ - **Unified Route-Based Configuration**: Match/action pattern for clean, consistent traffic routing
6
+ - **SSL/TLS Support**: Automatic HTTPS with Let's Encrypt certificate provisioning
7
+ - **Flexible Matching Patterns**: Route by port, domain, path, client IP, and TLS version
8
+ - **Advanced SNI Handling**: Smart TCP/SNI-based forwarding with IP filtering
9
+ - **Multiple Action Types**: Forward (with TLS modes), redirect, or block traffic
10
+ - **Security Features**: IP allowlists, connection limits, timeouts, and more
10
11
 
11
12
  ## Project Architecture Overview
12
13
 
13
- SmartProxy has been restructured using a modern, modular architecture to improve maintainability and clarity:
14
+ SmartProxy has been restructured using a modern, modular architecture with a unified route-based configuration system in v14.0.0:
14
15
 
15
16
  ```
16
17
  /ts
@@ -28,19 +29,17 @@ SmartProxy has been restructured using a modern, modular architecture to improve
28
29
  │ │ ├── http-handler.ts # HTTP-only handler
29
30
  │ │ └── ... # Other handlers
30
31
  │ ├── /config # Configuration models
31
- │ │ ├── forwarding-types.ts # Type definitions
32
- │ │ ├── domain-config.ts # Domain config utilities
33
- │ │ └── domain-manager.ts # Domain routing manager
34
32
  │ └── /factory # Factory for creating handlers
35
33
  ├── /proxies # Different proxy implementations
36
34
  │ ├── /smart-proxy # SmartProxy implementation
37
35
  │ │ ├── /models # SmartProxy-specific interfaces
36
+ │ │ │ ├── route-types.ts # Route-based configuration types
37
+ │ │ │ └── interfaces.ts # SmartProxy interfaces
38
+ │ │ ├── route-helpers.ts # Helper functions for creating routes
39
+ │ │ ├── route-manager.ts # Route management system
38
40
  │ │ ├── smart-proxy.ts # Main SmartProxy class
39
41
  │ │ └── ... # Supporting classes
40
42
  │ ├── /network-proxy # NetworkProxy implementation
41
- │ │ ├── /models # NetworkProxy-specific interfaces
42
- │ │ ├── network-proxy.ts # Main NetworkProxy class
43
- │ │ └── ... # Supporting classes
44
43
  │ └── /nftables-proxy # NfTablesProxy implementation
45
44
  ├── /tls # TLS-specific functionality
46
45
  │ ├── /sni # SNI handling components
@@ -51,34 +50,54 @@ SmartProxy has been restructured using a modern, modular architecture to improve
51
50
  └── /redirects # Redirect handlers
52
51
  ```
53
52
 
54
- ## Exports
55
- The following classes and interfaces are provided:
53
+ ## Main Components
54
+
55
+ ### Primary API (Recommended)
56
+
57
+ - **SmartProxy** (`ts/proxies/smart-proxy/smart-proxy.ts`)
58
+ The central unified API for all proxy needs, featuring:
59
+ - Route-based configuration with match/action pattern
60
+ - Flexible matching criteria (ports, domains, paths, client IPs)
61
+ - Multiple action types (forward, redirect, block)
62
+ - Automatic certificate management
63
+ - Advanced security controls
64
+
65
+ ### Helper Functions
66
+
67
+ - **createRoute**, **createHttpRoute**, **createHttpsRoute**, **createPassthroughRoute**
68
+ Helper functions to create different route configurations with clean syntax
69
+ - **createRedirectRoute**, **createHttpToHttpsRedirect**, **createBlockRoute**
70
+ Helper functions for common redirect and security configurations
71
+ - **createLoadBalancerRoute**, **createHttpsServer**
72
+ Helper functions for complex configurations
73
+
74
+ ### Specialized Components
56
75
 
57
76
  - **NetworkProxy** (`ts/proxies/network-proxy/network-proxy.ts`)
58
- HTTP/HTTPS reverse proxy with TLS termination, WebSocket support,
59
- connection pooling, and optional ACME integration.
77
+ HTTP/HTTPS reverse proxy with TLS termination and WebSocket support
60
78
  - **Port80Handler** (`ts/http/port80/port80-handler.ts`)
61
- ACME HTTP-01 challenge handler and certificate manager.
79
+ ACME HTTP-01 challenge handler for Let's Encrypt certificates
62
80
  - **NfTablesProxy** (`ts/proxies/nftables-proxy/nftables-proxy.ts`)
63
- Low-level port forwarding using nftables NAT rules.
81
+ Low-level port forwarding using nftables NAT rules
64
82
  - **Redirect**, **SslRedirect** (`ts/http/redirects/redirect-handler.ts`)
65
- HTTP/HTTPS redirect server and shortcut for HTTP→HTTPS.
66
- - **SmartProxy** (`ts/proxies/smart-proxy/smart-proxy.ts`)
67
- TCP/SNI-based proxy with dynamic routing, IP filtering, and unified certificates.
83
+ HTTP-to-HTTPS redirects with customizable rules
68
84
  - **SniHandler** (`ts/tls/sni/sni-handler.ts`)
69
- Static utilities to extract SNI hostnames from TLS handshakes.
70
- - **Forwarding Handlers** (`ts/forwarding/handlers/*.ts`)
71
- Unified forwarding handlers for different connection types (HTTP, HTTPS passthrough, TLS termination).
72
- - **Core Utilities**
73
- - **ValidationUtils** (`ts/core/utils/validation-utils.ts`) for domain, port, and configuration validation
74
- - **IpUtils** (`ts/core/utils/ip-utils.ts`) for IP address validation and filtering
75
-
76
- - **Interfaces and Types**
77
- - `ISmartProxyOptions`, `IDomainConfig` (`ts/proxies/smart-proxy/models/interfaces.ts`)
78
- - `INetworkProxyOptions` (`ts/proxies/network-proxy/models/types.ts`)
79
- - `IAcmeOptions`, `IDomainOptions` (`ts/certificate/models/certificate-types.ts`)
80
- - `INfTableProxySettings` (`ts/proxies/nftables-proxy/models/interfaces.ts`)
81
- - `IForwardConfig`, `TForwardingType` (`ts/forwarding/config/forwarding-types.ts`)
85
+ Utilities for SNI extraction from TLS handshakes
86
+
87
+ ### Core Utilities
88
+
89
+ - **ValidationUtils** (`ts/core/utils/validation-utils.ts`)
90
+ Domain, port, and configuration validation
91
+ - **IpUtils** (`ts/core/utils/ip-utils.ts`)
92
+ IP address validation and filtering with glob patterns
93
+
94
+ ### Interfaces and Types
95
+
96
+ - `IRouteConfig`, `IRouteMatch`, `IRouteAction` (`ts/proxies/smart-proxy/models/route-types.ts`)
97
+ - `IRoutedSmartProxyOptions` (`ts/proxies/smart-proxy/models/route-types.ts`)
98
+ - `INetworkProxyOptions` (`ts/proxies/network-proxy/models/types.ts`)
99
+ - `IAcmeOptions`, `IDomainOptions` (`ts/certificate/models/certificate-types.ts`)
100
+ - `INfTableProxySettings` (`ts/proxies/nftables-proxy/models/interfaces.ts`)
82
101
 
83
102
  ## Installation
84
103
  Install via npm:
@@ -86,181 +105,559 @@ Install via npm:
86
105
  npm install @push.rocks/smartproxy
87
106
  ```
88
107
 
89
- ## Quick Start
108
+ ## Quick Start with SmartProxy v14.0.0
109
+
110
+ SmartProxy v14.0.0 introduces a new unified route-based configuration system that makes configuring proxies more flexible and intuitive.
90
111
 
91
- ### 1. HTTP(S) Reverse Proxy (NetworkProxy)
92
112
  ```typescript
93
- import { NetworkProxy } from '@push.rocks/smartproxy';
113
+ import {
114
+ SmartProxy,
115
+ createHttpRoute,
116
+ createHttpsRoute,
117
+ createPassthroughRoute,
118
+ createHttpToHttpsRedirect
119
+ } from '@push.rocks/smartproxy';
120
+
121
+ // Create a new SmartProxy instance with route-based configuration
122
+ const proxy = new SmartProxy({
123
+ // Define all your routing rules in one array
124
+ routes: [
125
+ // Basic HTTP route - forward traffic from port 80 to internal service
126
+ createHttpRoute({
127
+ ports: 80,
128
+ domains: 'api.example.com',
129
+ target: { host: 'localhost', port: 3000 }
130
+ }),
131
+
132
+ // HTTPS route with TLS termination and automatic certificates
133
+ createHttpsRoute({
134
+ ports: 443,
135
+ domains: 'secure.example.com',
136
+ target: { host: 'localhost', port: 8080 },
137
+ certificate: 'auto' // Use Let's Encrypt
138
+ }),
139
+
140
+ // HTTPS passthrough for legacy systems
141
+ createPassthroughRoute({
142
+ ports: 443,
143
+ domains: 'legacy.example.com',
144
+ target: { host: '192.168.1.10', port: 443 }
145
+ }),
146
+
147
+ // Redirect HTTP to HTTPS
148
+ createHttpToHttpsRedirect({
149
+ domains: ['example.com', '*.example.com']
150
+ }),
151
+
152
+ // Complex load balancer setup with security controls
153
+ createLoadBalancerRoute({
154
+ domains: ['app.example.com'],
155
+ targets: ['192.168.1.10', '192.168.1.11', '192.168.1.12'],
156
+ targetPort: 8080,
157
+ tlsMode: 'terminate',
158
+ certificate: 'auto',
159
+ security: {
160
+ allowedIps: ['10.0.0.*', '192.168.1.*'],
161
+ blockedIps: ['1.2.3.4'],
162
+ maxConnections: 1000
163
+ }
164
+ })
165
+ ],
94
166
 
95
- const proxy = new NetworkProxy({ port: 443 });
96
- await proxy.start();
167
+ // Global settings that apply to all routes
168
+ defaults: {
169
+ security: {
170
+ maxConnections: 500
171
+ }
172
+ },
97
173
 
98
- await proxy.updateProxyConfigs([
99
- {
100
- hostName: 'example.com',
101
- destinationIps: ['127.0.0.1'],
102
- destinationPorts: [3000],
103
- publicKey: fs.readFileSync('cert.pem', 'utf8'),
104
- privateKey: fs.readFileSync('key.pem', 'utf8'),
174
+ // Automatic Let's Encrypt integration
175
+ acme: {
176
+ enabled: true,
177
+ contactEmail: 'admin@example.com',
178
+ useProduction: true
105
179
  }
106
- ]);
180
+ });
107
181
 
108
- // Add default headers to all responses
109
- await proxy.addDefaultHeaders({
110
- 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
182
+ // Listen for certificate events
183
+ proxy.on('certificate', evt => {
184
+ console.log(`Certificate for ${evt.domain} ready, expires: ${evt.expiryDate}`);
111
185
  });
112
- // ...
186
+
187
+ // Start the proxy
188
+ await proxy.start();
189
+
190
+ // Dynamically add new routes later
191
+ await proxy.addRoutes([
192
+ createHttpsRoute({
193
+ domains: 'new-domain.com',
194
+ target: { host: 'localhost', port: 9000 },
195
+ certificate: 'auto'
196
+ })
197
+ ]);
198
+
199
+ // Later, gracefully shut down
113
200
  await proxy.stop();
114
201
  ```
115
202
 
116
- ### 2. HTTP→HTTPS Redirect (Redirect / SslRedirect)
203
+ ## Route-Based Configuration System
204
+
205
+ SmartProxy v14.0.0 introduces a new unified route configuration system based on the `IRouteConfig` interface. This system follows a match/action pattern that makes routing more powerful, flexible, and declarative.
206
+
207
+ ### IRouteConfig Interface
208
+
209
+ The `IRouteConfig` interface is the core building block of SmartProxy's configuration system. Each route definition consists of match criteria and an action to perform on matched traffic:
210
+
117
211
  ```typescript
118
- import { Redirect, SslRedirect } from '@push.rocks/smartproxy';
119
- import * as fs from 'fs';
212
+ interface IRouteConfig {
213
+ // What traffic to match (required)
214
+ match: IRouteMatch;
215
+
216
+ // What to do with matched traffic (required)
217
+ action: IRouteAction;
218
+
219
+ // Metadata (all optional)
220
+ name?: string; // Human-readable name for this route
221
+ description?: string; // Description of the route's purpose
222
+ priority?: number; // Controls matching order (higher = matched first)
223
+ tags?: string[]; // Arbitrary tags for categorization
224
+ }
225
+ ```
226
+
227
+ #### Match Criteria (IRouteMatch)
228
+
229
+ The `match` property defines criteria for identifying which incoming traffic should be handled by this route:
230
+
231
+ ```typescript
232
+ interface IRouteMatch {
233
+ // Listen on these ports (required)
234
+ ports: TPortRange; // number | number[] | Array<{ from: number; to: number }>
235
+
236
+ // Optional domain patterns to match (default: all domains)
237
+ domains?: string | string[]; // Supports wildcards like '*.example.com'
238
+
239
+ // Advanced matching criteria (all optional)
240
+ path?: string; // Match specific URL paths, supports glob patterns
241
+ clientIp?: string[]; // Match specific client IPs, supports glob patterns
242
+ tlsVersion?: string[]; // Match specific TLS versions e.g. ['TLSv1.2', 'TLSv1.3']
243
+ }
244
+ ```
245
+
246
+ **Port Specification:**
247
+ - **Single port:** `ports: 80`
248
+ - **Multiple ports:** `ports: [80, 443]`
249
+ - **Port ranges:** `ports: [{ from: 8000, to: 8100 }]`
250
+ - **Mixed format:** `ports: [80, 443, { from: 8000, to: 8100 }]`
251
+
252
+ **Domain Matching:**
253
+ - **Single domain:** `domains: 'example.com'`
254
+ - **Multiple domains:** `domains: ['example.com', 'api.example.com']`
255
+ - **Wildcard domains:** `domains: '*.example.com'` (matches any subdomain)
256
+ - **Root domain + subdomains:** `domains: ['example.com', '*.example.com']`
257
+
258
+ **Path Matching:**
259
+ - **Exact path:** `path: '/api'` (matches only /api exactly)
260
+ - **Prefix match:** `path: '/api/*'` (matches /api and any paths under it)
261
+ - **Multiple patterns:** Use multiple routes with different priorities
262
+
263
+ **Client IP Matching:**
264
+ - **Exact IP:** `clientIp: ['192.168.1.1']`
265
+ - **Subnet wildcards:** `clientIp: ['10.0.0.*', '192.168.1.*']`
266
+ - **CIDR notation:** `clientIp: ['10.0.0.0/24']`
267
+
268
+ **TLS Version Matching:**
269
+ - `tlsVersion: ['TLSv1.2', 'TLSv1.3']` (only match these TLS versions)
270
+
271
+ #### Action Configuration (IRouteAction)
272
+
273
+ The `action` property defines what to do with traffic that matches the criteria:
274
+
275
+ ```typescript
276
+ interface IRouteAction {
277
+ // Action type (required)
278
+ type: 'forward' | 'redirect' | 'block';
279
+
280
+ // For 'forward' actions
281
+ target?: IRouteTarget;
282
+
283
+ // TLS handling for 'forward' actions
284
+ tls?: IRouteTls;
285
+
286
+ // For 'redirect' actions
287
+ redirect?: IRouteRedirect;
288
+
289
+ // Security options for any action
290
+ security?: IRouteSecurity;
291
+
292
+ // Advanced options
293
+ advanced?: IRouteAdvanced;
294
+ }
295
+ ```
296
+
297
+ **Forward Action:**
298
+ When `type: 'forward'`, the traffic is forwarded to the specified target:
299
+ ```typescript
300
+ interface IRouteTarget {
301
+ host: string | string[]; // Target host(s) - string array enables round-robin
302
+ port: number; // Target port
303
+ preservePort?: boolean; // Use incoming port as target port (default: false)
304
+ }
305
+ ```
306
+
307
+ **TLS Configuration:**
308
+ When forwarding with TLS, you can configure how TLS is handled:
309
+ ```typescript
310
+ interface IRouteTls {
311
+ mode: 'passthrough' | 'terminate' | 'terminate-and-reencrypt';
312
+ certificate?: 'auto' | { // 'auto' = use ACME (Let's Encrypt)
313
+ key: string; // TLS private key content
314
+ cert: string; // TLS certificate content
315
+ };
316
+ }
317
+ ```
318
+
319
+ **TLS Modes:**
320
+ - **passthrough:** Forward raw encrypted TLS traffic without decryption
321
+ - **terminate:** Terminate TLS and forward as HTTP
322
+ - **terminate-and-reencrypt:** Terminate TLS and create a new TLS connection to the backend
323
+
324
+ **Redirect Action:**
325
+ When `type: 'redirect'`, the client is redirected:
326
+ ```typescript
327
+ interface IRouteRedirect {
328
+ to: string; // URL or template with variables
329
+ status: 301 | 302 | 307 | 308; // HTTP status code
330
+ }
331
+ ```
332
+
333
+ **Block Action:**
334
+ When `type: 'block'`, the connection is immediately closed.
335
+
336
+ **Security Options:**
337
+ For any action type, you can add security controls:
338
+ ```typescript
339
+ interface IRouteSecurity {
340
+ allowedIps?: string[]; // IP allowlist with glob pattern support
341
+ blockedIps?: string[]; // IP blocklist with glob pattern support
342
+ maxConnections?: number; // Maximum concurrent connections
343
+ authentication?: { // Optional authentication (future support)
344
+ type: 'basic' | 'digest' | 'oauth';
345
+ // Auth-specific options
346
+ };
347
+ }
348
+ ```
349
+
350
+ **Advanced Options:**
351
+ Additional advanced configurations:
352
+ ```typescript
353
+ interface IRouteAdvanced {
354
+ timeout?: number; // Connection timeout in milliseconds
355
+ headers?: Record<string, string>; // Custom HTTP headers
356
+ keepAlive?: boolean; // Enable connection pooling
357
+ // Additional advanced options
358
+ }
359
+ ```
360
+
361
+ #### Template Variables
362
+
363
+ String values in redirect URLs and headers can include variables:
364
+
365
+ - `{domain}`: The requested domain name
366
+ - `{port}`: The incoming port number
367
+ - `{path}`: The requested URL path
368
+ - `{query}`: The query string
369
+ - `{clientIp}`: The client's IP address
370
+ - `{sni}`: The SNI hostname
371
+
372
+ Example with template variables:
373
+ ```typescript
374
+ redirect: {
375
+ to: 'https://{domain}{path}?source=redirect',
376
+ status: 301
377
+ }
378
+ ```
379
+
380
+ #### Route Metadata and Prioritization
381
+
382
+ You can add metadata to routes to help with organization and control matching priority:
383
+
384
+ ```typescript
385
+ {
386
+ name: 'API Server', // Human-readable name
387
+ description: 'Main API endpoints', // Description
388
+ priority: 100, // Matching priority (higher = matched first)
389
+ tags: ['api', 'internal'] // Arbitrary tags
390
+ }
391
+ ```
392
+
393
+ Routes with higher priority values are matched first, allowing you to create specialized routes that take precedence over more general ones.
120
394
 
121
- // Custom redirect rules
122
- const redirect = new Redirect({
123
- httpPort: 80,
124
- httpsPort: 443,
125
- sslOptions: {
126
- key: fs.readFileSync('key.pem'),
127
- cert: fs.readFileSync('cert.pem'),
395
+ #### Complete Route Configuration Example
396
+
397
+ ```typescript
398
+ // Example of a complete route configuration
399
+ {
400
+ match: {
401
+ ports: 443,
402
+ domains: ['api.example.com', 'api-v2.example.com'],
403
+ path: '/secure/*',
404
+ clientIp: ['10.0.0.*', '192.168.1.*']
128
405
  },
129
- rules: [
130
- {
131
- fromProtocol: 'http',
132
- fromHost: '*',
133
- toProtocol: 'https',
134
- toHost: '$1',
135
- statusCode: 301
406
+ action: {
407
+ type: 'forward',
408
+ target: {
409
+ host: ['10.0.0.1', '10.0.0.2'], // Round-robin between these hosts
410
+ port: 8080
411
+ },
412
+ tls: {
413
+ mode: 'terminate',
414
+ certificate: 'auto' // Use Let's Encrypt
415
+ },
416
+ security: {
417
+ allowedIps: ['10.0.0.*'],
418
+ maxConnections: 100
419
+ },
420
+ advanced: {
421
+ timeout: 30000,
422
+ headers: {
423
+ 'X-Original-Host': '{domain}',
424
+ 'X-Client-IP': '{clientIp}'
425
+ },
426
+ keepAlive: true
136
427
  }
137
- ]
428
+ },
429
+ name: 'Secure API Route',
430
+ description: 'Route for secure API endpoints with authentication',
431
+ priority: 100,
432
+ tags: ['api', 'secure', 'internal']
433
+ }
434
+ ```
435
+
436
+ ### Using Helper Functions
437
+
438
+ While you can create route configurations manually, SmartProxy provides helper functions to make it easier:
439
+
440
+ ```typescript
441
+ // Instead of building the full object:
442
+ const route = {
443
+ match: { ports: 80, domains: 'example.com' },
444
+ action: { type: 'forward', target: { host: 'localhost', port: 8080 } },
445
+ name: 'Web Server'
446
+ };
447
+
448
+ // Use the helper function:
449
+ const route = createHttpRoute({
450
+ domains: 'example.com',
451
+ target: { host: 'localhost', port: 8080 },
452
+ name: 'Web Server'
138
453
  });
139
- await redirect.start();
454
+ ```
140
455
 
141
- // Quick HTTP→HTTPS helper on port 80
142
- const quick = new SslRedirect(80);
143
- await quick.start();
456
+ Available helper functions:
457
+ - `createRoute()` - Basic function to create any route configuration
458
+ - `createHttpRoute()` - Create an HTTP forwarding route
459
+ - `createHttpsRoute()` - Create an HTTPS route with TLS termination
460
+ - `createPassthroughRoute()` - Create an HTTPS passthrough route
461
+ - `createRedirectRoute()` - Create a generic redirect route
462
+ - `createHttpToHttpsRedirect()` - Create an HTTP to HTTPS redirect
463
+ - `createBlockRoute()` - Create a route to block specific traffic
464
+ - `createLoadBalancerRoute()` - Create a route for load balancing
465
+ - `createHttpsServer()` - Create a complete HTTPS server setup with HTTP redirect
466
+
467
+ ## What You Can Do with SmartProxy
468
+
469
+ 1. **Route-Based Traffic Management**
470
+ ```typescript
471
+ // Route requests for different domains to different backend servers
472
+ createHttpsRoute({
473
+ domains: 'api.example.com',
474
+ target: { host: 'api-server', port: 3000 },
475
+ certificate: 'auto'
476
+ })
477
+ ```
478
+
479
+ 2. **Automatic SSL with Let's Encrypt**
480
+ ```typescript
481
+ // Get and automatically renew certificates
482
+ createHttpsRoute({
483
+ domains: 'secure.example.com',
484
+ target: { host: 'localhost', port: 8080 },
485
+ certificate: 'auto'
486
+ })
487
+ ```
488
+
489
+ 3. **Load Balancing**
490
+ ```typescript
491
+ // Distribute traffic across multiple backend servers
492
+ createLoadBalancerRoute({
493
+ domains: 'app.example.com',
494
+ targets: ['10.0.0.1', '10.0.0.2', '10.0.0.3'],
495
+ targetPort: 8080,
496
+ tlsMode: 'terminate',
497
+ certificate: 'auto'
498
+ })
499
+ ```
500
+
501
+ 4. **Security Controls**
502
+ ```typescript
503
+ // Restrict access based on IP addresses
504
+ createHttpsRoute({
505
+ domains: 'admin.example.com',
506
+ target: { host: 'localhost', port: 8080 },
507
+ certificate: 'auto',
508
+ security: {
509
+ allowedIps: ['10.0.0.*', '192.168.1.*'],
510
+ maxConnections: 100
511
+ }
512
+ })
513
+ ```
514
+
515
+ 5. **Wildcard Domains**
516
+ ```typescript
517
+ // Handle all subdomains with one config
518
+ createPassthroughRoute({
519
+ domains: ['example.com', '*.example.com'],
520
+ target: { host: 'backend-server', port: 443 }
521
+ })
522
+ ```
523
+
524
+ 6. **Path-Based Routing**
525
+ ```typescript
526
+ // Route based on URL path
527
+ createHttpsRoute({
528
+ domains: 'example.com',
529
+ path: '/api/*',
530
+ target: { host: 'api-server', port: 3000 },
531
+ certificate: 'auto'
532
+ })
533
+ ```
534
+
535
+ 7. **Block Malicious Traffic**
536
+ ```typescript
537
+ // Block traffic from specific IPs
538
+ createBlockRoute({
539
+ ports: [80, 443],
540
+ clientIp: ['1.2.3.*', '5.6.7.*'],
541
+ priority: 1000 // High priority to ensure blocking
542
+ })
543
+ ```
544
+
545
+ ## Other Components
546
+
547
+ While SmartProxy provides a unified API for most needs, you can also use individual components:
548
+
549
+ ### NetworkProxy
550
+ For HTTP/HTTPS reverse proxy with TLS termination and WebSocket support:
551
+
552
+ ```typescript
553
+ import { NetworkProxy } from '@push.rocks/smartproxy';
554
+ import * as fs from 'fs';
555
+
556
+ const proxy = new NetworkProxy({ port: 443 });
557
+ await proxy.start();
558
+ await proxy.updateProxyConfigs([
559
+ {
560
+ hostName: 'example.com',
561
+ destinationIps: ['127.0.0.1'],
562
+ destinationPorts: [3000],
563
+ publicKey: fs.readFileSync('cert.pem', 'utf8'),
564
+ privateKey: fs.readFileSync('key.pem', 'utf8'),
565
+ }
566
+ ]);
144
567
  ```
145
568
 
146
- ### 3. Automatic Certificates (ACME Port80Handler)
569
+ ### Port80Handler
570
+ For standalone ACME certificate management:
571
+
147
572
  ```typescript
148
573
  import { Port80Handler } from '@push.rocks/smartproxy';
149
574
 
150
- // Configure ACME on port 80 with contact email
151
575
  const acme = new Port80Handler({
152
576
  port: 80,
153
577
  contactEmail: 'admin@example.com',
154
- useProduction: true,
155
- renewThresholdDays: 30
156
- });
157
- acme.on('certificate-issued', evt => {
158
- console.log(`Certificate ready for ${evt.domain}, expires ${evt.expiryDate}`);
578
+ useProduction: true
159
579
  });
580
+ acme.on('certificate-issued', evt => console.log(`Certificate ready: ${evt.domain}`));
160
581
  await acme.start();
161
- acme.addDomain({
162
- domainName: 'example.com',
163
- sslRedirect: true,
164
- acmeMaintenance: true
165
- });
166
582
  ```
167
583
 
168
- ### 4. Low-Level Port Forwarding (NfTablesProxy)
584
+ ### NfTablesProxy
585
+ For low-level port forwarding using nftables:
586
+
169
587
  ```typescript
170
588
  import { NfTablesProxy } from '@push.rocks/smartproxy';
171
589
 
172
- // Forward port 80→8080 with source IP preservation
173
590
  const nft = new NfTablesProxy({
174
591
  fromPort: 80,
175
592
  toPort: 8080,
176
593
  toHost: 'localhost',
177
- preserveSourceIP: true,
178
- deleteOnExit: true
594
+ preserveSourceIP: true
179
595
  });
180
596
  await nft.start();
181
- // ...
182
- await nft.stop();
183
597
  ```
184
598
 
185
- ### 5. TCP/SNI Proxy (SmartProxy)
599
+ ### Redirect / SslRedirect
600
+ For HTTP-to-HTTPS redirects:
601
+
186
602
  ```typescript
187
- import { SmartProxy } from '@push.rocks/smartproxy';
188
- import { createDomainConfig, httpOnly, tlsTerminateToHttp, httpsPassthrough } from '@push.rocks/smartproxy';
603
+ import { SslRedirect } from '@push.rocks/smartproxy';
189
604
 
190
- const smart = new SmartProxy({
191
- fromPort: 443,
192
- toPort: 8443,
193
- domainConfigs: [
194
- // HTTPS passthrough example
195
- createDomainConfig(['example.com', '*.example.com'],
196
- httpsPassthrough({
197
- target: {
198
- host: '127.0.0.1',
199
- port: 443
200
- },
201
- security: {
202
- allowedIps: ['*']
203
- }
204
- })
205
- ),
206
- // HTTPS termination example
207
- createDomainConfig('secure.example.com',
208
- tlsTerminateToHttp({
209
- target: {
210
- host: 'localhost',
211
- port: 3000
212
- },
213
- acme: {
214
- enabled: true,
215
- production: true
216
- }
217
- })
218
- )
219
- ],
220
- sniEnabled: true
221
- });
222
- smart.on('certificate', evt => console.log(evt));
223
- await smart.start();
224
- // Update domains later
225
- await smart.updateDomainConfigs([/* new configs */]);
605
+ // Quick HTTP→HTTPS helper on port 80
606
+ const redirect = new SslRedirect(80);
607
+ await redirect.start();
226
608
  ```
227
609
 
228
- ### 6. SNI Utilities (SniHandler)
229
- ```js
230
- import { SniHandler } from '@push.rocks/smartproxy';
610
+ ## Migration from v13.x to v14.0.0
231
611
 
232
- // Extract SNI from a TLS ClientHello buffer
233
- const sni = SniHandler.extractSNI(buffer);
612
+ Version 14.0.0 introduces a breaking change with the new route-based configuration system:
234
613
 
235
- // Reassemble fragmented ClientHello
236
- const complete = SniHandler.handleFragmentedClientHello(buf, connId);
237
- ```
614
+ ### Key Changes
238
615
 
239
- ### 7. Core Utilities (ValidationUtils, IpUtils)
240
- ```typescript
241
- import { ValidationUtils, IpUtils } from '@push.rocks/smartproxy';
616
+ 1. **Configuration Structure**: The configuration now uses the match/action pattern instead of the old domain-based and port-based approach
617
+ 2. **SmartProxy Options**: Now takes an array of route configurations instead of `domainConfigs` and port ranges
618
+ 3. **Helper Functions**: New helper functions have been introduced to simplify configuration
242
619
 
243
- // Validate a domain name
244
- const isValidDomain = ValidationUtils.isValidDomainName('example.com');
620
+ ### Migration Example
245
621
 
246
- // Check if an IP is allowed based on filters
247
- const isAllowed = IpUtils.isIPAuthorized(
248
- '192.168.1.1',
249
- ['192.168.1.*'], // allowed IPs
250
- ['192.168.1.100'] // blocked IPs
251
- );
622
+ **v13.x Configuration**:
623
+ ```typescript
624
+ import { SmartProxy, createDomainConfig, httpOnly, tlsTerminateToHttp } from '@push.rocks/smartproxy';
252
625
 
253
- // Convert CIDR to glob patterns
254
- const globPatterns = IpUtils.cidrToGlobPatterns('10.0.0.0/24');
626
+ const proxy = new SmartProxy({
627
+ fromPort: 443,
628
+ domainConfigs: [
629
+ createDomainConfig('example.com', tlsTerminateToHttp({
630
+ target: { host: 'localhost', port: 8080 },
631
+ acme: { enabled: true, production: true }
632
+ }))
633
+ ],
634
+ sniEnabled: true
635
+ });
255
636
  ```
256
637
 
257
- ## API Reference
258
- For full configuration options and type definitions, see the TypeScript interfaces:
259
- - `INetworkProxyOptions` (`ts/proxies/network-proxy/models/types.ts`)
260
- - `IAcmeOptions`, `IDomainOptions` (`ts/certificate/models/certificate-types.ts`)
261
- - `IForwardConfig` (`ts/forwarding/config/forwarding-types.ts`)
262
- - `INfTableProxySettings` (`ts/proxies/nftables-proxy/models/interfaces.ts`)
263
- - `ISmartProxyOptions`, `IDomainConfig` (`ts/proxies/smart-proxy/models/interfaces.ts`)
638
+ **v14.0.0 Configuration**:
639
+ ```typescript
640
+ import { SmartProxy, createHttpsRoute } from '@push.rocks/smartproxy';
641
+
642
+ const proxy = new SmartProxy({
643
+ routes: [
644
+ createHttpsRoute({
645
+ ports: 443,
646
+ domains: 'example.com',
647
+ target: { host: 'localhost', port: 8080 },
648
+ certificate: 'auto'
649
+ })
650
+ ]
651
+ });
652
+ ```
653
+
654
+ ### Migration Steps
655
+
656
+ 1. Replace `domainConfigs` with an array of route configurations using `routes`
657
+ 2. Convert each domain configuration to use the new helper functions
658
+ 3. Update any code that uses `updateDomainConfigs()` to use `addRoutes()` or `updateRoutes()`
659
+ 4. For port-only configurations, create route configurations with port matching only
660
+ 5. For SNI-based routing, SNI is now automatically enabled when needed
264
661
 
265
662
  ## Architecture & Flow Diagrams
266
663
 
@@ -270,11 +667,10 @@ flowchart TB
270
667
 
271
668
  subgraph "SmartProxy Components"
272
669
  direction TB
273
- HTTP80["HTTP Port 80<br>Redirect / SslRedirect"]
670
+ RouteConfig["Route Configuration<br>(Match/Action)"]
671
+ RouteManager["Route Manager"]
274
672
  HTTPS443["HTTPS Port 443<br>NetworkProxy"]
275
673
  SmartProxy["SmartProxy<br>(TCP/SNI Proxy)"]
276
- NfTables[NfTablesProxy]
277
- Router[ProxyRouter]
278
674
  ACME["Port80Handler<br>(ACME HTTP-01)"]
279
675
  Certs[(SSL Certificates)]
280
676
  end
@@ -285,188 +681,110 @@ flowchart TB
285
681
  Service3[Service 3]
286
682
  end
287
683
 
288
- Client -->|HTTP Request| HTTP80
289
- HTTP80 -->|Redirect| Client
290
- Client -->|HTTPS Request| HTTPS443
291
- Client -->|TLS/TCP| SmartProxy
684
+ Client -->|HTTP/HTTPS Request| SmartProxy
292
685
 
293
- HTTPS443 -->|Route Request| Router
294
- Router -->|Proxy Request| Service1
295
- Router -->|Proxy Request| Service2
686
+ SmartProxy -->|Route Matching| RouteManager
687
+ RouteManager -->|Use| RouteConfig
688
+ RouteManager -->|Execute Action| SmartProxy
296
689
 
297
- SmartProxy -->|Direct TCP| Service2
298
- SmartProxy -->|Direct TCP| Service3
690
+ SmartProxy -->|Forward| Service1
691
+ SmartProxy -->|Redirect| Client
692
+ SmartProxy -->|Forward| Service2
693
+ SmartProxy -->|Forward| Service3
299
694
 
300
- NfTables -.->|Low-level forwarding| SmartProxy
301
-
302
- HTTP80 -.->|Challenge Response| ACME
303
695
  ACME -.->|Generate/Manage| Certs
304
- Certs -.->|Provide TLS Certs| HTTPS443
696
+ Certs -.->|Provide TLS Certs| SmartProxy
305
697
 
306
698
  classDef component fill:#f9f,stroke:#333,stroke-width:2px;
307
699
  classDef backend fill:#bbf,stroke:#333,stroke-width:1px;
308
700
  classDef client fill:#dfd,stroke:#333,stroke-width:2px;
309
701
 
310
702
  class Client client;
311
- class HTTP80,HTTPS443,SmartProxy,NfTables,Router,ACME component;
703
+ class RouteConfig,RouteManager,HTTPS443,SmartProxy,ACME component;
312
704
  class Service1,Service2,Service3 backend;
313
705
  ```
314
706
 
315
- ### HTTPS Reverse Proxy Flow
316
- This diagram shows how HTTPS requests are handled and proxied to backend services:
707
+ ### Route-Based Connection Handling
708
+ This diagram illustrates how requests are matched and processed using the route-based configuration:
317
709
 
318
710
  ```mermaid
319
711
  sequenceDiagram
320
712
  participant Client
321
- participant NetworkProxy
322
- participant ProxyRouter
713
+ participant SmartProxy
714
+ participant RouteManager
323
715
  participant Backend
324
716
 
325
- Client->>NetworkProxy: HTTPS Request
326
-
327
- Note over NetworkProxy: TLS Termination
328
-
329
- NetworkProxy->>ProxyRouter: Route Request
330
- ProxyRouter->>ProxyRouter: Match hostname to config
331
-
332
- alt Authentication Required
333
- NetworkProxy->>Client: Request Authentication
334
- Client->>NetworkProxy: Send Credentials
335
- NetworkProxy->>NetworkProxy: Validate Credentials
336
- end
337
-
338
- NetworkProxy->>Backend: Forward Request
339
- Backend->>NetworkProxy: Response
340
-
341
- Note over NetworkProxy: Add Default Headers
717
+ Client->>SmartProxy: Connection (TCP/HTTP/HTTPS)
342
718
 
343
- NetworkProxy->>Client: Forward Response
719
+ SmartProxy->>RouteManager: Match connection against routes
344
720
 
345
- alt WebSocket Request
346
- Client->>NetworkProxy: Upgrade to WebSocket
347
- NetworkProxy->>Backend: Upgrade to WebSocket
348
- loop WebSocket Active
349
- Client->>NetworkProxy: WebSocket Message
350
- NetworkProxy->>Backend: Forward Message
351
- Backend->>NetworkProxy: WebSocket Message
352
- NetworkProxy->>Client: Forward Message
353
- NetworkProxy-->>NetworkProxy: Heartbeat Check
354
- end
355
- end
356
- ```
357
-
358
- ### SNI-based Connection Handling
359
- This diagram illustrates how TCP connections with SNI (Server Name Indication) are processed and forwarded:
360
-
361
- ```mermaid
362
- sequenceDiagram
363
- participant Client
364
- participant SmartProxy
365
- participant Backend
721
+ RouteManager->>RouteManager: Check port match
722
+ RouteManager->>RouteManager: Check domain match (if SNI)
723
+ RouteManager->>RouteManager: Check path match (if HTTP)
724
+ RouteManager->>RouteManager: Check client IP match
725
+ RouteManager->>RouteManager: Check TLS version match
366
726
 
367
- Client->>SmartProxy: TLS Connection
727
+ RouteManager->>RouteManager: Determine highest priority matching route
368
728
 
369
- alt SNI Enabled
370
- SmartProxy->>Client: Accept Connection
371
- Client->>SmartProxy: TLS ClientHello with SNI
372
- SmartProxy->>SmartProxy: Extract SNI Hostname
373
- SmartProxy->>SmartProxy: Match Domain Config
374
- SmartProxy->>SmartProxy: Validate Client IP
729
+ alt Forward Action
730
+ RouteManager->>SmartProxy: Use forward action
375
731
 
376
- alt IP Allowed
377
- SmartProxy->>Backend: Forward Connection
378
- Note over SmartProxy,Backend: Bidirectional Data Flow
379
- else IP Rejected
380
- SmartProxy->>Client: Close Connection
732
+ alt TLS Termination
733
+ SmartProxy->>SmartProxy: Terminate TLS
734
+ SmartProxy->>Backend: Forward as HTTP/HTTPS
735
+ else TLS Passthrough
736
+ SmartProxy->>Backend: Forward raw TCP
381
737
  end
382
- else Port-based Routing
383
- SmartProxy->>SmartProxy: Match Port Range
384
- SmartProxy->>SmartProxy: Find Domain Config
385
- SmartProxy->>SmartProxy: Validate Client IP
386
738
 
387
- alt IP Allowed
388
- SmartProxy->>Backend: Forward Connection
389
- Note over SmartProxy,Backend: Bidirectional Data Flow
390
- else IP Rejected
391
- SmartProxy->>Client: Close Connection
392
- end
739
+ else Redirect Action
740
+ RouteManager->>SmartProxy: Use redirect action
741
+ SmartProxy->>Client: Send redirect response
742
+
743
+ else Block Action
744
+ RouteManager->>SmartProxy: Use block action
745
+ SmartProxy->>Client: Close connection
393
746
  end
394
747
 
395
748
  loop Connection Active
396
749
  SmartProxy-->>SmartProxy: Monitor Activity
397
- SmartProxy-->>SmartProxy: Check Max Lifetime
398
- alt Inactivity or Max Lifetime Exceeded
750
+ SmartProxy-->>SmartProxy: Check Security Rules
751
+ alt Security Violation or Timeout
399
752
  SmartProxy->>Client: Close Connection
400
753
  SmartProxy->>Backend: Close Connection
401
754
  end
402
755
  end
403
756
  ```
404
757
 
405
- ### Let's Encrypt Certificate Acquisition
406
- This diagram shows how certificates are automatically acquired through the ACME protocol:
407
-
408
- ```mermaid
409
- sequenceDiagram
410
- participant Client
411
- participant Port80Handler
412
- participant ACME as Let's Encrypt ACME
413
- participant NetworkProxy
414
-
415
- Client->>Port80Handler: HTTP Request for domain
416
-
417
- alt Certificate Exists
418
- Port80Handler->>Client: Redirect to HTTPS
419
- else No Certificate
420
- Port80Handler->>Port80Handler: Mark domain as obtaining cert
421
- Port80Handler->>ACME: Create account & new order
422
- ACME->>Port80Handler: Challenge information
423
-
424
- Port80Handler->>Port80Handler: Store challenge token & key authorization
425
-
426
- ACME->>Port80Handler: HTTP-01 Challenge Request
427
- Port80Handler->>ACME: Challenge Response
428
-
429
- ACME->>ACME: Validate domain ownership
430
- ACME->>Port80Handler: Challenge validated
431
-
432
- Port80Handler->>Port80Handler: Generate CSR
433
- Port80Handler->>ACME: Submit CSR
434
- ACME->>Port80Handler: Issue Certificate
435
-
436
- Port80Handler->>Port80Handler: Store certificate & private key
437
- Port80Handler->>Port80Handler: Mark certificate as obtained
438
-
439
- Note over Port80Handler,NetworkProxy: Certificate available for use
440
-
441
- Client->>Port80Handler: Another HTTP Request
442
- Port80Handler->>Client: Redirect to HTTPS
443
- Client->>NetworkProxy: HTTPS Request
444
- Note over NetworkProxy: Uses new certificate
445
- end
446
- ```
447
-
448
758
  ## Features
449
759
 
450
- - HTTP/HTTPS Reverse Proxy (NetworkProxy)
451
- TLS termination, virtual-host routing, HTTP/2 & WebSocket support, pooling & metrics
760
+ - **Route-Based Traffic Management**
761
+ Match/action pattern for flexible routing
762
+ • Port, domain, path, client IP, and TLS version matching
763
+ • Multiple action types (forward, redirect, block)
452
764
 
453
- - Automatic ACME Certificates (Port80Handler)
454
- HTTP-01 challenge handling, certificate issuance/renewal, pluggable storage
765
+ - **TLS Handling Options**
766
+ TLS passthrough for end-to-end encryption
767
+ • TLS termination for content inspection
768
+ • TLS termination with re-encryption for gateway scenarios
455
769
 
456
- - Low-Level Port Forwarding (NfTablesProxy)
457
- nftables NAT rules for ports/ranges, IPv4/IPv6, IP filtering, QoS & ipset support
770
+ - **Automatic ACME Certificates**
771
+ HTTP-01 challenge handling
772
+ • Certificate issuance/renewal
773
+ • Pluggable storage
458
774
 
459
- - Custom Redirects (Redirect / SslRedirect)
460
- URL redirects with wildcard host/path, template variables & status codes
775
+ - **Security Controls**
776
+ IP allow/block lists with glob pattern support
777
+ • Connection limits and rate limiting
778
+ • Timeout controls and connection monitoring
461
779
 
462
- - TCP/SNI Proxy (SmartProxy)
463
- SNI-based routing, IP allow/block lists, port ranges, timeouts & graceful shutdown
780
+ - **Load Balancing**
781
+ Round-robin distribution across multiple backends
782
+ • Health checks and failure handling
464
783
 
465
- - SNI Utilities (SniHandler)
466
- Robust ClientHello parsing, fragmentation & session resumption support
467
-
468
- - Core Utilities
469
- • ValidationUtils and IpUtils for configuration validation and IP management
784
+ - **Advanced Features**
785
+ Custom header manipulation
786
+ • Template variables for dynamic values
787
+ • Priority-based route matching
470
788
 
471
789
  ## Certificate Hooks & Events
472
790
 
@@ -479,128 +797,265 @@ Listen for certificate events via EventEmitter:
479
797
 
480
798
  Provide a `certProvisionFunction(domain)` in SmartProxy settings to supply static certs or return `'http01'`.
481
799
 
482
- ## Unified Forwarding System
800
+ ## SmartProxy: Common Use Cases
801
+
802
+ The SmartProxy component with route-based configuration offers a clean, unified approach to handle virtually any proxy scenario.
483
803
 
484
- The SmartProxy Unified Forwarding System provides a clean, use-case driven approach to configuring different types of traffic forwarding. It replaces disparate configuration mechanisms with a unified interface.
804
+ ### 1. API Gateway / Backend Routing
485
805
 
486
- ### Forwarding Types
806
+ Create a flexible API gateway to route traffic to different microservices based on domain and path:
487
807
 
488
- The system supports four primary forwarding types:
808
+ ```typescript
809
+ import { SmartProxy, createHttpsRoute } from '@push.rocks/smartproxy';
810
+
811
+ const apiGateway = new SmartProxy({
812
+ routes: [
813
+ // Users API
814
+ createHttpsRoute({
815
+ ports: 443,
816
+ domains: 'api.example.com',
817
+ path: '/users/*',
818
+ target: { host: 'users-service', port: 3000 },
819
+ certificate: 'auto'
820
+ }),
821
+
822
+ // Products API
823
+ createHttpsRoute({
824
+ ports: 443,
825
+ domains: 'api.example.com',
826
+ path: '/products/*',
827
+ target: { host: 'products-service', port: 3001 },
828
+ certificate: 'auto'
829
+ }),
830
+
831
+ // Admin dashboard with extra security
832
+ createHttpsRoute({
833
+ ports: 443,
834
+ domains: 'admin.example.com',
835
+ target: { host: 'admin-dashboard', port: 8080 },
836
+ certificate: 'auto',
837
+ security: {
838
+ allowedIps: ['10.0.0.*', '192.168.1.*'] // Only allow internal network
839
+ }
840
+ })
841
+ ]
842
+ });
489
843
 
490
- 1. **HTTP-only (`http-only`)**: Forwards HTTP traffic to a backend server.
491
- 2. **HTTPS Passthrough (`https-passthrough`)**: Passes through raw TLS traffic without termination (SNI forwarding).
492
- 3. **HTTPS Termination to HTTP (`https-terminate-to-http`)**: Terminates TLS and forwards the decrypted traffic to an HTTP backend.
493
- 4. **HTTPS Termination to HTTPS (`https-terminate-to-https`)**: Terminates TLS and creates a new TLS connection to an HTTPS backend.
844
+ await apiGateway.start();
845
+ ```
494
846
 
495
- ### Basic Configuration
847
+ ### 2. Complete HTTPS Server with HTTP Redirect
496
848
 
497
- Each domain is configured with a forwarding type and target:
849
+ Easily set up a secure HTTPS server with automatic redirection from HTTP:
498
850
 
499
851
  ```typescript
500
- {
501
- domains: ['example.com'],
502
- forwarding: {
503
- type: 'http-only',
504
- target: {
505
- host: 'localhost',
506
- port: 3000
507
- }
508
- }
509
- }
852
+ import { SmartProxy, createHttpsServer } from '@push.rocks/smartproxy';
853
+
854
+ const webServer = new SmartProxy({
855
+ routes: [
856
+ // createHttpsServer creates both the HTTPS route and HTTP redirect
857
+ ...createHttpsServer({
858
+ domains: 'example.com',
859
+ target: { host: 'localhost', port: 8080 },
860
+ certificate: 'auto',
861
+ addHttpRedirect: true
862
+ })
863
+ ]
864
+ });
865
+
866
+ await webServer.start();
510
867
  ```
511
868
 
512
- ### Helper Functions
869
+ ### 3. Multi-Tenant Application with Wildcard Domains
513
870
 
514
- Helper functions are provided for common configurations:
871
+ Support dynamically created tenants with wildcard domain matching:
515
872
 
516
873
  ```typescript
517
- import { createDomainConfig, httpOnly, tlsTerminateToHttp,
518
- tlsTerminateToHttps, httpsPassthrough } from '@push.rocks/smartproxy';
519
-
520
- // HTTP-only
521
- await domainManager.addDomainConfig(
522
- createDomainConfig('example.com', httpOnly({
523
- target: { host: 'localhost', port: 3000 }
524
- }))
525
- );
526
-
527
- // HTTPS termination to HTTP
528
- await domainManager.addDomainConfig(
529
- createDomainConfig('secure.example.com', tlsTerminateToHttp({
530
- target: { host: 'localhost', port: 3000 },
531
- acme: { production: true }
532
- }))
533
- );
534
-
535
- // HTTPS termination to HTTPS
536
- await domainManager.addDomainConfig(
537
- createDomainConfig('api.example.com', tlsTerminateToHttps({
538
- target: { host: 'internal-api', port: 8443 },
539
- http: { redirectToHttps: true }
540
- }))
541
- );
542
-
543
- // HTTPS passthrough (SNI)
544
- await domainManager.addDomainConfig(
545
- createDomainConfig('passthrough.example.com', httpsPassthrough({
546
- target: { host: '10.0.0.5', port: 443 }
547
- }))
548
- );
874
+ import { SmartProxy, createHttpsRoute, createHttpToHttpsRedirect } from '@push.rocks/smartproxy';
875
+
876
+ const multiTenantApp = new SmartProxy({
877
+ routes: [
878
+ // Handle all tenant subdomains with one route
879
+ createHttpsRoute({
880
+ ports: 443,
881
+ domains: '*.example.com',
882
+ target: { host: 'tenant-router', port: 8080 },
883
+ certificate: 'auto',
884
+ // Pass original hostname to backend for tenant identification
885
+ advanced: {
886
+ headers: {
887
+ 'X-Original-Host': '{sni}'
888
+ }
889
+ }
890
+ }),
891
+
892
+ // Redirect HTTP to HTTPS for all subdomains
893
+ createHttpToHttpsRedirect({
894
+ domains: ['*.example.com']
895
+ })
896
+ ]
897
+ });
898
+
899
+ await multiTenantApp.start();
549
900
  ```
550
901
 
551
- ### Advanced Configuration
902
+ ### 4. Complex Multi-Service Infrastructure
552
903
 
553
- For more complex scenarios, additional options can be specified:
904
+ Create a comprehensive proxy solution with multiple services and security controls:
554
905
 
555
906
  ```typescript
556
- {
557
- domains: ['api.example.com'],
558
- forwarding: {
559
- type: 'https-terminate-to-https',
560
- target: {
561
- host: ['10.0.0.10', '10.0.0.11'], // Round-robin load balancing
562
- port: 8443
563
- },
564
- http: {
565
- enabled: true,
566
- redirectToHttps: true
567
- },
568
- https: {
569
- // Custom certificate instead of ACME-provisioned
570
- customCert: {
571
- key: '-----BEGIN PRIVATE KEY-----\n...',
572
- cert: '-----BEGIN CERTIFICATE-----\n...'
907
+ import {
908
+ SmartProxy,
909
+ createHttpsRoute,
910
+ createPassthroughRoute,
911
+ createBlockRoute,
912
+ createHttpToHttpsRedirect
913
+ } from '@push.rocks/smartproxy';
914
+
915
+ const enterpriseProxy = new SmartProxy({
916
+ routes: [
917
+ // Web application with automatic HTTPS
918
+ createHttpsRoute({
919
+ ports: 443,
920
+ domains: 'app.example.com',
921
+ target: { host: 'web-app', port: 8080 },
922
+ certificate: 'auto'
923
+ }),
924
+
925
+ // Legacy system that needs HTTPS passthrough
926
+ createPassthroughRoute({
927
+ ports: 443,
928
+ domains: 'legacy.example.com',
929
+ target: { host: 'legacy-server', port: 443 }
930
+ }),
931
+
932
+ // Internal APIs with IP restrictions
933
+ createHttpsRoute({
934
+ ports: 443,
935
+ domains: 'api.internal.example.com',
936
+ target: { host: 'api-gateway', port: 3000 },
937
+ certificate: 'auto',
938
+ security: {
939
+ allowedIps: ['10.0.0.0/16', '192.168.0.0/16'],
940
+ maxConnections: 500
573
941
  }
574
- },
942
+ }),
943
+
944
+ // Block known malicious IPs
945
+ createBlockRoute({
946
+ ports: [80, 443],
947
+ clientIp: ['1.2.3.*', '5.6.7.*'],
948
+ priority: 1000
949
+ }),
950
+
951
+ // Redirect all HTTP to HTTPS
952
+ createHttpToHttpsRedirect({
953
+ domains: ['*.example.com', 'example.com']
954
+ })
955
+ ],
956
+
957
+ // Global settings that apply to all routes
958
+ defaults: {
575
959
  security: {
576
- allowedIps: ['10.0.0.*', '192.168.1.*'],
577
- blockedIps: ['1.2.3.4'],
578
- maxConnections: 100
579
- },
580
- advanced: {
581
- timeout: 30000,
582
- headers: {
583
- 'X-Forwarded-For': '{clientIp}',
584
- 'X-Original-Host': '{sni}'
585
- }
960
+ maxConnections: 1000
586
961
  }
962
+ },
963
+
964
+ // Enable connection timeouts for security
965
+ inactivityTimeout: 30000,
966
+
967
+ // Using global certificate management
968
+ acme: {
969
+ enabled: true,
970
+ contactEmail: 'admin@example.com',
971
+ useProduction: true,
972
+ renewThresholdDays: 30
587
973
  }
588
- }
974
+ });
975
+
976
+ await enterpriseProxy.start();
589
977
  ```
590
978
 
591
- ### Extended Configuration Options
979
+ ## Route-Based Configuration Details
980
+
981
+ ### Match Criteria Options
982
+
983
+ - **ports**: `number | number[] | Array<{ from: number; to: number }>` (required)
984
+ Listen on specific ports or port ranges
985
+
986
+ - **domains**: `string | string[]` (optional)
987
+ Match specific domain names, supports wildcards (e.g., `*.example.com`)
988
+
989
+ - **path**: `string` (optional)
990
+ Match specific URL paths, supports glob patterns
991
+
992
+ - **clientIp**: `string[]` (optional)
993
+ Match client IP addresses, supports glob patterns
994
+
995
+ - **tlsVersion**: `string[]` (optional)
996
+ Match specific TLS versions (e.g., `TLSv1.2`, `TLSv1.3`)
997
+
998
+ ### Action Types
999
+
1000
+ 1. **Forward**:
1001
+ ```typescript
1002
+ {
1003
+ type: 'forward',
1004
+ target: { host: 'localhost', port: 8080 },
1005
+ tls: { mode: 'terminate', certificate: 'auto' }
1006
+ }
1007
+ ```
1008
+
1009
+ 2. **Redirect**:
1010
+ ```typescript
1011
+ {
1012
+ type: 'redirect',
1013
+ redirect: { to: 'https://{domain}{path}', status: 301 }
1014
+ }
1015
+ ```
592
1016
 
593
- #### IForwardConfig
594
- - `type`: 'http-only' | 'https-passthrough' | 'https-terminate-to-http' | 'https-terminate-to-https'
595
- - `target`: { host: string | string[], port: number }
596
- - `http?`: { enabled?: boolean, redirectToHttps?: boolean, headers?: Record<string, string> }
597
- - `https?`: { customCert?: { key: string, cert: string }, forwardSni?: boolean }
598
- - `acme?`: { enabled?: boolean, maintenance?: boolean, production?: boolean, forwardChallenges?: { host: string, port: number, useTls?: boolean } }
599
- - `security?`: { allowedIps?: string[], blockedIps?: string[], maxConnections?: number }
600
- - `advanced?`: { portRanges?: Array<{ from: number, to: number }>, networkProxyPort?: number, keepAlive?: boolean, timeout?: number, headers?: Record<string, string> }
1017
+ 3. **Block**:
1018
+ ```typescript
1019
+ {
1020
+ type: 'block'
1021
+ }
1022
+ ```
1023
+
1024
+ ### TLS Modes
1025
+
1026
+ - **passthrough**: Forward raw TLS traffic without decryption
1027
+ - **terminate**: Terminate TLS and forward as HTTP
1028
+ - **terminate-and-reencrypt**: Terminate TLS and create a new TLS connection to the backend
1029
+
1030
+ ### Template Variables
1031
+
1032
+ Template variables can be used in string values:
1033
+
1034
+ - `{domain}`: The requested domain name
1035
+ - `{port}`: The incoming port number
1036
+ - `{path}`: The requested URL path
1037
+ - `{query}`: The query string
1038
+ - `{clientIp}`: The client's IP address
1039
+ - `{sni}`: The SNI hostname
1040
+
1041
+ Example:
1042
+ ```typescript
1043
+ createRedirectRoute({
1044
+ domains: 'old.example.com',
1045
+ redirectTo: 'https://new.example.com{path}?source=redirect'
1046
+ })
1047
+ ```
601
1048
 
602
1049
  ## Configuration Options
603
1050
 
1051
+ ### SmartProxy (IRoutedSmartProxyOptions)
1052
+ - `routes` (IRouteConfig[], required) - Array of route configurations
1053
+ - `defaults` (object) - Default settings for all routes
1054
+ - `acme` (IAcmeOptions) - ACME certificate options
1055
+ - Connection timeouts: `initialDataTimeout`, `socketTimeout`, `inactivityTimeout`, etc.
1056
+ - Socket opts: `noDelay`, `keepAlive`, `enableKeepAliveProbes`
1057
+ - `certProvisionFunction` (callback) - Custom certificate provisioning
1058
+
604
1059
  ### NetworkProxy (INetworkProxyOptions)
605
1060
  - `port` (number, required)
606
1061
  - `backendProtocol` ('http1'|'http2', default 'http1')
@@ -633,25 +1088,22 @@ For more complex scenarios, additional options can be specified:
633
1088
  - `useIPSets` (boolean, default true)
634
1089
  - `qos`, `netProxyIntegration` (objects)
635
1090
 
636
- ### Redirect / SslRedirect
637
- - Constructor options: `httpPort`, `httpsPort`, `sslOptions`, `rules` (IRedirectRule[])
638
-
639
- ### SmartProxy (ISmartProxyOptions)
640
- - `fromPort`, `toPort` (number)
641
- - `domainConfigs` (IDomainConfig[]) - Using unified forwarding configuration
642
- - `sniEnabled`, `preserveSourceIP` (booleans)
643
- - `defaultAllowedIPs`, `defaultBlockedIPs` (string[]) - Default IP allowlists/blocklists
644
- - Timeouts: `initialDataTimeout`, `socketTimeout`, `inactivityTimeout`, etc.
645
- - Socket opts: `noDelay`, `keepAlive`, `enableKeepAliveProbes`
646
- - `acme` (IAcmeOptions), `certProvisionFunction` (callback)
647
- - `useNetworkProxy` (number[]), `networkProxyPort` (number)
648
- - `globalPortRanges` (Array<{ from: number; to: number }>)
649
-
650
1091
  ## Troubleshooting
651
1092
 
1093
+ ### SmartProxy
1094
+ - If routes aren't matching as expected, check their priorities
1095
+ - For domain matching issues, verify SNI extraction is working
1096
+ - Use higher priority for block routes to ensure they take precedence
1097
+ - Enable `enableDetailedLogging` or `enableTlsDebugLogging` for debugging
1098
+
1099
+ ### TLS/Certificates
1100
+ - For certificate issues, check the ACME settings and domain validation
1101
+ - Ensure domains are publicly accessible for Let's Encrypt validation
1102
+ - For TLS handshake issues, increase `initialDataTimeout` and `maxPendingDataSize`
1103
+
652
1104
  ### NetworkProxy
653
1105
  - Verify ports, certificates and `rejectUnauthorized` for TLS errors
654
- - Configure CORS or use `addDefaultHeaders` for preflight issues
1106
+ - Configure CORS for preflight issues
655
1107
  - Increase `maxConnections` or `connectionPoolSize` under load
656
1108
 
657
1109
  ### Port80Handler
@@ -662,18 +1114,6 @@ For more complex scenarios, additional options can be specified:
662
1114
  - Ensure `nft` is installed and run with sufficient privileges
663
1115
  - Use `forceCleanSlate:true` to clear conflicting rules
664
1116
 
665
- ### Redirect / SslRedirect
666
- - Check `fromHost`/`fromPath` patterns and Host headers
667
- - Validate `sslOptions` key/cert correctness
668
-
669
- ### SmartProxy & SniHandler
670
- - Increase `initialDataTimeout`/`maxPendingDataSize` for large ClientHello
671
- - Enable `enableTlsDebugLogging` to trace handshake
672
- - Ensure `allowSessionTicket` and fragmentation support for resumption
673
- - Double-check forwarding configuration to ensure correct `type` for your use case
674
- - Use helper functions like `httpOnly()`, `httpsPassthrough()`, etc. to create correct configurations
675
- - For IP filtering issues, check the `security.allowedIps` and `security.blockedIps` settings
676
-
677
1117
  ## License and Legal Information
678
1118
 
679
1119
  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.