@push.rocks/smartproxy 7.2.0 → 10.0.1

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 (41) hide show
  1. package/dist_ts/00_commitinfo_data.js +2 -2
  2. package/dist_ts/classes.router.d.ts +9 -10
  3. package/dist_ts/classes.router.js +3 -5
  4. package/dist_ts/common/acmeFactory.d.ts +9 -0
  5. package/dist_ts/common/acmeFactory.js +20 -0
  6. package/dist_ts/common/eventUtils.d.ts +15 -0
  7. package/dist_ts/common/eventUtils.js +19 -0
  8. package/dist_ts/common/types.d.ts +82 -0
  9. package/dist_ts/common/types.js +17 -0
  10. package/dist_ts/networkproxy/classes.np.certificatemanager.js +23 -19
  11. package/dist_ts/networkproxy/classes.np.types.d.ts +5 -10
  12. package/dist_ts/networkproxy/classes.np.types.js +1 -1
  13. package/dist_ts/plugins.d.ts +2 -1
  14. package/dist_ts/plugins.js +3 -2
  15. package/dist_ts/port80handler/classes.port80handler.d.ts +8 -91
  16. package/dist_ts/port80handler/classes.port80handler.js +34 -222
  17. package/dist_ts/smartproxy/classes.pp.certprovisioner.d.ts +54 -0
  18. package/dist_ts/smartproxy/classes.pp.certprovisioner.js +166 -0
  19. package/dist_ts/smartproxy/classes.pp.interfaces.d.ts +2 -33
  20. package/dist_ts/smartproxy/classes.pp.networkproxybridge.d.ts +2 -1
  21. package/dist_ts/smartproxy/classes.pp.networkproxybridge.js +11 -11
  22. package/dist_ts/smartproxy/classes.pp.portrangemanager.js +1 -11
  23. package/dist_ts/smartproxy/classes.smartproxy.d.ts +1 -4
  24. package/dist_ts/smartproxy/classes.smartproxy.js +62 -213
  25. package/package.json +2 -1
  26. package/readme.md +254 -453
  27. package/readme.plan.md +27 -29
  28. package/ts/00_commitinfo_data.ts +1 -1
  29. package/ts/classes.router.ts +13 -15
  30. package/ts/common/acmeFactory.ts +23 -0
  31. package/ts/common/eventUtils.ts +34 -0
  32. package/ts/common/types.ts +89 -0
  33. package/ts/networkproxy/classes.np.certificatemanager.ts +23 -19
  34. package/ts/networkproxy/classes.np.types.ts +6 -10
  35. package/ts/plugins.ts +13 -2
  36. package/ts/port80handler/classes.port80handler.ts +44 -310
  37. package/ts/smartproxy/classes.pp.certprovisioner.ts +188 -0
  38. package/ts/smartproxy/classes.pp.interfaces.ts +3 -36
  39. package/ts/smartproxy/classes.pp.networkproxybridge.ts +11 -10
  40. package/ts/smartproxy/classes.pp.portrangemanager.ts +0 -10
  41. package/ts/smartproxy/classes.smartproxy.ts +73 -222
package/readme.md CHANGED
@@ -1,11 +1,178 @@
1
1
  # @push.rocks/smartproxy
2
2
 
3
- A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.
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
+
10
+ ## Exports
11
+ The following classes and interfaces are provided:
12
+
13
+ - **NetworkProxy** (ts/networkproxy/classes.np.networkproxy.ts)
14
+ HTTP/HTTPS reverse proxy with TLS termination, WebSocket support,
15
+ connection pooling, and optional ACME integration.
16
+ - **Port80Handler** (ts/port80handler/classes.port80handler.ts)
17
+ ACME HTTP-01 challenge handler and certificate manager.
18
+ - **NfTablesProxy** (ts/nfttablesproxy/classes.nftablesproxy.ts)
19
+ Low-level port forwarding using nftables NAT rules.
20
+ - **Redirect**, **SslRedirect** (ts/redirect/classes.redirect.ts)
21
+ HTTP/HTTPS redirect server and shortcut for HTTP→HTTPS.
22
+ - **SmartProxy** (ts/smartproxy/classes.smartproxy.ts)
23
+ TCP/SNI-based proxy with dynamic routing, IP filtering, and unified certificates.
24
+ - **SniHandler** (ts/smartproxy/classes.pp.snihandler.ts)
25
+ Static utilities to extract SNI hostnames from TLS handshakes.
26
+ - **Interfaces**
27
+ - IPortProxySettings, IDomainConfig (ts/smartproxy/classes.pp.interfaces.ts)
28
+ - INetworkProxyOptions (ts/networkproxy/classes.np.types.ts)
29
+ - IAcmeOptions, IDomainOptions, IForwardConfig (ts/common/types.ts)
30
+ - INfTableProxySettings (ts/nfttablesproxy/classes.nftablesproxy.ts)
31
+
32
+ ## Installation
33
+ Install via npm:
34
+ ```bash
35
+ npm install @push.rocks/smartproxy
36
+ ```
37
+
38
+ ## Quick Start
39
+
40
+ ### 1. HTTP(S) Reverse Proxy (NetworkProxy)
41
+ ```typescript
42
+ import { NetworkProxy } from '@push.rocks/smartproxy';
43
+
44
+ const proxy = new NetworkProxy({ port: 443 });
45
+ await proxy.start();
46
+
47
+ await proxy.updateProxyConfigs([
48
+ {
49
+ hostName: 'example.com',
50
+ destinationIps: ['127.0.0.1'],
51
+ destinationPorts: [3000],
52
+ publicKey: fs.readFileSync('cert.pem', 'utf8'),
53
+ privateKey: fs.readFileSync('key.pem', 'utf8'),
54
+ }
55
+ ]);
56
+
57
+ // Add default headers to all responses
58
+ await proxy.addDefaultHeaders({
59
+ 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains'
60
+ });
61
+ // ...
62
+ await proxy.stop();
63
+ ```
64
+
65
+ ### 2. HTTP→HTTPS Redirect (Redirect / SslRedirect)
66
+ ```typescript
67
+ import { Redirect, SslRedirect } from '@push.rocks/smartproxy';
68
+ import * as fs from 'fs';
69
+
70
+ // Custom redirect rules
71
+ const redirect = new Redirect({
72
+ httpPort: 80,
73
+ httpsPort: 443,
74
+ sslOptions: {
75
+ key: fs.readFileSync('key.pem'),
76
+ cert: fs.readFileSync('cert.pem'),
77
+ },
78
+ rules: [
79
+ {
80
+ fromProtocol: 'http',
81
+ fromHost: '*',
82
+ toProtocol: 'https',
83
+ toHost: '$1',
84
+ statusCode: 301
85
+ }
86
+ ]
87
+ });
88
+ await redirect.start();
89
+
90
+ // Quick HTTP→HTTPS helper on port 80
91
+ const quick = new SslRedirect(80);
92
+ await quick.start();
93
+ ```
94
+
95
+ ### 3. Automatic Certificates (ACME Port80Handler)
96
+ ```typescript
97
+ import { Port80Handler } from '@push.rocks/smartproxy';
98
+
99
+ // Configure ACME on port 80 with contact email
100
+ const acme = new Port80Handler({
101
+ port: 80,
102
+ contactEmail: 'admin@example.com',
103
+ useProduction: true,
104
+ renewThresholdDays: 30
105
+ });
106
+ acme.on('certificate-issued', evt => {
107
+ console.log(`Certificate ready for ${evt.domain}, expires ${evt.expiryDate}`);
108
+ });
109
+ await acme.start();
110
+ acme.addDomain({
111
+ domainName: 'example.com',
112
+ sslRedirect: true,
113
+ acmeMaintenance: true
114
+ });
115
+ ```
116
+
117
+ ### 4. Low-Level Port Forwarding (NfTablesProxy)
118
+ ```typescript
119
+ import { NfTablesProxy } from '@push.rocks/smartproxy';
120
+
121
+ // Forward port 80→8080 with source IP preservation
122
+ const nft = new NfTablesProxy({
123
+ fromPort: 80,
124
+ toPort: 8080,
125
+ toHost: 'localhost',
126
+ preserveSourceIP: true,
127
+ deleteOnExit: true
128
+ });
129
+ await nft.start();
130
+ // ...
131
+ await nft.stop();
132
+ ```
133
+
134
+ ### 5. TCP/SNI Proxy (SmartProxy)
135
+ ```typescript
136
+ import { SmartProxy } from '@push.rocks/smartproxy';
137
+
138
+ const smart = new SmartProxy({
139
+ fromPort: 443,
140
+ toPort: 8443,
141
+ domainConfigs: [
142
+ {
143
+ domains: ['example.com', '*.example.com'],
144
+ allowedIPs: ['*'],
145
+ targetIPs: ['127.0.0.1'],
146
+ }
147
+ ],
148
+ sniEnabled: true
149
+ });
150
+ smart.on('certificate', evt => console.log(evt));
151
+ await smart.start();
152
+ // Update domains later
153
+ await smart.updateDomainConfigs([/* new configs */]);
154
+ ```
155
+
156
+ ### 6. SNI Utilities (SniHandler)
157
+ ```js
158
+ import { SniHandler } from '@push.rocks/smartproxy';
159
+
160
+ // Extract SNI from a TLS ClientHello buffer
161
+ const sni = SniHandler.extractSNI(buffer);
162
+
163
+ // Reassemble fragmented ClientHello
164
+ const complete = SniHandler.handleFragmentedClientHello(buf, connId);
165
+ ```
166
+
167
+ ## API Reference
168
+ For full configuration options and type definitions, see the TypeScript interfaces in the `ts/` directory:
169
+ - `INetworkProxyOptions` (ts/networkproxy/classes.np.types.ts)
170
+ - `IAcmeOptions`, `IDomainOptions`, `IForwardConfig` (ts/common/types.ts)
171
+ - `INfTableProxySettings` (ts/nfttablesproxy/classes.nftablesproxy.ts)
172
+ - `IPortProxySettings`, `IDomainConfig` (ts/smartproxy/classes.pp.interfaces.ts)
4
173
 
5
174
  ## Architecture & Flow Diagrams
6
175
 
7
- ### Component Architecture
8
- The diagram below illustrates the main components of SmartProxy and how they interact:
9
176
 
10
177
  ```mermaid
11
178
  flowchart TB
@@ -13,12 +180,12 @@ flowchart TB
13
180
 
14
181
  subgraph "SmartProxy Components"
15
182
  direction TB
16
- HTTP80[HTTP Port 80\nSslRedirect]
17
- HTTPS443[HTTPS Port 443\nNetworkProxy]
18
- SmartProxy[SmartProxy\nwith SNI routing]
183
+ HTTP80["HTTP Port 80<br>Redirect / SslRedirect"]
184
+ HTTPS443["HTTPS Port 443<br>NetworkProxy"]
185
+ SmartProxy["SmartProxy<br>(TCP/SNI Proxy)"]
19
186
  NfTables[NfTablesProxy]
20
187
  Router[ProxyRouter]
21
- ACME[Port80Handler\nACME/Let's Encrypt]
188
+ ACME["Port80Handler<br>(ACME HTTP-01)"]
22
189
  Certs[(SSL Certificates)]
23
190
  end
24
191
 
@@ -190,470 +357,104 @@ sequenceDiagram
190
357
 
191
358
  ## Features
192
359
 
193
- - **HTTPS Reverse Proxy** - Route traffic to backend services based on hostname with TLS termination
194
- - **WebSocket Support** - Full WebSocket proxying with heartbeat monitoring
195
- - **TCP Connection Handling** - Advanced connection handling with SNI inspection and domain-based routing
196
- - **Enhanced TLS Handling** - Robust TLS handshake processing with improved certificate error handling
197
- - **HTTP to HTTPS Redirection** - Automatically redirect HTTP requests to HTTPS
198
- - **Let's Encrypt Integration** - Automatic certificate management using ACME protocol
199
- - **IP Filtering** - Control access with IP allow/block lists using glob patterns
200
- - **NfTables Integration** - Direct manipulation of nftables for advanced low-level port forwarding
360
+ - HTTP/HTTPS Reverse Proxy (NetworkProxy)
361
+ TLS termination, virtual-host routing, HTTP/2 & WebSocket support, pooling & metrics
201
362
 
202
- ## Certificate Provider Hook & Events
363
+ - Automatic ACME Certificates (Port80Handler)
364
+ • HTTP-01 challenge handling, certificate issuance/renewal, pluggable storage
203
365
 
204
- You can customize how certificates are provisioned per domain by using the `certProvider` callback and listen for certificate events emitted by `SmartProxy`.
366
+ - Low-Level Port Forwarding (NfTablesProxy)
367
+ • nftables NAT rules for ports/ranges, IPv4/IPv6, IP filtering, QoS & ipset support
205
368
 
206
- ```typescript
207
- import { SmartProxy } from '@push.rocks/smartproxy';
208
- import * as fs from 'fs';
369
+ - Custom Redirects (Redirect / SslRedirect)
370
+ URL redirects with wildcard host/path, template variables & status codes
209
371
 
210
- // Example certProvider: static for a specific domain, HTTP-01 otherwise
211
- const certProvider = async (domain: string) => {
212
- if (domain === 'static.example.com') {
213
- // Load from disk or vault
214
- return {
215
- id: 'static-cert',
216
- domainName: domain,
217
- created: Date.now(),
218
- validUntil: Date.now() + 90 * 24 * 60 * 60 * 1000,
219
- privateKey: fs.readFileSync('/etc/ssl/private/static.key', 'utf8'),
220
- publicKey: fs.readFileSync('/etc/ssl/certs/static.crt', 'utf8'),
221
- csr: ''
222
- };
223
- }
224
- // Fallback to ACME HTTP-01 challenge
225
- return 'http01';
226
- };
372
+ - TCP/SNI Proxy (SmartProxy)
373
+ SNI-based routing, IP allow/block lists, port ranges, timeouts & graceful shutdown
227
374
 
228
- const proxy = new SmartProxy({
229
- fromPort: 80,
230
- toPort: 8080,
231
- domainConfigs: [{
232
- domains: ['static.example.com', 'dynamic.example.com'],
233
- allowedIPs: ['*']
234
- }],
235
- certProvider
236
- });
375
+ - SNI Utilities (SniHandler)
376
+ Robust ClientHello parsing, fragmentation & session resumption support
237
377
 
238
- // Listen for certificate issuance or renewal
239
- proxy.on('certificate', (evt) => {
240
- console.log(`Certificate for ${evt.domain} ready, expires on ${evt.expiryDate}`);
241
- });
242
-
243
- await proxy.start();
244
- ```
245
-
246
- ## Configuration Options
247
-
248
- ### backendProtocol
378
+ ## Certificate Hooks & Events
249
379
 
250
- Type: 'http1' | 'http2' (default: 'http1')
380
+ Listen for certificate events via EventEmitter:
381
+ - **Port80Handler**:
382
+ - `certificate-issued`, `certificate-renewed`, `certificate-failed`
383
+ - `manager-started`, `manager-stopped`, `request-forwarded`
384
+ - **SmartProxy**:
385
+ - `certificate` (domain, publicKey, privateKey, expiryDate, source, isRenewal)
251
386
 
252
- Controls the protocol used when proxying requests to backend services. By default, the proxy uses HTTP/1.x (`http.request`). Setting `backendProtocol: 'http2'` establishes HTTP/2 client sessions (`http2.connect`) to your backends for full end-to-end HTTP/2 support (assuming your backend servers support HTTP/2).
253
-
254
- Example:
255
- ```js
256
- import { NetworkProxy } from '@push.rocks/smartproxy';
257
-
258
- const proxy = new NetworkProxy({
259
- port: 8443,
260
- backendProtocol: 'http2',
261
- // other options...
262
- });
263
- proxy.start();
264
- ```
265
- - **Basic Authentication** - Support for basic auth on proxied routes
266
- - **Connection Management** - Intelligent connection tracking and cleanup with configurable timeouts
267
- - **Browser Compatibility** - Optimized for modern browsers with fixes for common TLS handshake issues
268
-
269
- ## Installation
270
-
271
- ```bash
272
- npm install @push.rocks/smartproxy
273
- ```
274
-
275
- ## Usage
276
-
277
- ### Basic Reverse Proxy Setup
278
-
279
- ```typescript
280
- import { NetworkProxy } from '@push.rocks/smartproxy';
281
-
282
- // Create a reverse proxy listening on port 443
283
- const proxy = new NetworkProxy({
284
- port: 443
285
- });
286
-
287
- // Define reverse proxy configurations
288
- const proxyConfigs = [
289
- {
290
- hostName: 'example.com',
291
- destinationIps: ['127.0.0.1'],
292
- destinationPorts: [3000],
293
- publicKey: 'your-cert-content',
294
- privateKey: 'your-key-content',
295
- rewriteHostHeader: true
296
- },
297
- {
298
- hostName: 'api.example.com',
299
- destinationIps: ['127.0.0.1'],
300
- destinationPorts: [4000],
301
- publicKey: 'your-cert-content',
302
- privateKey: 'your-key-content',
303
- // Optional basic auth
304
- authentication: {
305
- type: 'Basic',
306
- user: 'admin',
307
- pass: 'secret'
308
- }
309
- }
310
- ];
311
-
312
- // Start the proxy and update configurations
313
- (async () => {
314
- await proxy.start();
315
- await proxy.updateProxyConfigs(proxyConfigs);
316
-
317
- // Add default headers to all responses
318
- await proxy.addDefaultHeaders({
319
- 'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload'
320
- });
321
- })();
322
- ```
323
-
324
- ### HTTP to HTTPS Redirection
325
-
326
- ```typescript
327
- import { SslRedirect } from '@push.rocks/smartproxy';
328
-
329
- // Create and start HTTP to HTTPS redirect service on port 80
330
- const redirector = new SslRedirect(80);
331
- redirector.start();
332
- ```
333
-
334
- ### TCP Connection Handling with Domain-based Routing
335
-
336
- ```typescript
337
- import { SmartProxy } from '@push.rocks/smartproxy';
338
-
339
- // Configure SmartProxy with domain-based routing
340
- const smartProxy = new SmartProxy({
341
- fromPort: 443,
342
- toPort: 8443,
343
- targetIP: 'localhost', // Default target host
344
- sniEnabled: true, // Enable SNI inspection
345
-
346
- // Enhanced reliability settings
347
- initialDataTimeout: 60000, // 60 seconds for initial TLS handshake
348
- socketTimeout: 3600000, // 1 hour socket timeout
349
- maxConnectionLifetime: 3600000, // 1 hour connection lifetime
350
- inactivityTimeout: 3600000, // 1 hour inactivity timeout
351
- maxPendingDataSize: 10 * 1024 * 1024, // 10MB buffer for large TLS handshakes
352
-
353
- // Browser compatibility enhancement
354
- enableTlsDebugLogging: false, // Enable for troubleshooting TLS issues
355
-
356
- // Port and IP configuration
357
- globalPortRanges: [{ from: 443, to: 443 }],
358
- defaultAllowedIPs: ['*'], // Allow all IPs by default
359
-
360
- // Socket optimizations for better connection stability
361
- noDelay: true, // Disable Nagle's algorithm
362
- keepAlive: true, // Enable TCP keepalive
363
- enableKeepAliveProbes: true, // Enhanced keepalive for stability
364
-
365
- // Domain-specific routing configuration
366
- domainConfigs: [
367
- {
368
- domains: ['example.com', '*.example.com'], // Glob patterns for matching domains
369
- allowedIPs: ['192.168.1.*'], // Restrict access by IP
370
- blockedIPs: ['192.168.1.100'], // Block specific IPs
371
- targetIPs: ['10.0.0.1', '10.0.0.2'], // Round-robin between multiple targets
372
- portRanges: [{ from: 443, to: 443 }],
373
- connectionTimeout: 7200000 // Domain-specific timeout (2 hours)
374
- }
375
- ],
376
-
377
- preserveSourceIP: true
378
- });
379
-
380
- smartProxy.start();
381
- ```
382
-
383
- ### NfTables Port Forwarding
384
-
385
- ```typescript
386
- import { NfTablesProxy } from '@push.rocks/smartproxy';
387
-
388
- // Basic usage - forward single port
389
- const basicProxy = new NfTablesProxy({
390
- fromPort: 80,
391
- toPort: 8080,
392
- toHost: 'localhost',
393
- preserveSourceIP: true,
394
- deleteOnExit: true // Automatically clean up rules on process exit
395
- });
396
-
397
- // Forward port ranges
398
- const rangeProxy = new NfTablesProxy({
399
- fromPort: { from: 3000, to: 3010 }, // Forward ports 3000-3010
400
- toPort: { from: 8000, to: 8010 }, // To ports 8000-8010
401
- protocol: 'tcp', // TCP protocol (default)
402
- ipv6Support: true, // Enable IPv6 support
403
- enableLogging: true // Enable detailed logging
404
- });
405
-
406
- // Multiple port specifications with IP filtering
407
- const advancedProxy = new NfTablesProxy({
408
- fromPort: [80, 443, { from: 8000, to: 8010 }], // Multiple ports/ranges
409
- toPort: [8080, 8443, { from: 18000, to: 18010 }],
410
- allowedSourceIPs: ['10.0.0.0/8', '192.168.1.0/24'], // Only allow these IPs
411
- bannedSourceIPs: ['192.168.1.100'], // Explicitly block these IPs
412
- useIPSets: true, // Use IP sets for efficient IP management
413
- forceCleanSlate: false // Clean all NfTablesProxy rules before starting
414
- });
415
-
416
- // Advanced features: QoS, connection tracking, and NetworkProxy integration
417
- const advancedProxy = new NfTablesProxy({
418
- fromPort: 443,
419
- toPort: 8443,
420
- toHost: 'localhost',
421
- useAdvancedNAT: true, // Use connection tracking for stateful NAT
422
- qos: {
423
- enabled: true,
424
- maxRate: '10mbps', // Limit bandwidth
425
- priority: 1 // Set traffic priority (1-10)
426
- },
427
- netProxyIntegration: {
428
- enabled: true,
429
- redirectLocalhost: true, // Redirect localhost traffic to NetworkProxy
430
- sslTerminationPort: 8443 // Port where NetworkProxy handles SSL
431
- }
432
- });
433
-
434
- // Start any of the proxies
435
- await basicProxy.start();
436
- ```
437
-
438
- ### Automatic HTTPS Certificate Management
439
-
440
- ```typescript
441
- import { Port80Handler } from '@push.rocks/smartproxy';
442
-
443
- // Create an ACME handler for Let's Encrypt
444
- const acmeHandler = new Port80Handler({
445
- port: 80,
446
- contactEmail: 'admin@example.com',
447
- useProduction: true, // Use Let's Encrypt production servers (default is staging)
448
- renewThresholdDays: 30, // Renew certificates 30 days before expiry
449
- httpsRedirectPort: 443 // Redirect HTTP to HTTPS on this port
450
- });
451
-
452
- // Add domains to manage certificates for
453
- acmeHandler.addDomain({
454
- domainName: 'example.com',
455
- sslRedirect: true,
456
- acmeMaintenance: true
457
- });
458
-
459
- acmeHandler.addDomain({
460
- domainName: 'api.example.com',
461
- sslRedirect: true,
462
- acmeMaintenance: true
463
- });
464
-
465
- // Support for glob pattern domains for routing (certificates not issued for glob patterns)
466
- acmeHandler.addDomain({
467
- domainName: '*.example.com',
468
- sslRedirect: true,
469
- acmeMaintenance: false, // Can't issue certificates for wildcard domains via HTTP-01
470
- forward: { ip: '192.168.1.10', port: 8080 } // Forward requests to this target
471
- });
472
- ```
387
+ Provide a `certProvider(domain)` in SmartProxy settings to supply static certs or return `'http01'`.
473
388
 
474
389
  ## Configuration Options
475
390
 
476
- ### NetworkProxy Options
477
-
478
- | Option | Description | Default |
479
- |----------------|---------------------------------------------------|---------|
480
- | `port` | Port to listen on for HTTPS connections | - |
481
- | `maxConnections` | Maximum concurrent connections | 10000 |
482
- | `keepAliveTimeout` | Keep-alive timeout in milliseconds | 60000 |
483
- | `headersTimeout` | Headers timeout in milliseconds | 60000 |
484
- | `logLevel` | Logging level ('error', 'warn', 'info', 'debug') | 'info' |
485
- | `cors` | CORS configuration object | - |
486
- | `rewriteHostHeader` | Whether to rewrite the Host header | false |
487
-
488
- ### SmartProxy Settings
489
-
490
- | Option | Description | Default |
491
- |---------------------------|--------------------------------------------------------|-------------|
492
- | `fromPort` | Port to listen on | - |
493
- | `toPort` | Destination port to forward to | - |
494
- | `targetIP` | Default destination IP if not specified in domainConfig | 'localhost' |
495
- | `sniEnabled` | Enable SNI inspection for TLS connections | false |
496
- | `defaultAllowedIPs` | IP patterns allowed by default | - |
497
- | `defaultBlockedIPs` | IP patterns blocked by default | - |
498
- | `preserveSourceIP` | Preserve the original client IP | false |
499
- | `maxConnectionLifetime` | Maximum time in ms to keep a connection open | 3600000 |
500
- | `initialDataTimeout` | Timeout for initial data/handshake in ms | 60000 |
501
- | `socketTimeout` | Socket inactivity timeout in ms | 3600000 |
502
- | `inactivityTimeout` | Connection inactivity check timeout in ms | 3600000 |
503
- | `inactivityCheckInterval` | How often to check for inactive connections in ms | 60000 |
504
- | `maxPendingDataSize` | Maximum bytes to buffer during connection setup | 10485760 |
505
- | `globalPortRanges` | Array of port ranges to listen on | - |
506
- | `forwardAllGlobalRanges` | Forward all global range connections to targetIP | false |
507
- | `gracefulShutdownTimeout` | Time in ms to wait during shutdown | 30000 |
508
- | `noDelay` | Disable Nagle's algorithm | true |
509
- | `keepAlive` | Enable TCP keepalive | true |
510
- | `keepAliveInitialDelay` | Initial delay before sending keepalive probes in ms | 30000 |
511
- | `enableKeepAliveProbes` | Enable enhanced TCP keep-alive probes | false |
512
- | `enableTlsDebugLogging` | Enable detailed TLS handshake debugging | false |
513
- | `enableDetailedLogging` | Enable detailed connection logging | false |
514
- | `enableRandomizedTimeouts`| Randomize timeouts slightly to prevent thundering herd | true |
515
-
516
- ### NfTablesProxy Settings
517
-
518
- | Option | Description | Default |
519
- |-----------------------|---------------------------------------------------|-------------|
520
- | `fromPort` | Source port(s) or range(s) to forward from | - |
521
- | `toPort` | Destination port(s) or range(s) to forward to | - |
522
- | `toHost` | Destination host to forward to | 'localhost' |
523
- | `preserveSourceIP` | Preserve the original client IP | false |
524
- | `deleteOnExit` | Remove nftables rules when process exits | false |
525
- | `protocol` | Protocol to forward ('tcp', 'udp', or 'all') | 'tcp' |
526
- | `enableLogging` | Enable detailed logging | false |
527
- | `logFormat` | Format for logs ('plain' or 'json') | 'plain' |
528
- | `ipv6Support` | Enable IPv6 support | false |
529
- | `allowedSourceIPs` | Array of IP addresses/CIDR allowed to connect | - |
530
- | `bannedSourceIPs` | Array of IP addresses/CIDR blocked from connecting | - |
531
- | `useIPSets` | Use nftables sets for efficient IP management | true |
532
- | `forceCleanSlate` | Clear all NfTablesProxy rules before starting | false |
533
- | `tableName` | Custom table name | 'portproxy' |
534
- | `maxRetries` | Maximum number of retries for failed commands | 3 |
535
- | `retryDelayMs` | Delay between retries in milliseconds | 1000 |
536
- | `useAdvancedNAT` | Use connection tracking for stateful NAT | false |
537
- | `qos` | Quality of Service options (object) | - |
538
- | `netProxyIntegration` | NetworkProxy integration options (object) | - |
539
-
540
- ## Advanced Features
541
-
542
- ### TLS Handshake Optimization
543
-
544
- The enhanced `SmartProxy` implementation includes significant improvements for TLS handshake handling:
545
-
546
- - Robust SNI extraction with improved error handling
547
- - Increased buffer size for complex TLS handshakes (10MB)
548
- - Longer initial handshake timeout (60 seconds)
549
- - Detection and tracking of TLS connection states
550
- - Optional detailed TLS debug logging for troubleshooting
551
- - Browser compatibility fixes for Chrome certificate errors
552
-
553
- ```typescript
554
- // Example configuration to solve Chrome certificate errors
555
- const portProxy = new SmartProxy({
556
- // ... other settings
557
- initialDataTimeout: 60000, // Give browser more time for handshake
558
- maxPendingDataSize: 10 * 1024 * 1024, // Larger buffer for complex handshakes
559
- enableTlsDebugLogging: true, // Enable when troubleshooting
560
- });
561
- ```
562
-
563
- ### Connection Management and Monitoring
564
-
565
- The `SmartProxy` class includes built-in connection tracking and monitoring:
566
-
567
- - Automatic cleanup of idle connections with configurable timeouts
568
- - Timeouts for connections that exceed maximum lifetime
569
- - Detailed logging of connection states
570
- - Termination statistics
571
- - Randomized timeouts to prevent "thundering herd" problems
572
- - Per-domain timeout configuration
573
-
574
- ### WebSocket Support
575
-
576
- The `NetworkProxy` class provides WebSocket support with:
577
-
578
- - WebSocket connection proxying
579
- - Automatic heartbeat monitoring
580
- - Connection cleanup for inactive WebSockets
581
-
582
- ### SNI-based Routing
583
-
584
- The `SmartProxy` class can inspect the SNI (Server Name Indication) field in TLS handshakes to route connections based on the requested domain:
585
-
586
- - Multiple backend targets per domain
587
- - Round-robin load balancing
588
- - Domain-specific allowed IP ranges
589
- - Protection against SNI renegotiation attacks
590
-
591
- ### Enhanced NfTables Management
592
-
593
- The `NfTablesProxy` class offers advanced capabilities:
594
-
595
- - Support for multiple port ranges and individual ports
596
- - More efficient IP filtering using nftables sets
597
- - IPv6 support with full feature parity
598
- - Quality of Service (QoS) features including bandwidth limiting and traffic prioritization
599
- - Advanced connection tracking for stateful NAT
600
- - Robust error handling with retry mechanisms
601
- - Structured logging with JSON support
602
- - NetworkProxy integration for SSL termination
603
- - Comprehensive cleanup on shutdown
604
-
605
- ### Port80Handler with Glob Pattern Support
606
-
607
- The `Port80Handler` class includes support for glob pattern domain matching:
608
-
609
- - Supports wildcard domains like `*.example.com` for HTTP request routing
610
- - Detects glob patterns and skips certificate issuance for them
611
- - Smart routing that first attempts exact matches, then tries pattern matching
612
- - Supports forwarding HTTP requests to backend services
613
- - Separate forwarding configuration for ACME challenges
391
+ ### NetworkProxy (INetworkProxyOptions)
392
+ - `port` (number, required)
393
+ - `backendProtocol` ('http1'|'http2', default 'http1')
394
+ - `maxConnections` (number, default 10000)
395
+ - `keepAliveTimeout` (ms, default 120000)
396
+ - `headersTimeout` (ms, default 60000)
397
+ - `cors` (object)
398
+ - `connectionPoolSize` (number, default 50)
399
+ - `logLevel` ('error'|'warn'|'info'|'debug')
400
+ - `acme` (IAcmeOptions)
401
+ - `useExternalPort80Handler` (boolean)
402
+ - `portProxyIntegration` (boolean)
403
+
404
+ ### Port80Handler (IAcmeOptions)
405
+ - `enabled` (boolean, default true)
406
+ - `port` (number, default 80)
407
+ - `contactEmail` (string)
408
+ - `useProduction` (boolean, default false)
409
+ - `renewThresholdDays` (number, default 30)
410
+ - `autoRenew` (boolean, default true)
411
+ - `certificateStore` (string)
412
+ - `skipConfiguredCerts` (boolean)
413
+ - `domainForwards` (IDomainForwardConfig[])
414
+
415
+ ### NfTablesProxy (INfTableProxySettings)
416
+ - `fromPort` / `toPort` (number|range|array)
417
+ - `toHost` (string, default 'localhost')
418
+ - `preserveSourceIP`, `deleteOnExit`, `protocol`, `enableLogging`, `ipv6Support` (booleans)
419
+ - `allowedSourceIPs`, `bannedSourceIPs` (string[])
420
+ - `useIPSets` (boolean, default true)
421
+ - `qos`, `netProxyIntegration` (objects)
422
+
423
+ ### Redirect / SslRedirect
424
+ - Constructor options: `httpPort`, `httpsPort`, `sslOptions`, `rules` (RedirectRule[])
425
+
426
+ ### SmartProxy (IPortProxySettings)
427
+ - `fromPort`, `toPort` (number)
428
+ - `domainConfigs` (IDomainConfig[])
429
+ - `sniEnabled`, `defaultAllowedIPs`, `preserveSourceIP` (booleans)
430
+ - Timeouts: `initialDataTimeout`, `socketTimeout`, `inactivityTimeout`, etc.
431
+ - Socket opts: `noDelay`, `keepAlive`, `enableKeepAliveProbes`
432
+ - `acme` (IAcmeOptions), `certProvider` (callback)
433
+ - `useNetworkProxy` (number[]), `networkProxyPort` (number)
614
434
 
615
435
  ## Troubleshooting
616
436
 
617
- ### Browser Certificate Errors
618
-
619
- If you experience certificate errors in browsers, especially in Chrome, try these solutions:
620
-
621
- 1. **Increase Initial Data Timeout**: Set `initialDataTimeout` to 60 seconds or higher
622
- 2. **Increase Buffer Size**: Set `maxPendingDataSize` to 10MB or higher
623
- 3. **Enable TLS Debug Logging**: Set `enableTlsDebugLogging: true` to troubleshoot handshake issues
624
- 4. **Enable Keep-Alive Probes**: Set `enableKeepAliveProbes: true` for better connection stability
625
- 5. **Check Certificate Chain**: Ensure your certificate chain is complete and in the correct order
626
-
627
- ```typescript
628
- // Configuration to fix Chrome certificate errors
629
- const smartProxy = new SmartProxy({
630
- // ... other settings
631
- initialDataTimeout: 60000,
632
- maxPendingDataSize: 10 * 1024 * 1024,
633
- enableTlsDebugLogging: true,
634
- enableKeepAliveProbes: true
635
- });
636
- ```
637
-
638
- ### Connection Stability
639
-
640
- For improved connection stability in high-traffic environments:
437
+ ### NetworkProxy
438
+ - Verify ports, certificates and `rejectUnauthorized` for TLS errors
439
+ - Configure CORS or use `addDefaultHeaders` for preflight issues
440
+ - Increase `maxConnections` or `connectionPoolSize` under load
641
441
 
642
- 1. **Set Appropriate Timeouts**: Use longer timeouts for long-lived connections
643
- 2. **Use Domain-Specific Timeouts**: Configure per-domain timeouts for different types of services
644
- 3. **Enable TCP Keep-Alive**: Ensure `keepAlive` is set to `true`
645
- 4. **Monitor Connection Statistics**: Enable detailed logging to track termination reasons
646
- 5. **Fine-tune Inactivity Checks**: Adjust `inactivityCheckInterval` based on your traffic patterns
442
+ ### Port80Handler
443
+ - Run as root or grant CAP_NET_BIND_SERVICE for port 80
444
+ - Inspect `certificate-failed` events and switch staging/production
647
445
 
648
- ### NfTables Troubleshooting
446
+ ### NfTablesProxy
447
+ - Ensure `nft` is installed and run with sufficient privileges
448
+ - Use `forceCleanSlate:true` to clear conflicting rules
649
449
 
650
- If you're experiencing issues with NfTablesProxy:
450
+ ### Redirect / SslRedirect
451
+ - Check `fromHost`/`fromPath` patterns and Host headers
452
+ - Validate `sslOptions` key/cert correctness
651
453
 
652
- 1. **Enable Detailed Logging**: Set `enableLogging: true` to see all rule operations
653
- 2. **Force Clean Slate**: Use `forceCleanSlate: true` to remove any lingering rules
654
- 3. **Use IP Sets**: Enable `useIPSets: true` for cleaner rule management
655
- 4. **Check Permissions**: Ensure your process has sufficient permissions to modify nftables
656
- 5. **Verify IPv6 Support**: If using `ipv6Support: true`, ensure ip6tables is available
454
+ ### SmartProxy & SniHandler
455
+ - Increase `initialDataTimeout`/`maxPendingDataSize` for large ClientHello
456
+ - Enable `enableTlsDebugLogging` to trace handshake
457
+ - Ensure `allowSessionTicket` and fragmentation support for resumption
657
458
 
658
459
  ## License and Legal Information
659
460