Compare commits
144 Commits
Author | SHA1 | Date | |
---|---|---|---|
58ba0d9362 | |||
ccccc5b8c8 | |||
d8466a866c | |||
119b643690 | |||
98f1e0df4c | |||
d6022c8f8a | |||
0ea0f02428 | |||
e452f55203 | |||
55f25f1976 | |||
98b7f3ed7f | |||
cb83caeafd | |||
7850a80452 | |||
ef8f583a90 | |||
2bdd6f8c1f | |||
99d28eafd1 | |||
788b444fcc | |||
4225abe3c4 | |||
74fdb58f84 | |||
bffdaffe39 | |||
67a4228518 | |||
681209f2e1 | |||
c415a6c361 | |||
009e3c4f0e | |||
f9c42975dc | |||
feef949afe | |||
8d3b07b1e6 | |||
51fe935f1f | |||
146fac73cf | |||
4465cac807 | |||
9d7ed21cba | |||
54fbe5beac | |||
0704853fa2 | |||
8cf22ee38b | |||
f28e68e487 | |||
499aed19f6 | |||
618b6fe2d1 | |||
d6027c11c1 | |||
bbdea52677 | |||
d8585975a8 | |||
98c61cccbb | |||
b3dcc0ae22 | |||
b96d7dec98 | |||
0d0a1c740b | |||
9bd87b8437 | |||
0e281b3243 | |||
a14b7802c4 | |||
138900ca8b | |||
cb6c2503e2 | |||
f3fd903231 | |||
0e605d9a9d | |||
1718a3b2f2 | |||
568f77e65b | |||
e212dacbf3 | |||
eea8942670 | |||
0574331b91 | |||
06e6c2eb52 | |||
edd9db31c2 | |||
d4251b2cf9 | |||
4ccc1db8a2 | |||
7e3ed93bc9 | |||
fa793f2c4a | |||
fe8106f0c8 | |||
b317ab8b3a | |||
4fd5524a0f | |||
2013d03ac6 | |||
0e888c5add | |||
7f891a304c | |||
f6cc665f12 | |||
48c5ea3b1d | |||
bd9292bf47 | |||
6532e6f0e0 | |||
8791da83b4 | |||
9ad08edf79 | |||
c0de8c59a2 | |||
3748689c16 | |||
d0b3139fda | |||
fd4f731ada | |||
ced9b5b27b | |||
eb70a86304 | |||
131d9d326e | |||
12de96a7d5 | |||
296e1fcdc7 | |||
8459e4013c | |||
191c8ac0e6 | |||
3ab483d164 | |||
fcd80dc56b | |||
8ddffcd6e5 | |||
a5a7781c17 | |||
d647e77cdf | |||
9161336197 | |||
2e63d13dd4 | |||
af6ed735d5 | |||
7d38f29ef3 | |||
0df26d4367 | |||
f9a6e2d748 | |||
1cb6302750 | |||
f336f25535 | |||
5d6b707440 | |||
622ad2ff20 | |||
dd23efd28d | |||
0ddf68a919 | |||
ec08ca51f5 | |||
29688d1379 | |||
c83f6fa278 | |||
60333b0a59 | |||
1aa409907b | |||
adee6afc76 | |||
4a0792142f | |||
f1b810a4fa | |||
96b5877c5f | |||
6d627f67f7 | |||
9af968b8e7 | |||
b3ba0c21e8 | |||
ef707a5870 | |||
6ca14edb38 | |||
5a5686b6b9 | |||
2080f419cb | |||
659aae297b | |||
fcd0f61b5c | |||
7ee35a98e3 | |||
ea0f6d2270 | |||
621ad9e681 | |||
7cea5773ee | |||
a2cb56ba65 | |||
408b793149 | |||
f6c3d2d3d0 | |||
422eb5ec40 | |||
45390c4389 | |||
0f2e6d688c | |||
3bd7b70c19 | |||
07a82a09be | |||
23253a2731 | |||
be31a9b553 | |||
a1051f78e8 | |||
aa756bd698 | |||
ff4f44d6fc | |||
63ebad06ea | |||
31e15b65ec | |||
266895ccc5 | |||
dc3d56771b | |||
38601a41bb | |||
a53e6f1019 | |||
3de35f3b2c | |||
b9210d891e |
496
changelog.md
496
changelog.md
@ -1,5 +1,501 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-03-11 - 3.32.0 - feat(PortProxy)
|
||||
Enhance TLS session cache, SNI extraction, and chained proxy support in PortProxy. Improve handling of multiple and fragmented TLS records, and add new configuration options (isChainedProxy, chainPosition, aggressiveTlsRefresh, tlsSessionCache) for robust TLS certificate refresh.
|
||||
|
||||
- Implement TlsSessionCache with configurable cleanup, eviction, and statistics.
|
||||
- Improve extractSNIInfo to process multiple TLS records and partial handshake data.
|
||||
- Add new settings to detect chained proxy scenarios and adjust timeouts accordingly.
|
||||
- Enhance TLS state refresh with aggressive probing and deep refresh sequence.
|
||||
|
||||
## 2025-03-11 - 3.31.2 - fix(PortProxy)
|
||||
Improve SNI renegotiation handling by adding flexible domain configuration matching on rehandshake and session resumption events.
|
||||
|
||||
- When a rehandshake is detected with a changed SNI, first check existing domain config rules and log if allowed.
|
||||
- If the exact domain config is not found, additionally attempt flexible matching using parent domain and wildcard patterns.
|
||||
- For resumed sessions, try an exact match first and then use fallback logic to select a similar domain config based on matching target IP.
|
||||
- Enhanced logging added to help diagnose missing or mismatched domain configurations.
|
||||
|
||||
## 2025-03-11 - 3.31.1 - fix(PortProxy)
|
||||
Improve TLS handshake buffering and enhance debug logging for SNI forwarding in PortProxy
|
||||
|
||||
- Explicitly copy the initial TLS handshake data to prevent mutation before buffering
|
||||
- Log buffered TLS handshake data with SNI information for better diagnostics
|
||||
- Add detailed error logs on TLS connection failures, including server and domain config status
|
||||
- Output additional debug messages during ClientHello forwarding to verify proper TLS handshake processing
|
||||
|
||||
## 2025-03-11 - 3.31.0 - feat(PortProxy)
|
||||
Improve TLS handshake SNI extraction and add session resumption tracking in PortProxy
|
||||
|
||||
- Added ITlsSessionInfo interface and a global tlsSessionCache to track TLS session IDs for session resumption
|
||||
- Implemented a cleanup timer for the TLS session cache with startSessionCleanupTimer and stopSessionCleanupTimer
|
||||
- Enhanced extractSNIInfo to return detailed SNI information including session IDs, ticket details, and resumption status
|
||||
- Updated renegotiation handlers to use extractSNIInfo for proper SNI extraction during TLS rehandshake
|
||||
|
||||
## 2025-03-11 - 3.30.8 - fix(core)
|
||||
No changes in this commit.
|
||||
|
||||
|
||||
## 2025-03-11 - 3.30.7 - fix(PortProxy)
|
||||
Improve TLS renegotiation SNI handling by first checking if the new SNI is allowed under the existing domain config. If not, attempt to find an alternative domain config and update the locked domain accordingly; otherwise, terminate the connection on SNI mismatch.
|
||||
|
||||
- Added a preliminary check against the original domain config to allow re-handshakes if the new SNI matches allowed patterns.
|
||||
- If the original config does not allow, search for an alternative domain config and validate IP rules.
|
||||
- Update the locked domain when allowed, ensuring connection reuse with valid certificate context.
|
||||
- Terminate the connection if no suitable domain config is found or IP restrictions are violated.
|
||||
|
||||
## 2025-03-11 - 3.30.6 - fix(PortProxy)
|
||||
Improve TLS renegotiation handling in PortProxy by validating the new SNI against allowed domain configurations. If the new SNI is permitted based on existing IP rules, update the locked domain to allow connection reuse; otherwise, terminate the connection to prevent misrouting.
|
||||
|
||||
- Added logic to check if a new SNI during renegotiation is allowed by comparing IP rules from the matching domain configuration.
|
||||
- Updated detailed logging to indicate when a valid SNI change is accepted and when it results in a mismatch termination.
|
||||
|
||||
## 2025-03-10 - 3.30.5 - fix(internal)
|
||||
No uncommitted changes detected; project files and tests remain unchanged.
|
||||
|
||||
|
||||
## 2025-03-10 - 3.30.4 - fix(PortProxy)
|
||||
Fix TLS renegotiation handling and adjust TLS keep-alive timeouts in PortProxy implementation
|
||||
|
||||
- Allow TLS renegotiation data without an explicit SNI extraction to pass through, ensuring valid renegotiations are not dropped (critical for Chrome).
|
||||
- Update TLS keep-alive timeout from an aggressive 30 minutes to a more generous 4 hours to reduce unnecessary reconnections.
|
||||
- Increase inactivity thresholds for TLS connections from 20 minutes to 2 hours with an additional verification interval extended from 5 to 15 minutes.
|
||||
- Adjust long-lived TLS connection timeout from 45 minutes to 8 hours for improved certificate context refresh in chained proxy scenarios.
|
||||
|
||||
## 2025-03-10 - 3.30.3 - fix(classes.portproxy.ts)
|
||||
Simplify timeout management in PortProxy and fix chained proxy certificate refresh issues
|
||||
|
||||
- Reduced TLS keep-alive timeout from 8 hours to 30 minutes to ensure frequent certificate refresh
|
||||
- Added aggressive TLS state refresh after 20 minutes of inactivity and secondary verification checks
|
||||
- Lowered long-lived TLS connection lifetime from 12 hours to 45 minutes to prevent stale certificates
|
||||
- Removed configurable timeout settings from the public API in favor of hardcoded sensible defaults
|
||||
- Simplified internal timeout management to reduce code complexity and improve certificate handling in chained proxies
|
||||
|
||||
## 2025-03-10 - 3.31.0 - fix(classes.portproxy.ts)
|
||||
Simplified timeout management and fixed certificate issues in chained proxy scenarios
|
||||
|
||||
- Dramatically reduced TLS keep-alive timeout from 8 hours to 30 minutes to ensure fresh certificates
|
||||
- Added aggressive certificate refresh after 20 minutes of inactivity (down from 4 hours)
|
||||
- Added secondary verification checks for TLS refresh operations
|
||||
- Reduced long-lived TLS connection lifetime from 12 hours to 45 minutes
|
||||
- Removed configurable timeouts completely from the public API in favor of hardcoded sensible defaults
|
||||
- Simplified interface by removing no-longer-configurable settings while maintaining internal compatibility
|
||||
- Reduced overall code complexity by eliminating complex timeout management
|
||||
- Fixed chained proxy certificate issues by ensuring more frequent certificate refreshes in all deployment scenarios
|
||||
|
||||
## 2025-03-10 - 3.30.2 - fix(classes.portproxy.ts)
|
||||
Adjust TLS keep-alive timeout to refresh certificate context.
|
||||
|
||||
- Modified TLS keep-alive timeout for connections to 8 hours to refresh certificate context.
|
||||
- Updated timeout log messages for clarity on TLS certificate refresh.
|
||||
|
||||
## 2025-03-10 - 3.30.1 - fix(PortProxy)
|
||||
Improve TLS keep-alive management and fix whitespace formatting
|
||||
|
||||
- Implemented better handling for TLS keep-alive connections after sleep or long inactivity.
|
||||
- Reformatted whitespace for better readability and consistency.
|
||||
|
||||
## 2025-03-08 - 3.30.0 - feat(PortProxy)
|
||||
Add advanced TLS keep-alive handling and system sleep detection
|
||||
|
||||
- Implemented system sleep detection to maintain keep-alive connections.
|
||||
- Enhanced TLS keep-alive connections with extended timeout and sleep detection mechanisms.
|
||||
- Introduced automatic TLS state refresh after system wake-up to prevent connection drops.
|
||||
|
||||
## 2025-03-07 - 3.29.3 - fix(core)
|
||||
Fix functional errors in the proxy setup and enhance pnpm configuration
|
||||
|
||||
- Corrected pnpm configuration to include specific dependencies as 'onlyBuiltDependencies'.
|
||||
|
||||
## 2025-03-07 - 3.29.2 - fix(PortProxy)
|
||||
Fix test for PortProxy handling of custom IPs in Docker/CI environments.
|
||||
|
||||
- Ensure compatibility with Docker/CI environments by standardizing on 127.0.0.1 for test server setup.
|
||||
- Simplify test configuration by using a unique port rather than different IPs.
|
||||
|
||||
## 2025-03-07 - 3.29.1 - fix(readme)
|
||||
Update readme for IPTablesProxy options
|
||||
|
||||
- Add comprehensive examples for IPTablesProxy usage.
|
||||
- Expand IPTablesProxy settings with IPv6, logging, and advanced features.
|
||||
- Clarify option defaults and descriptions for IPTablesProxy.
|
||||
- Enhance 'Troubleshooting' section with IPTables tips.
|
||||
|
||||
## 2025-03-07 - 3.29.0 - feat(IPTablesProxy)
|
||||
Enhanced IPTablesProxy with multi-port and IPv6 support
|
||||
|
||||
- Added support for specifying multiple ports and port ranges, allowing for more complex network proxy configurations.
|
||||
- Introduced IPv6 support to allow handling of IPv6 addressed networks.
|
||||
- Implemented more detailed logging and error handling features to improve debugging capabilities.
|
||||
- Enhanced integration options with NetworkProxy, allowing for a more seamless routing and termination process.
|
||||
- Restructured the initialization and validation process to ensure robust handling of configuration settings.
|
||||
|
||||
## 2025-03-07 - 3.28.6 - fix(PortProxy)
|
||||
Adjust default timeout settings and enhance keep-alive connection handling in PortProxy.
|
||||
|
||||
- Updated default value for maxConnectionLifetime to 24 hours and inactivityTimeout to 4 hours.
|
||||
- Introduced enhanced settings for treating keep-alive connections as 'extended' or 'immortal'.
|
||||
- Modified logic to avoid closing keep-alive connections unnecessarily by adding inactivity warnings and grace periods.
|
||||
|
||||
## 2025-03-07 - 3.28.5 - fix(core)
|
||||
Ensure proper resource cleanup during server shutdown.
|
||||
|
||||
- Fixed potential hanging of server shutdown due to improper cleanup in promise handling.
|
||||
- Corrected potential memory leaks by ensuring all pending and active connections are properly closed during shutdown.
|
||||
|
||||
## 2025-03-07 - 3.28.4 - fix(router)
|
||||
Improve path pattern matching and hostname prioritization in router
|
||||
|
||||
- Enhance path pattern matching capabilities
|
||||
- Ensure hostname prioritization in routing logic
|
||||
|
||||
## 2025-03-06 - 3.28.3 - fix(PortProxy)
|
||||
Ensure timeout values are within Node.js safe limits
|
||||
|
||||
- Implemented `ensureSafeTimeout` to keep timeout values under the maximum safe integer for Node.js.
|
||||
- Updated timeout configurations in `PortProxy` to include safety checks.
|
||||
|
||||
## 2025-03-06 - 3.28.2 - fix(portproxy)
|
||||
Adjust safe timeout defaults in PortProxy to prevent overflow issues.
|
||||
|
||||
- Adjusted socketTimeout to maximum safe limit (~24.8 days) for PortProxy.
|
||||
- Adjusted maxConnectionLifetime to maximum safe limit (~24.8 days) for PortProxy.
|
||||
- Ensured enhanced default timeout settings in PortProxy.
|
||||
|
||||
## 2025-03-06 - 3.28.1 - fix(PortProxy)
|
||||
Improved code formatting and readability in PortProxy class by adjusting spacing and comments.
|
||||
|
||||
- Adjusted comment and spacing for better code readability.
|
||||
- No functional changes made in the PortProxy class.
|
||||
|
||||
## 2025-03-06 - 3.28.0 - feat(router)
|
||||
Add detailed routing tests and refactor ProxyRouter for improved path matching
|
||||
|
||||
- Implemented a comprehensive test suite for the ProxyRouter class to ensure accurate routing based on hostnames and path patterns.
|
||||
- Refactored the ProxyRouter to enhance path matching logic with improvements in wildcard and parameter handling.
|
||||
- Improved logging capabilities within the ProxyRouter for enhanced debugging and info level insights.
|
||||
- Optimized the data structures for storing and accessing proxy configurations to reduce overhead in routing operations.
|
||||
|
||||
## 2025-03-06 - 3.27.0 - feat(AcmeCertManager)
|
||||
Introduce AcmeCertManager for enhanced ACME certificate management
|
||||
|
||||
- Refactored the existing Port80Handler to AcmeCertManager.
|
||||
- Added event-driven certificate management with CertManagerEvents.
|
||||
- Introduced options for configuration such as renew thresholds and production mode.
|
||||
- Implemented certificate renewal checks and logging improvements.
|
||||
|
||||
## 2025-03-05 - 3.26.0 - feat(readme)
|
||||
Updated README with enhanced TLS handling, connection management, and troubleshooting sections.
|
||||
|
||||
- Added details on enhanced TLS handling and browser compatibility improvements.
|
||||
- Included advanced connection management features like random timeout prevention.
|
||||
- Provided comprehensive troubleshooting tips for browser certificate errors and connection stability.
|
||||
- Clarified default configuration options and optimization settings for PortProxy.
|
||||
|
||||
## 2025-03-05 - 3.25.4 - fix(portproxy)
|
||||
Improve connection timeouts and detailed logging for PortProxy
|
||||
|
||||
- Refactored timeout management for connections to include enhanced defaults and prevent thundering herd.
|
||||
- Improved support for TLS handshake detection with logging capabilities in PortProxy.
|
||||
- Removed protocol-specific handling which is now managed generically.
|
||||
- Introduced enhanced logging for SNI extraction and connection management.
|
||||
|
||||
## 2025-03-05 - 3.25.3 - fix(core)
|
||||
Update dependencies and configuration improvements.
|
||||
|
||||
- Upgrade TypeScript version to 5.8.2 for better compatibility.
|
||||
- Ensure all proxy and server tests pass with updated configurations.
|
||||
- Improve logging for better traceability in proxy operations.
|
||||
- Add handlers for WebSockets and HTTPS improvements.
|
||||
- Fix various issues related to proxy timeout and connection handling.
|
||||
- Update test certificates validation for better test coverage.
|
||||
|
||||
## 2025-03-05 - 3.25.2 - fix(PortProxy)
|
||||
Adjust timeout settings and handle inactivity properly in PortProxy.
|
||||
|
||||
- Changed initialDataTimeout default to 30 seconds for better handling of initial data reception.
|
||||
- Adjusted keepAliveInitialDelay to 30 seconds for consistent socket optimization.
|
||||
- Introduced proper inactivity handling with updated timeout logic.
|
||||
- Parity check now accounts for a 120-second threshold for outgoing socket closure.
|
||||
|
||||
## 2025-03-05 - 3.25.1 - fix(PortProxy)
|
||||
Adjust inactivity threshold to a random value between 20 and 30 minutes for better variability
|
||||
|
||||
- Modified inactivity threshold calculation within PortProxy to use a random value between 1.2 and 1.8 million milliseconds.
|
||||
|
||||
## 2025-03-05 - 3.25.0 - feat(PortProxy)
|
||||
Enhanced PortProxy with detailed logging, protocol detection, and rate limiting.
|
||||
|
||||
- Added detailed logging capabilities for connection tracking in the PortProxy.
|
||||
- Introduced protocol detection allowing HTTP and WebSocket upgrades.
|
||||
- Implemented rate limiting for connections by IP.
|
||||
- Enhanced timeout handling for various protocol-specific scenarios.
|
||||
|
||||
## 2025-03-05 - 3.24.0 - feat(core)
|
||||
Enhance core functionalities and test coverage for NetworkProxy and PortProxy
|
||||
|
||||
- Added maximum connections, timeout settings, log levels, and CORS support in NetworkProxy.
|
||||
- Improved WebSocket handling with heartbeat and metrics tracking.
|
||||
- Enhanced connection management in PortProxy with optimizations for socket settings.
|
||||
- SNI and IP validation improvements.
|
||||
- Updates to test cases for comprehensive coverage.
|
||||
|
||||
## 2025-03-05 - 3.23.1 - fix(PortProxy)
|
||||
Enhanced connection setup to handle pending data buffering before establishing outgoing connection
|
||||
|
||||
- Introduced pending data buffering to address issues with data reception before outgoing connection is fully established.
|
||||
- Removed immediate data piping in favor of buffering to ensure complete initial data transfer.
|
||||
- Added temporary data handler to collect incoming data during connection setup for precise activity tracking.
|
||||
|
||||
## 2025-03-03 - 3.23.0 - feat(documentation)
|
||||
Updated documentation with architecture flow diagrams.
|
||||
|
||||
- Added detailed architecture and flow diagrams for SmartProxy components.
|
||||
- Included HTTPS Reverse Proxy Flow diagram.
|
||||
- Integrated Port Proxy with SNI-based Routing diagram.
|
||||
- Added Let's Encrypt Certificate Acquisition flow.
|
||||
|
||||
## 2025-03-03 - 3.22.5 - fix(documentation)
|
||||
Refactored readme for clarity and consistency, fixed documentation typos
|
||||
|
||||
- Updated readme to improve clarity and remove redundant information.
|
||||
- Fixed minor documentation issues in the code comments.
|
||||
- Reorganized readme structure for better readability.
|
||||
- Improved sample code snippets for easier understanding.
|
||||
|
||||
## 2025-03-03 - 3.22.4 - fix(core)
|
||||
Addressed minor issues in the core modules to improve stability and performance.
|
||||
|
||||
|
||||
## 2025-03-03 - 3.22.3 - fix(core)
|
||||
Improve connection management and error handling in PortProxy
|
||||
|
||||
- Refactored connection cleanup to handle errors more gracefully.
|
||||
- Introduced comprehensive comments for better code understanding.
|
||||
- Revised SNI data timeout logic for connection handling.
|
||||
- Enhanced logging and error reporting during connection management.
|
||||
- Improved inactivity checks and parity checks for existing connections.
|
||||
|
||||
## 2025-03-03 - 3.22.2 - fix(portproxy)
|
||||
Refactored connection cleanup logic in PortProxy
|
||||
|
||||
- Simplified the connection cleanup logic by removing redundant methods.
|
||||
- Consolidated the cleanup initiation and execution into a single cleanup method.
|
||||
- Improved error handling by ensuring connections are closed appropriately.
|
||||
|
||||
## 2025-03-03 - 3.22.1 - fix(PortProxy)
|
||||
Fix connection timeout and IP validation handling for PortProxy
|
||||
|
||||
- Adjusted initial data timeout setting for SNI-enabled connections in PortProxy.
|
||||
- Restored IP validation logic to original behavior, ensuring compatibility with domain configurations.
|
||||
|
||||
## 2025-03-03 - 3.22.0 - feat(classes.portproxy)
|
||||
Enhanced PortProxy to support initial data timeout and improved IP handling
|
||||
|
||||
- Added `initialDataTimeout` to PortProxy settings for handling data flow in chained proxies.
|
||||
- Improved IP validation by allowing relaxed checks in chained proxy setups.
|
||||
- Introduced dynamic logging for connection lifecycle and proxy configurations.
|
||||
- Enhanced timeout handling for better proxy resilience.
|
||||
|
||||
## 2025-03-03 - 3.21.0 - feat(PortProxy)
|
||||
Enhancements to connection management in PortProxy
|
||||
|
||||
- Introduced a unique ID for each connection record for improved tracking.
|
||||
- Enhanced cleanup mechanism for connections with dual states: initiated and executed.
|
||||
- Implemented shutdown process handling to ensure graceful connection closure.
|
||||
- Added logging for better tracing of connection activities and states.
|
||||
- Improved connection setup with explicit timeouts and data flow management.
|
||||
- Integrated inactivity and parity checks to monitor connection health.
|
||||
|
||||
## 2025-03-01 - 3.20.2 - fix(PortProxy)
|
||||
Enhance connection cleanup handling in PortProxy
|
||||
|
||||
- Add checks to ensure timers are reset only if outgoing socket is active
|
||||
- Prevent setting outgoingActive if the connection is already closed
|
||||
|
||||
## 2025-03-01 - 3.20.1 - fix(PortProxy)
|
||||
Improve IP allowance check for forced domains
|
||||
|
||||
- Enhanced IP allowance check logic by incorporating blocked IPs and default allowed IPs for forced domains within port proxy configurations.
|
||||
|
||||
## 2025-03-01 - 3.20.0 - feat(PortProxy)
|
||||
Enhance PortProxy with advanced connection cleanup and logging
|
||||
|
||||
- Introduced `cleanupConnection` method for improved connection management.
|
||||
- Added logging for connection cleanup including special conditions.
|
||||
- Implemented parity check to clean up connections when outgoing side closes but incoming remains active.
|
||||
- Improved logging during interval checks for active connections and their durations.
|
||||
|
||||
## 2025-03-01 - 3.19.0 - feat(PortProxy)
|
||||
Enhance PortProxy with default blocked IPs
|
||||
|
||||
- Introduced defaultBlockedIPs in IPortProxySettings to handle globally blocked IPs.
|
||||
- Added logic for merging domain-specific and default allowed and blocked IPs for effective IP filtering.
|
||||
- Refactored helper functions for IP and port range checks to improve modularity in PortProxy.
|
||||
|
||||
## 2025-02-27 - 3.18.2 - fix(portproxy)
|
||||
Fixed typographical errors in comments within PortProxy class.
|
||||
|
||||
- Corrected typographical errors in comments within the PortProxy class.
|
||||
|
||||
## 2025-02-27 - 3.18.1 - fix(PortProxy)
|
||||
Refactor and enhance PortProxy test cases and handling
|
||||
|
||||
- Refactored test cases in test/test.portproxy.ts for clarity and added coverage.
|
||||
- Improved TCP server helper functions for better flexibility.
|
||||
- Fixed issues with domain handling in PortProxy configuration.
|
||||
- Introduced round-robin logic for multi-IP domains in PortProxy.
|
||||
- Ensured proper cleanup and stopping of test servers in the test suite.
|
||||
|
||||
## 2025-02-27 - 3.18.0 - feat(PortProxy)
|
||||
Add SNI-based renegotiation handling in PortProxy
|
||||
|
||||
- Introduced a new field 'lockedDomain' in IConnectionRecord to store initial SNI.
|
||||
- Enhanced connection management by enforcing termination if rehandshake is detected with different SNI.
|
||||
|
||||
## 2025-02-27 - 3.17.1 - fix(PortProxy)
|
||||
Fix handling of SNI re-negotiation in PortProxy
|
||||
|
||||
- Removed connection locking to the initially negotiated SNI
|
||||
- Improved handling of SNI during renegotiation in PortProxy
|
||||
|
||||
## 2025-02-27 - 3.17.0 - feat(smartproxy)
|
||||
Enhance description clarity and improve SNI handling with domain locking.
|
||||
|
||||
- Improved package description in package.json, readme.md, and npmextra.json for better clarity and keyword optimization.
|
||||
- Enhanced SNI handling in PortProxy by adding domain locking and extra checks to terminate connections if a different SNI is detected post-handshake.
|
||||
- Refactored readme.md to better explain the usage and functionalities of the proxy features including SSL redirection, WebSocket handling, and dynamic routing.
|
||||
|
||||
## 2025-02-27 - 3.16.9 - fix(portproxy)
|
||||
Extend domain input validation to support string arrays in port proxy configurations.
|
||||
|
||||
- Modify IDomainConfig interface to allow domain specification as string array.
|
||||
- Update connection setup logic to handle multiple domain patterns.
|
||||
- Enhance domain rejection logging to include all domain patterns.
|
||||
|
||||
## 2025-02-27 - 3.16.8 - fix(PortProxy)
|
||||
Fix IP filtering for domain and global default allowed lists and improve port-based routing logic.
|
||||
|
||||
- Improved logic to prioritize domain-specific allowed IPs over global defaults.
|
||||
- Fixed port-based rules application to handle global port ranges more effectively.
|
||||
- Enhanced rejection handling for unauthorized IP addresses in both domain-specific and default global lists.
|
||||
|
||||
## 2025-02-27 - 3.16.7 - fix(PortProxy)
|
||||
Improved IP validation logic in PortProxy to ensure correct domain matching and fallback
|
||||
|
||||
- Refactored the setupConnection function inside PortProxy to enhance IP address validation.
|
||||
- Domain-specific allowed IP preference is applied before default list lookup.
|
||||
- Removed redundant condition checks to streamline connection rejection paths.
|
||||
|
||||
## 2025-02-27 - 3.16.6 - fix(PortProxy)
|
||||
Optimize connection cleanup logic in PortProxy by removing unnecessary delays.
|
||||
|
||||
- Removed multiple await plugins.smartdelay.delayFor(0) calls.
|
||||
- Improved performance by ensuring timely resource release during connection termination.
|
||||
|
||||
## 2025-02-27 - 3.16.5 - fix(PortProxy)
|
||||
Improved connection cleanup process with added asynchronous delays
|
||||
|
||||
- Connection cleanup now includes asynchronous delays for reliable order of operations.
|
||||
|
||||
## 2025-02-27 - 3.16.4 - fix(PortProxy)
|
||||
Fix and enhance port proxy handling
|
||||
|
||||
- Ensure that all created proxy servers are correctly checked for listening state.
|
||||
- Corrected the handling of ports and domain configurations within port proxy setups.
|
||||
- Expanded test coverage for handling multiple concurrent and chained proxy connections.
|
||||
|
||||
## 2025-02-27 - 3.16.3 - fix(PortProxy)
|
||||
Refactored PortProxy to support multiple listening ports and improved modularity.
|
||||
|
||||
- Updated PortProxy to allow multiple listening ports with flexible configuration.
|
||||
- Moved helper functions for IP and port range checks outside the class for cleaner code structure.
|
||||
|
||||
## 2025-02-27 - 3.16.2 - fix(PortProxy)
|
||||
Fix port-based routing logic in PortProxy
|
||||
|
||||
- Optimized the handling and checking of local ports in the global port range.
|
||||
- Fixed the logic for rejecting or accepting connections based on predefined port ranges.
|
||||
- Improved handling of the default and specific domain configurations during port-based connections.
|
||||
|
||||
## 2025-02-27 - 3.16.1 - fix(core)
|
||||
Updated minor version numbers in dependencies for patch release.
|
||||
|
||||
- No specific file changes detected.
|
||||
- Dependencies versioning adjusted for stability.
|
||||
|
||||
## 2025-02-27 - 3.16.0 - feat(PortProxy)
|
||||
Enhancements made to PortProxy settings and capabilities
|
||||
|
||||
- Added 'forwardAllGlobalRanges' and 'targetIP' to IPortProxySettings.
|
||||
- Improved PortProxy to forward connections based on domain-specific configurations.
|
||||
- Added comprehensive handling for global port-range based connection forwarding.
|
||||
- Enabled forwarding of all connections on global port ranges directly to global target IP.
|
||||
|
||||
## 2025-02-27 - 3.15.0 - feat(classes.portproxy)
|
||||
Add support for port range-based routing with enhanced IP and port validation.
|
||||
|
||||
- Introduced globalPortRanges in IPortProxySettings for routing based on port ranges.
|
||||
- Improved connection handling with port range and domain configuration validations.
|
||||
- Updated connection logging to include the local port information.
|
||||
|
||||
## 2025-02-26 - 3.14.2 - fix(PortProxy)
|
||||
Fix cleanup timer reset for PortProxy
|
||||
|
||||
- Resolved an issue where the cleanup timer in the PortProxy class did not reset correctly if both incoming and outgoing data events were triggered without clearing flags.
|
||||
|
||||
## 2025-02-26 - 3.14.1 - fix(PortProxy)
|
||||
Increased default maxConnectionLifetime for PortProxy to 600000 ms
|
||||
|
||||
- Updated PortProxy settings to extend default maxConnectionLifetime to 10 minutes.
|
||||
|
||||
## 2025-02-26 - 3.14.0 - feat(PortProxy)
|
||||
Introduce max connection lifetime feature
|
||||
|
||||
- Added an optional maxConnectionLifetime setting for PortProxy.
|
||||
- Forces cleanup of long-lived connections based on inactivity or lifetime limit.
|
||||
|
||||
## 2025-02-25 - 3.13.0 - feat(core)
|
||||
Add support for tagging iptables rules with comments and cleaning them up on process exit
|
||||
|
||||
- Extended IPTablesProxy class to include tagging rules with unique comments.
|
||||
- Added feature to clean up iptables rules via comments during process exit.
|
||||
|
||||
## 2025-02-24 - 3.12.0 - feat(IPTablesProxy)
|
||||
Introduce IPTablesProxy class for managing iptables NAT rules
|
||||
|
||||
- Added IPTablesProxy class to facilitate basic port forwarding using iptables.
|
||||
- Introduced IIpTableProxySettings interface for configuring IPTablesProxy.
|
||||
- Implemented start and stop methods for managing iptables rules dynamically.
|
||||
|
||||
## 2025-02-24 - 3.11.0 - feat(Port80Handler)
|
||||
Add automatic certificate issuance with ACME client
|
||||
|
||||
- Implemented automatic certificate issuance using 'acme-client' for Port80Handler.
|
||||
- Converts account key and CSR from Buffers to strings for processing.
|
||||
- Implemented HTTP-01 challenge handling for certificate acquisition.
|
||||
- New certificates are fetched and added dynamically.
|
||||
|
||||
## 2025-02-24 - 3.10.5 - fix(portproxy)
|
||||
Fix incorrect import path in test file
|
||||
|
||||
- Change import path from '../ts/smartproxy.portproxy.js' to '../ts/classes.portproxy.js' in test/test.portproxy.ts
|
||||
|
||||
## 2025-02-23 - 3.10.4 - fix(PortProxy)
|
||||
Refactor connection tracking to utilize unified records in PortProxy
|
||||
|
||||
- Implemented a unified record system for tracking incoming and outgoing connections.
|
||||
- Replaced individual connection tracking sets with a Set of IConnectionRecord.
|
||||
- Improved logging of connection activities and statistics.
|
||||
|
||||
## 2025-02-23 - 3.10.3 - fix(PortProxy)
|
||||
Refactor and optimize PortProxy for improved readability and maintainability
|
||||
|
||||
- Simplified and clarified inline comments.
|
||||
- Optimized the extractSNI function for better readability.
|
||||
- Streamlined the cleanup process for connections in PortProxy.
|
||||
- Improved handling and logging of incoming and outgoing connections.
|
||||
|
||||
## 2025-02-23 - 3.10.2 - fix(PortProxy)
|
||||
Fix connection handling to include timeouts for SNI-enabled connections.
|
||||
|
||||
|
@ -5,22 +5,26 @@
|
||||
"githost": "code.foss.global",
|
||||
"gitscope": "push.rocks",
|
||||
"gitrepo": "smartproxy",
|
||||
"description": "a proxy for handling high workloads of proxying",
|
||||
"description": "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.",
|
||||
"npmPackagename": "@push.rocks/smartproxy",
|
||||
"license": "MIT",
|
||||
"projectDomain": "push.rocks",
|
||||
"keywords": [
|
||||
"proxy",
|
||||
"network traffic",
|
||||
"network",
|
||||
"traffic management",
|
||||
"SSL",
|
||||
"TLS",
|
||||
"WebSocket",
|
||||
"port proxying",
|
||||
"dynamic routing",
|
||||
"authentication",
|
||||
"real-time applications",
|
||||
"high workload",
|
||||
"http",
|
||||
"https",
|
||||
"websocket",
|
||||
"network routing",
|
||||
"ssl redirect",
|
||||
"port mapping",
|
||||
"HTTPS",
|
||||
"reverse proxy",
|
||||
"authentication"
|
||||
"server",
|
||||
"network security"
|
||||
]
|
||||
}
|
||||
},
|
||||
|
48
package.json
48
package.json
@ -1,8 +1,8 @@
|
||||
{
|
||||
"name": "@push.rocks/smartproxy",
|
||||
"version": "3.10.2",
|
||||
"version": "3.32.0",
|
||||
"private": false,
|
||||
"description": "a proxy for handling high workloads of proxying",
|
||||
"description": "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.",
|
||||
"main": "dist_ts/index.js",
|
||||
"typings": "dist_ts/index.d.ts",
|
||||
"type": "module",
|
||||
@ -15,25 +15,26 @@
|
||||
"buildDocs": "tsdoc"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@git.zone/tsbuild": "^2.1.66",
|
||||
"@git.zone/tsbuild": "^2.2.6",
|
||||
"@git.zone/tsrun": "^1.2.44",
|
||||
"@git.zone/tstest": "^1.0.77",
|
||||
"@push.rocks/tapbundle": "^5.5.6",
|
||||
"@types/node": "^22.13.0",
|
||||
"typescript": "^5.7.3"
|
||||
"@types/node": "^22.13.9",
|
||||
"typescript": "^5.8.2"
|
||||
},
|
||||
"dependencies": {
|
||||
"@push.rocks/lik": "^6.1.0",
|
||||
"@push.rocks/smartdelay": "^3.0.5",
|
||||
"@push.rocks/smartpromise": "^4.2.2",
|
||||
"@push.rocks/smartpromise": "^4.2.3",
|
||||
"@push.rocks/smartrequest": "^2.0.23",
|
||||
"@push.rocks/smartstring": "^4.0.15",
|
||||
"@tsclass/tsclass": "^4.4.0",
|
||||
"@tsclass/tsclass": "^4.4.3",
|
||||
"@types/minimatch": "^5.1.2",
|
||||
"@types/ws": "^8.5.14",
|
||||
"minimatch": "^9.0.3",
|
||||
"@types/ws": "^8.18.0",
|
||||
"acme-client": "^5.4.0",
|
||||
"minimatch": "^10.0.1",
|
||||
"pretty-ms": "^9.2.0",
|
||||
"ws": "^8.18.0"
|
||||
"ws": "^8.18.1"
|
||||
},
|
||||
"files": [
|
||||
"ts/**/*",
|
||||
@ -52,16 +53,20 @@
|
||||
],
|
||||
"keywords": [
|
||||
"proxy",
|
||||
"network traffic",
|
||||
"network",
|
||||
"traffic management",
|
||||
"SSL",
|
||||
"TLS",
|
||||
"WebSocket",
|
||||
"port proxying",
|
||||
"dynamic routing",
|
||||
"authentication",
|
||||
"real-time applications",
|
||||
"high workload",
|
||||
"http",
|
||||
"https",
|
||||
"websocket",
|
||||
"network routing",
|
||||
"ssl redirect",
|
||||
"port mapping",
|
||||
"HTTPS",
|
||||
"reverse proxy",
|
||||
"authentication"
|
||||
"server",
|
||||
"network security"
|
||||
],
|
||||
"homepage": "https://code.foss.global/push.rocks/smartproxy#readme",
|
||||
"repository": {
|
||||
@ -72,6 +77,11 @@
|
||||
"url": "https://code.foss.global/push.rocks/smartproxy/issues"
|
||||
},
|
||||
"pnpm": {
|
||||
"overrides": {}
|
||||
"overrides": {},
|
||||
"onlyBuiltDependencies": [
|
||||
"esbuild",
|
||||
"mongodb-memory-server",
|
||||
"puppeteer"
|
||||
]
|
||||
}
|
||||
}
|
||||
|
2294
pnpm-lock.yaml
generated
2294
pnpm-lock.yaml
generated
File diff suppressed because it is too large
Load Diff
583
readme.md
583
readme.md
@ -1,108 +1,553 @@
|
||||
# @push.rocks/smartproxy
|
||||
|
||||
A proxy for handling high workloads of proxying.
|
||||
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.
|
||||
|
||||
## Install
|
||||
## Architecture & Flow Diagrams
|
||||
|
||||
To install `@push.rocks/smartproxy`, run the following command in your project's root directory:
|
||||
### Component Architecture
|
||||
The diagram below illustrates the main components of SmartProxy and how they interact:
|
||||
|
||||
```bash
|
||||
npm install @push.rocks/smartproxy --save
|
||||
```mermaid
|
||||
flowchart TB
|
||||
Client([Client])
|
||||
|
||||
subgraph "SmartProxy Components"
|
||||
direction TB
|
||||
HTTP80[HTTP Port 80\nSslRedirect]
|
||||
HTTPS443[HTTPS Port 443\nNetworkProxy]
|
||||
PortProxy[TCP Port Proxy\nwith SNI routing]
|
||||
IPTables[IPTablesProxy]
|
||||
Router[ProxyRouter]
|
||||
ACME[Port80Handler\nACME/Let's Encrypt]
|
||||
Certs[(SSL Certificates)]
|
||||
end
|
||||
|
||||
subgraph "Backend Services"
|
||||
Service1[Service 1]
|
||||
Service2[Service 2]
|
||||
Service3[Service 3]
|
||||
end
|
||||
|
||||
Client -->|HTTP Request| HTTP80
|
||||
HTTP80 -->|Redirect| Client
|
||||
Client -->|HTTPS Request| HTTPS443
|
||||
Client -->|TLS/TCP| PortProxy
|
||||
|
||||
HTTPS443 -->|Route Request| Router
|
||||
Router -->|Proxy Request| Service1
|
||||
Router -->|Proxy Request| Service2
|
||||
|
||||
PortProxy -->|Direct TCP| Service2
|
||||
PortProxy -->|Direct TCP| Service3
|
||||
|
||||
IPTables -.->|Low-level forwarding| PortProxy
|
||||
|
||||
HTTP80 -.->|Challenge Response| ACME
|
||||
ACME -.->|Generate/Manage| Certs
|
||||
Certs -.->|Provide TLS Certs| HTTPS443
|
||||
|
||||
classDef component fill:#f9f,stroke:#333,stroke-width:2px;
|
||||
classDef backend fill:#bbf,stroke:#333,stroke-width:1px;
|
||||
classDef client fill:#dfd,stroke:#333,stroke-width:2px;
|
||||
|
||||
class Client client;
|
||||
class HTTP80,HTTPS443,PortProxy,IPTables,Router,ACME component;
|
||||
class Service1,Service2,Service3 backend;
|
||||
```
|
||||
|
||||
This will add `@push.rocks/smartproxy` to your project's dependencies.
|
||||
### HTTPS Reverse Proxy Flow
|
||||
This diagram shows how HTTPS requests are handled and proxied to backend services:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Client
|
||||
participant NetworkProxy
|
||||
participant ProxyRouter
|
||||
participant Backend
|
||||
|
||||
Client->>NetworkProxy: HTTPS Request
|
||||
|
||||
Note over NetworkProxy: TLS Termination
|
||||
|
||||
NetworkProxy->>ProxyRouter: Route Request
|
||||
ProxyRouter->>ProxyRouter: Match hostname to config
|
||||
|
||||
alt Authentication Required
|
||||
NetworkProxy->>Client: Request Authentication
|
||||
Client->>NetworkProxy: Send Credentials
|
||||
NetworkProxy->>NetworkProxy: Validate Credentials
|
||||
end
|
||||
|
||||
NetworkProxy->>Backend: Forward Request
|
||||
Backend->>NetworkProxy: Response
|
||||
|
||||
Note over NetworkProxy: Add Default Headers
|
||||
|
||||
NetworkProxy->>Client: Forward Response
|
||||
|
||||
alt WebSocket Request
|
||||
Client->>NetworkProxy: Upgrade to WebSocket
|
||||
NetworkProxy->>Backend: Upgrade to WebSocket
|
||||
loop WebSocket Active
|
||||
Client->>NetworkProxy: WebSocket Message
|
||||
NetworkProxy->>Backend: Forward Message
|
||||
Backend->>NetworkProxy: WebSocket Message
|
||||
NetworkProxy->>Client: Forward Message
|
||||
NetworkProxy-->>NetworkProxy: Heartbeat Check
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
### Port Proxy with SNI-based Routing
|
||||
This diagram illustrates how TCP connections with SNI (Server Name Indication) are processed and forwarded:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Client
|
||||
participant PortProxy
|
||||
participant Backend
|
||||
|
||||
Client->>PortProxy: TLS Connection
|
||||
|
||||
alt SNI Enabled
|
||||
PortProxy->>Client: Accept Connection
|
||||
Client->>PortProxy: TLS ClientHello with SNI
|
||||
PortProxy->>PortProxy: Extract SNI Hostname
|
||||
PortProxy->>PortProxy: Match Domain Config
|
||||
PortProxy->>PortProxy: Validate Client IP
|
||||
|
||||
alt IP Allowed
|
||||
PortProxy->>Backend: Forward Connection
|
||||
Note over PortProxy,Backend: Bidirectional Data Flow
|
||||
else IP Rejected
|
||||
PortProxy->>Client: Close Connection
|
||||
end
|
||||
else Port-based Routing
|
||||
PortProxy->>PortProxy: Match Port Range
|
||||
PortProxy->>PortProxy: Find Domain Config
|
||||
PortProxy->>PortProxy: Validate Client IP
|
||||
|
||||
alt IP Allowed
|
||||
PortProxy->>Backend: Forward Connection
|
||||
Note over PortProxy,Backend: Bidirectional Data Flow
|
||||
else IP Rejected
|
||||
PortProxy->>Client: Close Connection
|
||||
end
|
||||
end
|
||||
|
||||
loop Connection Active
|
||||
PortProxy-->>PortProxy: Monitor Activity
|
||||
PortProxy-->>PortProxy: Check Max Lifetime
|
||||
alt Inactivity or Max Lifetime Exceeded
|
||||
PortProxy->>Client: Close Connection
|
||||
PortProxy->>Backend: Close Connection
|
||||
end
|
||||
end
|
||||
```
|
||||
|
||||
### Let's Encrypt Certificate Acquisition
|
||||
This diagram shows how certificates are automatically acquired through the ACME protocol:
|
||||
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
participant Client
|
||||
participant Port80Handler
|
||||
participant ACME as Let's Encrypt ACME
|
||||
participant NetworkProxy
|
||||
|
||||
Client->>Port80Handler: HTTP Request for domain
|
||||
|
||||
alt Certificate Exists
|
||||
Port80Handler->>Client: Redirect to HTTPS
|
||||
else No Certificate
|
||||
Port80Handler->>Port80Handler: Mark domain as obtaining cert
|
||||
Port80Handler->>ACME: Create account & new order
|
||||
ACME->>Port80Handler: Challenge information
|
||||
|
||||
Port80Handler->>Port80Handler: Store challenge token & key authorization
|
||||
|
||||
ACME->>Port80Handler: HTTP-01 Challenge Request
|
||||
Port80Handler->>ACME: Challenge Response
|
||||
|
||||
ACME->>ACME: Validate domain ownership
|
||||
ACME->>Port80Handler: Challenge validated
|
||||
|
||||
Port80Handler->>Port80Handler: Generate CSR
|
||||
Port80Handler->>ACME: Submit CSR
|
||||
ACME->>Port80Handler: Issue Certificate
|
||||
|
||||
Port80Handler->>Port80Handler: Store certificate & private key
|
||||
Port80Handler->>Port80Handler: Mark certificate as obtained
|
||||
|
||||
Note over Port80Handler,NetworkProxy: Certificate available for use
|
||||
|
||||
Client->>Port80Handler: Another HTTP Request
|
||||
Port80Handler->>Client: Redirect to HTTPS
|
||||
Client->>NetworkProxy: HTTPS Request
|
||||
Note over NetworkProxy: Uses new certificate
|
||||
end
|
||||
```
|
||||
|
||||
## Features
|
||||
|
||||
- **HTTPS Reverse Proxy** - Route traffic to backend services based on hostname with TLS termination
|
||||
- **WebSocket Support** - Full WebSocket proxying with heartbeat monitoring
|
||||
- **TCP Port Forwarding** - Advanced port forwarding with SNI inspection and domain-based routing
|
||||
- **Enhanced TLS Handling** - Robust TLS handshake processing with improved certificate error handling
|
||||
- **HTTP to HTTPS Redirection** - Automatically redirect HTTP requests to HTTPS
|
||||
- **Let's Encrypt Integration** - Automatic certificate management using ACME protocol
|
||||
- **IP Filtering** - Control access with IP allow/block lists using glob patterns
|
||||
- **IPTables Integration** - Direct manipulation of iptables for low-level port forwarding
|
||||
- **Basic Authentication** - Support for basic auth on proxied routes
|
||||
- **Connection Management** - Intelligent connection tracking and cleanup with configurable timeouts
|
||||
- **Browser Compatibility** - Optimized for modern browsers with fixes for common TLS handshake issues
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
npm install @push.rocks/smartproxy
|
||||
```
|
||||
|
||||
## Usage
|
||||
|
||||
`@push.rocks/smartproxy` is a versatile package for setting up and handling proxies with various capabilities such as SSL redirection, port proxying, and creating network proxies with complex routing rules. Below is a comprehensive guide on using its features.
|
||||
|
||||
### Setting Up a Network Proxy
|
||||
|
||||
Create a network proxy to route incoming HTTPS requests to different local servers based on the hostname.
|
||||
### Basic Reverse Proxy Setup
|
||||
|
||||
```typescript
|
||||
import { NetworkProxy } from '@push.rocks/smartproxy';
|
||||
|
||||
// Instantiate the NetworkProxy with desired options
|
||||
const myNetworkProxy = new NetworkProxy({ port: 443 });
|
||||
// Create a reverse proxy listening on port 443
|
||||
const proxy = new NetworkProxy({
|
||||
port: 443
|
||||
});
|
||||
|
||||
// Define your reverse proxy configurations
|
||||
// Define reverse proxy configurations
|
||||
const proxyConfigs = [
|
||||
{
|
||||
destinationIp: '127.0.0.1',
|
||||
destinationPort: '3000',
|
||||
hostName: 'example.com',
|
||||
privateKey: `-----BEGIN PRIVATE KEY-----
|
||||
PRIVATE_KEY_CONTENT
|
||||
-----END PRIVATE KEY-----`,
|
||||
publicKey: `-----BEGIN CERTIFICATE-----
|
||||
CERTIFICATE_CONTENT
|
||||
-----END CERTIFICATE-----`,
|
||||
destinationIp: '127.0.0.1',
|
||||
destinationPort: 3000,
|
||||
publicKey: 'your-cert-content',
|
||||
privateKey: 'your-key-content'
|
||||
},
|
||||
// Add more reverse proxy configurations here
|
||||
{
|
||||
hostName: 'api.example.com',
|
||||
destinationIp: '127.0.0.1',
|
||||
destinationPort: 4000,
|
||||
publicKey: 'your-cert-content',
|
||||
privateKey: 'your-key-content',
|
||||
// Optional basic auth
|
||||
authentication: {
|
||||
type: 'Basic',
|
||||
user: 'admin',
|
||||
pass: 'secret'
|
||||
}
|
||||
}
|
||||
];
|
||||
|
||||
// Start the network proxy
|
||||
await myNetworkProxy.start();
|
||||
|
||||
// Update proxy configurations dynamically
|
||||
await myNetworkProxy.updateProxyConfigs(proxyConfigs);
|
||||
|
||||
// Optionally, add default headers to all responses
|
||||
await myNetworkProxy.addDefaultHeaders({
|
||||
'X-Powered-By': 'smartproxy',
|
||||
});
|
||||
// Start the proxy and update configurations
|
||||
(async () => {
|
||||
await proxy.start();
|
||||
await proxy.updateProxyConfigs(proxyConfigs);
|
||||
|
||||
// Add default headers to all responses
|
||||
await proxy.addDefaultHeaders({
|
||||
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload'
|
||||
});
|
||||
})();
|
||||
```
|
||||
|
||||
### Port Proxying
|
||||
|
||||
You can also set up a port proxy to forward traffic from one port to another, which is useful for dynamic port forwarding scenarios.
|
||||
|
||||
```typescript
|
||||
import { PortProxy } from '@push.rocks/smartproxy';
|
||||
|
||||
// Create a PortProxy to forward traffic from port 5000 to port 3000
|
||||
const myPortProxy = new PortProxy(5000, 3000);
|
||||
|
||||
// Start the port proxy
|
||||
await myPortProxy.start();
|
||||
|
||||
// To stop the port proxy, simply call
|
||||
await myPortProxy.stop();
|
||||
```
|
||||
|
||||
### Enabling SSL Redirection
|
||||
|
||||
Easily redirect HTTP traffic to HTTPS using the `SslRedirect` class. This is particularly useful when ensuring all traffic uses encryption.
|
||||
### HTTP to HTTPS Redirection
|
||||
|
||||
```typescript
|
||||
import { SslRedirect } from '@push.rocks/smartproxy';
|
||||
|
||||
// Instantiate the SslRedirect on port 80 (HTTP)
|
||||
const mySslRedirect = new SslRedirect(80);
|
||||
|
||||
// Start listening and redirecting to HTTPS
|
||||
await mySslRedirect.start();
|
||||
|
||||
// To stop the redirection, use
|
||||
await mySslRedirect.stop();
|
||||
// Create and start HTTP to HTTPS redirect service on port 80
|
||||
const redirector = new SslRedirect(80);
|
||||
redirector.start();
|
||||
```
|
||||
|
||||
### Advanced Usage
|
||||
### TCP Port Forwarding with Domain-based Routing
|
||||
|
||||
The package integrates seamlessly with TypeScript, allowing for advanced use cases, such as implementing custom routing logic, authentication mechanisms, and handling WebSocket connections through the network proxy.
|
||||
```typescript
|
||||
import { PortProxy } from '@push.rocks/smartproxy';
|
||||
|
||||
For a more advanced setup involving WebSocket proxying and dynamic configuration reloading, refer to the network proxy example provided above. The WebSocket support demonstrates how seamless it is to work with real-time applications.
|
||||
// Configure port proxy with domain-based routing
|
||||
const portProxy = new PortProxy({
|
||||
fromPort: 443,
|
||||
toPort: 8443,
|
||||
targetIP: 'localhost', // Default target host
|
||||
sniEnabled: true, // Enable SNI inspection
|
||||
|
||||
// Enhanced reliability settings
|
||||
initialDataTimeout: 60000, // 60 seconds for initial TLS handshake
|
||||
socketTimeout: 3600000, // 1 hour socket timeout
|
||||
maxConnectionLifetime: 3600000, // 1 hour connection lifetime
|
||||
inactivityTimeout: 3600000, // 1 hour inactivity timeout
|
||||
maxPendingDataSize: 10 * 1024 * 1024, // 10MB buffer for large TLS handshakes
|
||||
|
||||
// Browser compatibility enhancement
|
||||
enableTlsDebugLogging: false, // Enable for troubleshooting TLS issues
|
||||
|
||||
// Port and IP configuration
|
||||
globalPortRanges: [{ from: 443, to: 443 }],
|
||||
defaultAllowedIPs: ['*'], // Allow all IPs by default
|
||||
|
||||
// Socket optimizations for better connection stability
|
||||
noDelay: true, // Disable Nagle's algorithm
|
||||
keepAlive: true, // Enable TCP keepalive
|
||||
enableKeepAliveProbes: true, // Enhanced keepalive for stability
|
||||
|
||||
// Domain-specific routing configuration
|
||||
domainConfigs: [
|
||||
{
|
||||
domains: ['example.com', '*.example.com'], // Glob patterns for matching domains
|
||||
allowedIPs: ['192.168.1.*'], // Restrict access by IP
|
||||
blockedIPs: ['192.168.1.100'], // Block specific IPs
|
||||
targetIPs: ['10.0.0.1', '10.0.0.2'], // Round-robin between multiple targets
|
||||
portRanges: [{ from: 443, to: 443 }],
|
||||
connectionTimeout: 7200000 // Domain-specific timeout (2 hours)
|
||||
}
|
||||
],
|
||||
|
||||
preserveSourceIP: true
|
||||
});
|
||||
|
||||
Remember, when dealing with certificates and private keys for HTTPS configurations, always secure your keys and store them appropriately.
|
||||
portProxy.start();
|
||||
```
|
||||
|
||||
`@push.rocks/smartproxy` provides a solid foundation for handling high workloads and complex proxying requirements with ease, whether you're implementing SSL redirections, port forwarding, or extensive routing and WebSocket support in your network.
|
||||
### IPTables Port Forwarding
|
||||
|
||||
For more information on how to use the features, refer to the in-depth documentation available in the package's repository or the npm package description.
|
||||
```typescript
|
||||
import { IPTablesProxy } from '@push.rocks/smartproxy';
|
||||
|
||||
// Basic usage - forward single port
|
||||
const basicProxy = new IPTablesProxy({
|
||||
fromPort: 80,
|
||||
toPort: 8080,
|
||||
toHost: 'localhost',
|
||||
preserveSourceIP: true,
|
||||
deleteOnExit: true // Automatically clean up rules on process exit
|
||||
});
|
||||
|
||||
// Forward port ranges
|
||||
const rangeProxy = new IPTablesProxy({
|
||||
fromPort: { from: 3000, to: 3010 }, // Forward ports 3000-3010
|
||||
toPort: { from: 8000, to: 8010 }, // To ports 8000-8010
|
||||
protocol: 'tcp', // TCP protocol (default)
|
||||
ipv6Support: true, // Enable IPv6 support
|
||||
enableLogging: true // Enable detailed logging
|
||||
});
|
||||
|
||||
// Multiple port specifications with IP filtering
|
||||
const advancedProxy = new IPTablesProxy({
|
||||
fromPort: [80, 443, { from: 8000, to: 8010 }], // Multiple ports/ranges
|
||||
toPort: [8080, 8443, { from: 18000, to: 18010 }],
|
||||
allowedSourceIPs: ['10.0.0.0/8', '192.168.1.0/24'], // Only allow these IPs
|
||||
bannedSourceIPs: ['192.168.1.100'], // Explicitly block these IPs
|
||||
addJumpRule: true, // Use custom chain for better management
|
||||
checkExistingRules: true // Check for duplicate rules
|
||||
});
|
||||
|
||||
// NetworkProxy integration for SSL termination
|
||||
const sslProxy = new IPTablesProxy({
|
||||
fromPort: 443,
|
||||
toPort: 8443,
|
||||
netProxyIntegration: {
|
||||
enabled: true,
|
||||
redirectLocalhost: true, // Redirect localhost traffic to NetworkProxy
|
||||
sslTerminationPort: 8443 // Port where NetworkProxy handles SSL
|
||||
}
|
||||
});
|
||||
|
||||
// Start any of the proxies
|
||||
await basicProxy.start();
|
||||
```
|
||||
|
||||
### Automatic HTTPS Certificate Management
|
||||
|
||||
```typescript
|
||||
import { Port80Handler } from '@push.rocks/smartproxy';
|
||||
|
||||
// Create an ACME handler for Let's Encrypt
|
||||
const acmeHandler = new Port80Handler();
|
||||
|
||||
// Add domains to manage certificates for
|
||||
acmeHandler.addDomain('example.com');
|
||||
acmeHandler.addDomain('api.example.com');
|
||||
```
|
||||
|
||||
## Configuration Options
|
||||
|
||||
### NetworkProxy Options
|
||||
|
||||
| Option | Description | Default |
|
||||
|----------------|---------------------------------------------------|---------|
|
||||
| `port` | Port to listen on for HTTPS connections | - |
|
||||
|
||||
### PortProxy Settings
|
||||
|
||||
| Option | Description | Default |
|
||||
|---------------------------|--------------------------------------------------------|-------------|
|
||||
| `fromPort` | Port to listen on | - |
|
||||
| `toPort` | Destination port to forward to | - |
|
||||
| `targetIP` | Default destination IP if not specified in domainConfig | 'localhost' |
|
||||
| `sniEnabled` | Enable SNI inspection for TLS connections | false |
|
||||
| `defaultAllowedIPs` | IP patterns allowed by default | - |
|
||||
| `defaultBlockedIPs` | IP patterns blocked by default | - |
|
||||
| `preserveSourceIP` | Preserve the original client IP | false |
|
||||
| `maxConnectionLifetime` | Maximum time in ms to keep a connection open | 3600000 |
|
||||
| `initialDataTimeout` | Timeout for initial data/handshake in ms | 60000 |
|
||||
| `socketTimeout` | Socket inactivity timeout in ms | 3600000 |
|
||||
| `inactivityTimeout` | Connection inactivity check timeout in ms | 3600000 |
|
||||
| `inactivityCheckInterval` | How often to check for inactive connections in ms | 60000 |
|
||||
| `maxPendingDataSize` | Maximum bytes to buffer during connection setup | 10485760 |
|
||||
| `globalPortRanges` | Array of port ranges to listen on | - |
|
||||
| `forwardAllGlobalRanges` | Forward all global range connections to targetIP | false |
|
||||
| `gracefulShutdownTimeout` | Time in ms to wait during shutdown | 30000 |
|
||||
| `noDelay` | Disable Nagle's algorithm | true |
|
||||
| `keepAlive` | Enable TCP keepalive | true |
|
||||
| `keepAliveInitialDelay` | Initial delay before sending keepalive probes in ms | 30000 |
|
||||
| `enableKeepAliveProbes` | Enable enhanced TCP keep-alive probes | false |
|
||||
| `enableTlsDebugLogging` | Enable detailed TLS handshake debugging | false |
|
||||
| `enableDetailedLogging` | Enable detailed connection logging | false |
|
||||
| `enableRandomizedTimeouts`| Randomize timeouts slightly to prevent thundering herd | true |
|
||||
|
||||
### IPTablesProxy Settings
|
||||
|
||||
| Option | Description | Default |
|
||||
|-----------------------|---------------------------------------------------|-------------|
|
||||
| `fromPort` | Source port(s) or range(s) to forward from | - |
|
||||
| `toPort` | Destination port(s) or range(s) to forward to | - |
|
||||
| `toHost` | Destination host to forward to | 'localhost' |
|
||||
| `preserveSourceIP` | Preserve the original client IP | false |
|
||||
| `deleteOnExit` | Remove iptables rules when process exits | false |
|
||||
| `protocol` | Protocol to forward ('tcp', 'udp', or 'all') | 'tcp' |
|
||||
| `enableLogging` | Enable detailed logging | false |
|
||||
| `ipv6Support` | Enable IPv6 support with ip6tables | false |
|
||||
| `allowedSourceIPs` | Array of IP addresses/CIDR allowed to connect | - |
|
||||
| `bannedSourceIPs` | Array of IP addresses/CIDR blocked from connecting | - |
|
||||
| `forceCleanSlate` | Clear all IPTablesProxy rules before starting | false |
|
||||
| `addJumpRule` | Add a custom chain for cleaner rule management | false |
|
||||
| `checkExistingRules` | Check if rules already exist before adding | true |
|
||||
| `netProxyIntegration` | NetworkProxy integration options (object) | - |
|
||||
|
||||
#### IPTablesProxy NetworkProxy Integration Options
|
||||
|
||||
| Option | Description | Default |
|
||||
|----------------------|---------------------------------------------------|---------|
|
||||
| `enabled` | Enable NetworkProxy integration | false |
|
||||
| `redirectLocalhost` | Redirect localhost traffic to NetworkProxy | false |
|
||||
| `sslTerminationPort` | Port where NetworkProxy handles SSL termination | - |
|
||||
|
||||
## Advanced Features
|
||||
|
||||
### TLS Handshake Optimization
|
||||
|
||||
The enhanced `PortProxy` implementation includes significant improvements for TLS handshake handling:
|
||||
|
||||
- Robust SNI extraction with improved error handling
|
||||
- Increased buffer size for complex TLS handshakes (10MB)
|
||||
- Longer initial handshake timeout (60 seconds)
|
||||
- Detection and tracking of TLS connection states
|
||||
- Optional detailed TLS debug logging for troubleshooting
|
||||
- Browser compatibility fixes for Chrome certificate errors
|
||||
|
||||
```typescript
|
||||
// Example configuration to solve Chrome certificate errors
|
||||
const portProxy = new PortProxy({
|
||||
// ... other settings
|
||||
initialDataTimeout: 60000, // Give browser more time for handshake
|
||||
maxPendingDataSize: 10 * 1024 * 1024, // Larger buffer for complex handshakes
|
||||
enableTlsDebugLogging: true, // Enable when troubleshooting
|
||||
});
|
||||
```
|
||||
|
||||
### Connection Management and Monitoring
|
||||
|
||||
The `PortProxy` class includes built-in connection tracking and monitoring:
|
||||
|
||||
- Automatic cleanup of idle connections with configurable timeouts
|
||||
- Timeouts for connections that exceed maximum lifetime
|
||||
- Detailed logging of connection states
|
||||
- Termination statistics
|
||||
- Randomized timeouts to prevent "thundering herd" problems
|
||||
- Per-domain timeout configuration
|
||||
|
||||
### WebSocket Support
|
||||
|
||||
The `NetworkProxy` class provides WebSocket support with:
|
||||
|
||||
- WebSocket connection proxying
|
||||
- Automatic heartbeat monitoring
|
||||
- Connection cleanup for inactive WebSockets
|
||||
|
||||
### SNI-based Routing
|
||||
|
||||
The `PortProxy` class can inspect the SNI (Server Name Indication) field in TLS handshakes to route connections based on the requested domain:
|
||||
|
||||
- Multiple backend targets per domain
|
||||
- Round-robin load balancing
|
||||
- Domain-specific allowed IP ranges
|
||||
- Protection against SNI renegotiation attacks
|
||||
|
||||
### Enhanced IPTables Management
|
||||
|
||||
The improved `IPTablesProxy` class offers advanced capabilities:
|
||||
|
||||
- Support for multiple port ranges and individual ports
|
||||
- IPv6 support with ip6tables
|
||||
- Source IP filtering with allow/block lists
|
||||
- Custom chain creation for better rule organization
|
||||
- NetworkProxy integration for SSL termination
|
||||
- Automatic rule existence checking to prevent duplicates
|
||||
- Comprehensive cleanup on shutdown
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Browser Certificate Errors
|
||||
|
||||
If you experience certificate errors in browsers, especially in Chrome, try these solutions:
|
||||
|
||||
1. **Increase Initial Data Timeout**: Set `initialDataTimeout` to 60 seconds or higher
|
||||
2. **Increase Buffer Size**: Set `maxPendingDataSize` to 10MB or higher
|
||||
3. **Enable TLS Debug Logging**: Set `enableTlsDebugLogging: true` to troubleshoot handshake issues
|
||||
4. **Enable Keep-Alive Probes**: Set `enableKeepAliveProbes: true` for better connection stability
|
||||
5. **Check Certificate Chain**: Ensure your certificate chain is complete and in the correct order
|
||||
|
||||
```typescript
|
||||
// Configuration to fix Chrome certificate errors
|
||||
const portProxy = new PortProxy({
|
||||
// ... other settings
|
||||
initialDataTimeout: 60000,
|
||||
maxPendingDataSize: 10 * 1024 * 1024,
|
||||
enableTlsDebugLogging: true,
|
||||
enableKeepAliveProbes: true
|
||||
});
|
||||
```
|
||||
|
||||
### Connection Stability
|
||||
|
||||
For improved connection stability in high-traffic environments:
|
||||
|
||||
1. **Set Appropriate Timeouts**: Use longer timeouts for long-lived connections
|
||||
2. **Use Domain-Specific Timeouts**: Configure per-domain timeouts for different types of services
|
||||
3. **Enable TCP Keep-Alive**: Ensure `keepAlive` is set to `true`
|
||||
4. **Monitor Connection Statistics**: Enable detailed logging to track termination reasons
|
||||
5. **Fine-tune Inactivity Checks**: Adjust `inactivityCheckInterval` based on your traffic patterns
|
||||
|
||||
### IPTables Troubleshooting
|
||||
|
||||
If you're experiencing issues with IPTablesProxy:
|
||||
|
||||
1. **Enable Detailed Logging**: Set `enableLogging: true` to see all rule operations
|
||||
2. **Force Clean Slate**: Use `forceCleanSlate: true` to remove any lingering rules
|
||||
3. **Use Custom Chains**: Enable `addJumpRule: true` for cleaner rule management
|
||||
4. **Check Permissions**: Ensure your process has sufficient permissions to modify iptables
|
||||
5. **Verify IPv6 Support**: If using `ipv6Support: true`, ensure ip6tables is available
|
||||
|
||||
## 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 that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
||||
|
||||
**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.
|
||||
|
||||
@ -117,4 +562,4 @@ 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.
|
||||
|
||||
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.
|
@ -1,6 +1,6 @@
|
||||
import { expect, tap } from '@push.rocks/tapbundle';
|
||||
import * as net from 'net';
|
||||
import { PortProxy } from '../ts/smartproxy.portproxy.js';
|
||||
import { PortProxy } from '../ts/classes.portproxy.js';
|
||||
|
||||
let testServer: net.Server;
|
||||
let portProxy: PortProxy;
|
||||
@ -8,246 +8,336 @@ const TEST_SERVER_PORT = 4000;
|
||||
const PROXY_PORT = 4001;
|
||||
const TEST_DATA = 'Hello through port proxy!';
|
||||
|
||||
// Helper function to create a test TCP server
|
||||
function createTestServer(port: number): Promise<net.Server> {
|
||||
// Track all created servers and proxies for proper cleanup
|
||||
const allServers: net.Server[] = [];
|
||||
const allProxies: PortProxy[] = [];
|
||||
|
||||
// Helper: Creates a test TCP server that listens on a given port and host.
|
||||
function createTestServer(port: number, host: string = 'localhost'): Promise<net.Server> {
|
||||
return new Promise((resolve) => {
|
||||
const server = net.createServer((socket) => {
|
||||
socket.on('data', (data) => {
|
||||
// Echo the received data back
|
||||
// Echo the received data back with a prefix.
|
||||
socket.write(`Echo: ${data.toString()}`);
|
||||
});
|
||||
|
||||
socket.on('error', (error) => {
|
||||
console.error('[Test Server] Socket error:', error);
|
||||
console.error(`[Test Server] Socket error on ${host}:${port}:`, error);
|
||||
});
|
||||
});
|
||||
|
||||
server.listen(port, () => {
|
||||
console.log(`[Test Server] Listening on port ${port}`);
|
||||
server.listen(port, host, () => {
|
||||
console.log(`[Test Server] Listening on ${host}:${port}`);
|
||||
allServers.push(server); // Track this server
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Helper function to create a test client connection
|
||||
// Helper: Creates a test client connection.
|
||||
function createTestClient(port: number, data: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const client = new net.Socket();
|
||||
let response = '';
|
||||
|
||||
|
||||
const timeout = setTimeout(() => {
|
||||
client.destroy();
|
||||
reject(new Error(`Client connection timeout to port ${port}`));
|
||||
}, 5000);
|
||||
|
||||
client.connect(port, 'localhost', () => {
|
||||
console.log('[Test Client] Connected to server');
|
||||
client.write(data);
|
||||
});
|
||||
|
||||
client.on('data', (chunk) => {
|
||||
response += chunk.toString();
|
||||
client.end();
|
||||
});
|
||||
|
||||
client.on('end', () => {
|
||||
clearTimeout(timeout);
|
||||
resolve(response);
|
||||
});
|
||||
|
||||
client.on('error', (error) => {
|
||||
clearTimeout(timeout);
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Setup test environment
|
||||
// SETUP: Create a test server and a PortProxy instance.
|
||||
tap.test('setup port proxy test environment', async () => {
|
||||
testServer = await createTestServer(TEST_SERVER_PORT);
|
||||
portProxy = new PortProxy({
|
||||
fromPort: PROXY_PORT,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
toHost: 'localhost',
|
||||
domains: [],
|
||||
targetIP: 'localhost',
|
||||
domainConfigs: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1']
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
globalPortRanges: []
|
||||
});
|
||||
allProxies.push(portProxy); // Track this proxy
|
||||
});
|
||||
|
||||
// Test that the proxy starts and its servers are listening.
|
||||
tap.test('should start port proxy', async () => {
|
||||
await portProxy.start();
|
||||
expect(portProxy.netServer.listening).toBeTrue();
|
||||
expect((portProxy as any).netServers.every((server: net.Server) => server.listening)).toBeTrue();
|
||||
});
|
||||
|
||||
// Test basic TCP forwarding.
|
||||
tap.test('should forward TCP connections and data to localhost', async () => {
|
||||
const response = await createTestClient(PROXY_PORT, TEST_DATA);
|
||||
expect(response).toEqual(`Echo: ${TEST_DATA}`);
|
||||
});
|
||||
|
||||
// Test proxy with a custom target host.
|
||||
tap.test('should forward TCP connections to custom host', async () => {
|
||||
// Create a new proxy instance with a custom host
|
||||
const customHostProxy = new PortProxy({
|
||||
fromPort: PROXY_PORT + 1,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
toHost: '127.0.0.1',
|
||||
domains: [],
|
||||
targetIP: '127.0.0.1',
|
||||
domainConfigs: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1']
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
globalPortRanges: []
|
||||
});
|
||||
allProxies.push(customHostProxy); // Track this proxy
|
||||
|
||||
await customHostProxy.start();
|
||||
const response = await createTestClient(PROXY_PORT + 1, TEST_DATA);
|
||||
expect(response).toEqual(`Echo: ${TEST_DATA}`);
|
||||
await customHostProxy.stop();
|
||||
|
||||
// Remove from tracking after stopping
|
||||
const index = allProxies.indexOf(customHostProxy);
|
||||
if (index !== -1) allProxies.splice(index, 1);
|
||||
});
|
||||
|
||||
tap.test('should forward connections based on domain-specific target IP', async () => {
|
||||
// Create a second test server on a different port
|
||||
const TEST_SERVER_PORT_2 = TEST_SERVER_PORT + 100;
|
||||
const testServer2 = await createTestServer(TEST_SERVER_PORT_2);
|
||||
// Test custom IP forwarding
|
||||
// Modified to work in Docker/CI environments without needing 127.0.0.2
|
||||
tap.test('should forward connections to custom IP', async () => {
|
||||
// Set up ports that are FAR apart to avoid any possible confusion
|
||||
const forcedProxyPort = PROXY_PORT + 2; // 4003 - The port that our proxy listens on
|
||||
const targetServerPort = TEST_SERVER_PORT + 200; // 4200 - Target test server on different port
|
||||
|
||||
// Create a test server listening on a unique port on 127.0.0.1 (works in all environments)
|
||||
const testServer2 = await createTestServer(targetServerPort, '127.0.0.1');
|
||||
|
||||
// Create a proxy with domain-specific target IPs
|
||||
// We're simulating routing to a different IP by using a different port
|
||||
// This tests the core functionality without requiring multiple IPs
|
||||
const domainProxy = new PortProxy({
|
||||
fromPort: PROXY_PORT + 2,
|
||||
toPort: TEST_SERVER_PORT, // default port
|
||||
toHost: 'localhost', // default host
|
||||
domains: [{
|
||||
domain: 'domain1.test',
|
||||
allowedIPs: ['127.0.0.1'],
|
||||
targetIP: '127.0.0.1'
|
||||
}, {
|
||||
domain: 'domain2.test',
|
||||
allowedIPs: ['127.0.0.1'],
|
||||
targetIP: 'localhost'
|
||||
}],
|
||||
sniEnabled: false, // We'll test without SNI first since this is a TCP proxy test
|
||||
defaultAllowedIPs: ['127.0.0.1']
|
||||
fromPort: forcedProxyPort, // 4003 - Listen on this port
|
||||
toPort: targetServerPort, // 4200 - Forward to this port
|
||||
targetIP: '127.0.0.1', // Always use localhost (works in Docker)
|
||||
domainConfigs: [], // No domain configs to confuse things
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1'], // Allow localhost
|
||||
// We'll test the functionality WITHOUT port ranges this time
|
||||
globalPortRanges: []
|
||||
});
|
||||
allProxies.push(domainProxy); // Track this proxy
|
||||
|
||||
await domainProxy.start();
|
||||
|
||||
// Test default connection (should use default host)
|
||||
const response1 = await createTestClient(PROXY_PORT + 2, TEST_DATA);
|
||||
expect(response1).toEqual(`Echo: ${TEST_DATA}`);
|
||||
|
||||
// Create another proxy with different default host
|
||||
const domainProxy2 = new PortProxy({
|
||||
fromPort: PROXY_PORT + 3,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
toHost: '127.0.0.1',
|
||||
domains: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1']
|
||||
});
|
||||
|
||||
await domainProxy2.start();
|
||||
const response2 = await createTestClient(PROXY_PORT + 3, TEST_DATA);
|
||||
expect(response2).toEqual(`Echo: ${TEST_DATA}`);
|
||||
// Send a single test connection
|
||||
const response = await createTestClient(forcedProxyPort, TEST_DATA);
|
||||
expect(response).toEqual(`Echo: ${TEST_DATA}`);
|
||||
|
||||
await domainProxy.stop();
|
||||
await domainProxy2.stop();
|
||||
|
||||
// Remove from tracking after stopping
|
||||
const proxyIndex = allProxies.indexOf(domainProxy);
|
||||
if (proxyIndex !== -1) allProxies.splice(proxyIndex, 1);
|
||||
|
||||
// Close the test server
|
||||
await new Promise<void>((resolve) => testServer2.close(() => resolve()));
|
||||
|
||||
// Remove from tracking
|
||||
const serverIndex = allServers.indexOf(testServer2);
|
||||
if (serverIndex !== -1) allServers.splice(serverIndex, 1);
|
||||
});
|
||||
|
||||
// Test handling of multiple concurrent connections.
|
||||
tap.test('should handle multiple concurrent connections', async () => {
|
||||
const concurrentRequests = 5;
|
||||
const requests = Array(concurrentRequests).fill(null).map((_, i) =>
|
||||
const requests = Array(concurrentRequests).fill(null).map((_, i) =>
|
||||
createTestClient(PROXY_PORT, `${TEST_DATA} ${i + 1}`)
|
||||
);
|
||||
|
||||
const responses = await Promise.all(requests);
|
||||
|
||||
responses.forEach((response, i) => {
|
||||
expect(response).toEqual(`Echo: ${TEST_DATA} ${i + 1}`);
|
||||
});
|
||||
});
|
||||
|
||||
// Test connection timeout handling.
|
||||
tap.test('should handle connection timeouts', async () => {
|
||||
const client = new net.Socket();
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
// Add a timeout to ensure we don't hang here
|
||||
const timeout = setTimeout(() => {
|
||||
client.destroy();
|
||||
resolve();
|
||||
}, 3000);
|
||||
|
||||
client.connect(PROXY_PORT, 'localhost', () => {
|
||||
// Don't send any data, just wait for timeout
|
||||
// Do not send any data to trigger a timeout.
|
||||
client.on('close', () => {
|
||||
clearTimeout(timeout);
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
|
||||
client.on('error', () => {
|
||||
clearTimeout(timeout);
|
||||
client.destroy();
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
// Test stopping the port proxy.
|
||||
tap.test('should stop port proxy', async () => {
|
||||
await portProxy.stop();
|
||||
expect(portProxy.netServer.listening).toBeFalse();
|
||||
expect((portProxy as any).netServers.every((server: net.Server) => !server.listening)).toBeTrue();
|
||||
|
||||
// Remove from tracking
|
||||
const index = allProxies.indexOf(portProxy);
|
||||
if (index !== -1) allProxies.splice(index, 1);
|
||||
});
|
||||
|
||||
// Cleanup
|
||||
// Test chained proxies with and without source IP preservation.
|
||||
tap.test('should support optional source IP preservation in chained proxies', async () => {
|
||||
// Test 1: Without IP preservation (default behavior)
|
||||
// Chained proxies without IP preservation.
|
||||
const firstProxyDefault = new PortProxy({
|
||||
fromPort: PROXY_PORT + 4,
|
||||
toPort: PROXY_PORT + 5,
|
||||
toHost: 'localhost',
|
||||
domains: [],
|
||||
targetIP: 'localhost',
|
||||
domainConfigs: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1']
|
||||
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1'],
|
||||
globalPortRanges: []
|
||||
});
|
||||
|
||||
const secondProxyDefault = new PortProxy({
|
||||
fromPort: PROXY_PORT + 5,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
toHost: 'localhost',
|
||||
domains: [],
|
||||
targetIP: 'localhost',
|
||||
domainConfigs: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1']
|
||||
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1'],
|
||||
globalPortRanges: []
|
||||
});
|
||||
|
||||
|
||||
allProxies.push(firstProxyDefault, secondProxyDefault); // Track these proxies
|
||||
|
||||
await secondProxyDefault.start();
|
||||
await firstProxyDefault.start();
|
||||
|
||||
// This should work because we explicitly allow both IPv4 and IPv6 formats
|
||||
const response1 = await createTestClient(PROXY_PORT + 4, TEST_DATA);
|
||||
expect(response1).toEqual(`Echo: ${TEST_DATA}`);
|
||||
|
||||
await firstProxyDefault.stop();
|
||||
await secondProxyDefault.stop();
|
||||
|
||||
// Remove from tracking
|
||||
const index1 = allProxies.indexOf(firstProxyDefault);
|
||||
if (index1 !== -1) allProxies.splice(index1, 1);
|
||||
const index2 = allProxies.indexOf(secondProxyDefault);
|
||||
if (index2 !== -1) allProxies.splice(index2, 1);
|
||||
|
||||
// Test 2: With IP preservation
|
||||
// Chained proxies with IP preservation.
|
||||
const firstProxyPreserved = new PortProxy({
|
||||
fromPort: PROXY_PORT + 6,
|
||||
toPort: PROXY_PORT + 7,
|
||||
toHost: 'localhost',
|
||||
domains: [],
|
||||
targetIP: 'localhost',
|
||||
domainConfigs: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
preserveSourceIP: true
|
||||
preserveSourceIP: true,
|
||||
globalPortRanges: []
|
||||
});
|
||||
|
||||
const secondProxyPreserved = new PortProxy({
|
||||
fromPort: PROXY_PORT + 7,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
toHost: 'localhost',
|
||||
domains: [],
|
||||
targetIP: 'localhost',
|
||||
domainConfigs: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
preserveSourceIP: true
|
||||
preserveSourceIP: true,
|
||||
globalPortRanges: []
|
||||
});
|
||||
|
||||
|
||||
allProxies.push(firstProxyPreserved, secondProxyPreserved); // Track these proxies
|
||||
|
||||
await secondProxyPreserved.start();
|
||||
await firstProxyPreserved.start();
|
||||
|
||||
// This should work with just IPv4 because source IP is preserved
|
||||
const response2 = await createTestClient(PROXY_PORT + 6, TEST_DATA);
|
||||
expect(response2).toEqual(`Echo: ${TEST_DATA}`);
|
||||
|
||||
await firstProxyPreserved.stop();
|
||||
await secondProxyPreserved.stop();
|
||||
|
||||
// Remove from tracking
|
||||
const index3 = allProxies.indexOf(firstProxyPreserved);
|
||||
if (index3 !== -1) allProxies.splice(index3, 1);
|
||||
const index4 = allProxies.indexOf(secondProxyPreserved);
|
||||
if (index4 !== -1) allProxies.splice(index4, 1);
|
||||
});
|
||||
|
||||
// Test round-robin behavior for multiple target IPs in a domain config.
|
||||
tap.test('should use round robin for multiple target IPs in domain config', async () => {
|
||||
const domainConfig = {
|
||||
domains: ['rr.test'],
|
||||
allowedIPs: ['127.0.0.1'],
|
||||
targetIPs: ['hostA', 'hostB']
|
||||
} as any;
|
||||
|
||||
const proxyInstance = new PortProxy({
|
||||
fromPort: 0,
|
||||
toPort: 0,
|
||||
targetIP: 'localhost',
|
||||
domainConfigs: [domainConfig],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: [],
|
||||
globalPortRanges: []
|
||||
});
|
||||
|
||||
// Don't track this proxy as it doesn't actually start or listen
|
||||
|
||||
const firstTarget = (proxyInstance as any).getTargetIP(domainConfig);
|
||||
const secondTarget = (proxyInstance as any).getTargetIP(domainConfig);
|
||||
expect(firstTarget).toEqual('hostA');
|
||||
expect(secondTarget).toEqual('hostB');
|
||||
});
|
||||
|
||||
// CLEANUP: Tear down all servers and proxies
|
||||
tap.test('cleanup port proxy test environment', async () => {
|
||||
await new Promise<void>((resolve) => testServer.close(() => resolve()));
|
||||
// Stop all remaining proxies
|
||||
for (const proxy of [...allProxies]) {
|
||||
try {
|
||||
await proxy.stop();
|
||||
const index = allProxies.indexOf(proxy);
|
||||
if (index !== -1) allProxies.splice(index, 1);
|
||||
} catch (err) {
|
||||
console.error(`Error stopping proxy: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Close all remaining servers
|
||||
for (const server of [...allServers]) {
|
||||
try {
|
||||
await new Promise<void>((resolve) => {
|
||||
if (server.listening) {
|
||||
server.close(() => resolve());
|
||||
} else {
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
const index = allServers.indexOf(server);
|
||||
if (index !== -1) allServers.splice(index, 1);
|
||||
} catch (err) {
|
||||
console.error(`Error closing server: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Verify all resources are cleaned up
|
||||
expect(allProxies.length).toEqual(0);
|
||||
expect(allServers.length).toEqual(0);
|
||||
});
|
||||
|
||||
process.on('exit', () => {
|
||||
if (testServer) {
|
||||
testServer.close();
|
||||
}
|
||||
if (portProxy && portProxy.netServer) {
|
||||
portProxy.stop();
|
||||
}
|
||||
});
|
||||
|
||||
export default tap.start();
|
||||
export default tap.start();
|
346
test/test.router.ts
Normal file
346
test/test.router.ts
Normal file
@ -0,0 +1,346 @@
|
||||
import { expect, tap } from '@push.rocks/tapbundle';
|
||||
import * as tsclass from '@tsclass/tsclass';
|
||||
import * as http from 'http';
|
||||
import { ProxyRouter, type IRouterResult } from '../ts/classes.router.js';
|
||||
|
||||
// Test proxies and configurations
|
||||
let router: ProxyRouter;
|
||||
|
||||
// Sample hostname for testing
|
||||
const TEST_DOMAIN = 'example.com';
|
||||
const TEST_SUBDOMAIN = 'api.example.com';
|
||||
const TEST_WILDCARD = '*.example.com';
|
||||
|
||||
// Helper: Creates a mock HTTP request for testing
|
||||
function createMockRequest(host: string, url: string = '/'): http.IncomingMessage {
|
||||
const req = {
|
||||
headers: { host },
|
||||
url,
|
||||
socket: {
|
||||
remoteAddress: '127.0.0.1'
|
||||
}
|
||||
} as any;
|
||||
return req;
|
||||
}
|
||||
|
||||
// Helper: Creates a test proxy configuration
|
||||
function createProxyConfig(
|
||||
hostname: string,
|
||||
destinationIp: string = '10.0.0.1',
|
||||
destinationPort: number = 8080
|
||||
): tsclass.network.IReverseProxyConfig {
|
||||
return {
|
||||
hostName: hostname,
|
||||
destinationIp,
|
||||
destinationPort: destinationPort.toString(), // Convert to string for IReverseProxyConfig
|
||||
publicKey: 'mock-cert',
|
||||
privateKey: 'mock-key'
|
||||
} as tsclass.network.IReverseProxyConfig;
|
||||
}
|
||||
|
||||
// SETUP: Create a ProxyRouter instance
|
||||
tap.test('setup proxy router test environment', async () => {
|
||||
router = new ProxyRouter();
|
||||
|
||||
// Initialize with empty config
|
||||
router.setNewProxyConfigs([]);
|
||||
});
|
||||
|
||||
// Test basic routing by hostname
|
||||
tap.test('should route requests by hostname', async () => {
|
||||
const config = createProxyConfig(TEST_DOMAIN);
|
||||
router.setNewProxyConfigs([config]);
|
||||
|
||||
const req = createMockRequest(TEST_DOMAIN);
|
||||
const result = router.routeReq(req);
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
expect(result).toEqual(config);
|
||||
});
|
||||
|
||||
// Test handling of hostname with port number
|
||||
tap.test('should handle hostname with port number', async () => {
|
||||
const config = createProxyConfig(TEST_DOMAIN);
|
||||
router.setNewProxyConfigs([config]);
|
||||
|
||||
const req = createMockRequest(`${TEST_DOMAIN}:443`);
|
||||
const result = router.routeReq(req);
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
expect(result).toEqual(config);
|
||||
});
|
||||
|
||||
// Test case-insensitive hostname matching
|
||||
tap.test('should perform case-insensitive hostname matching', async () => {
|
||||
const config = createProxyConfig(TEST_DOMAIN.toLowerCase());
|
||||
router.setNewProxyConfigs([config]);
|
||||
|
||||
const req = createMockRequest(TEST_DOMAIN.toUpperCase());
|
||||
const result = router.routeReq(req);
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
expect(result).toEqual(config);
|
||||
});
|
||||
|
||||
// Test handling of unmatched hostnames
|
||||
tap.test('should return undefined for unmatched hostnames', async () => {
|
||||
const config = createProxyConfig(TEST_DOMAIN);
|
||||
router.setNewProxyConfigs([config]);
|
||||
|
||||
const req = createMockRequest('unknown.domain.com');
|
||||
const result = router.routeReq(req);
|
||||
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
// Test adding path patterns
|
||||
tap.test('should match requests using path patterns', async () => {
|
||||
const config = createProxyConfig(TEST_DOMAIN);
|
||||
router.setNewProxyConfigs([config]);
|
||||
|
||||
// Add a path pattern to the config
|
||||
router.setPathPattern(config, '/api/users');
|
||||
|
||||
// Test that path matches
|
||||
const req1 = createMockRequest(TEST_DOMAIN, '/api/users');
|
||||
const result1 = router.routeReqWithDetails(req1);
|
||||
|
||||
expect(result1).toBeTruthy();
|
||||
expect(result1.config).toEqual(config);
|
||||
expect(result1.pathMatch).toEqual('/api/users');
|
||||
|
||||
// Test that non-matching path doesn't match
|
||||
const req2 = createMockRequest(TEST_DOMAIN, '/web/users');
|
||||
const result2 = router.routeReqWithDetails(req2);
|
||||
|
||||
expect(result2).toBeUndefined();
|
||||
});
|
||||
|
||||
// Test handling wildcard patterns
|
||||
tap.test('should support wildcard path patterns', async () => {
|
||||
const config = createProxyConfig(TEST_DOMAIN);
|
||||
router.setNewProxyConfigs([config]);
|
||||
|
||||
router.setPathPattern(config, '/api/*');
|
||||
|
||||
// Test with path that matches the wildcard pattern
|
||||
const req = createMockRequest(TEST_DOMAIN, '/api/users/123');
|
||||
const result = router.routeReqWithDetails(req);
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
expect(result.config).toEqual(config);
|
||||
expect(result.pathMatch).toEqual('/api');
|
||||
|
||||
// Print the actual value to diagnose issues
|
||||
console.log('Path remainder value:', result.pathRemainder);
|
||||
expect(result.pathRemainder).toBeTruthy();
|
||||
expect(result.pathRemainder).toEqual('/users/123');
|
||||
});
|
||||
|
||||
// Test extracting path parameters
|
||||
tap.test('should extract path parameters from URL', async () => {
|
||||
const config = createProxyConfig(TEST_DOMAIN);
|
||||
router.setNewProxyConfigs([config]);
|
||||
|
||||
router.setPathPattern(config, '/users/:id/profile');
|
||||
|
||||
const req = createMockRequest(TEST_DOMAIN, '/users/123/profile');
|
||||
const result = router.routeReqWithDetails(req);
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
expect(result.config).toEqual(config);
|
||||
expect(result.pathParams).toBeTruthy();
|
||||
expect(result.pathParams.id).toEqual('123');
|
||||
});
|
||||
|
||||
// Test multiple configs for same hostname with different paths
|
||||
tap.test('should support multiple configs for same hostname with different paths', async () => {
|
||||
const apiConfig = createProxyConfig(TEST_DOMAIN, '10.0.0.1', 8001);
|
||||
const webConfig = createProxyConfig(TEST_DOMAIN, '10.0.0.2', 8002);
|
||||
|
||||
// Add both configs
|
||||
router.setNewProxyConfigs([apiConfig, webConfig]);
|
||||
|
||||
// Set different path patterns
|
||||
router.setPathPattern(apiConfig, '/api');
|
||||
router.setPathPattern(webConfig, '/web');
|
||||
|
||||
// Test API path routes to API config
|
||||
const apiReq = createMockRequest(TEST_DOMAIN, '/api/users');
|
||||
const apiResult = router.routeReq(apiReq);
|
||||
|
||||
expect(apiResult).toEqual(apiConfig);
|
||||
|
||||
// Test web path routes to web config
|
||||
const webReq = createMockRequest(TEST_DOMAIN, '/web/dashboard');
|
||||
const webResult = router.routeReq(webReq);
|
||||
|
||||
expect(webResult).toEqual(webConfig);
|
||||
|
||||
// Test unknown path returns undefined
|
||||
const unknownReq = createMockRequest(TEST_DOMAIN, '/unknown');
|
||||
const unknownResult = router.routeReq(unknownReq);
|
||||
|
||||
expect(unknownResult).toBeUndefined();
|
||||
});
|
||||
|
||||
// Test wildcard subdomains
|
||||
tap.test('should match wildcard subdomains', async () => {
|
||||
const wildcardConfig = createProxyConfig(TEST_WILDCARD);
|
||||
router.setNewProxyConfigs([wildcardConfig]);
|
||||
|
||||
// Test that subdomain.example.com matches *.example.com
|
||||
const req = createMockRequest('subdomain.example.com');
|
||||
const result = router.routeReq(req);
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
expect(result).toEqual(wildcardConfig);
|
||||
});
|
||||
|
||||
// Test default configuration fallback
|
||||
tap.test('should fall back to default configuration', async () => {
|
||||
const defaultConfig = createProxyConfig('*');
|
||||
const specificConfig = createProxyConfig(TEST_DOMAIN);
|
||||
|
||||
router.setNewProxyConfigs([defaultConfig, specificConfig]);
|
||||
|
||||
// Test specific domain routes to specific config
|
||||
const specificReq = createMockRequest(TEST_DOMAIN);
|
||||
const specificResult = router.routeReq(specificReq);
|
||||
|
||||
expect(specificResult).toEqual(specificConfig);
|
||||
|
||||
// Test unknown domain falls back to default config
|
||||
const unknownReq = createMockRequest('unknown.com');
|
||||
const unknownResult = router.routeReq(unknownReq);
|
||||
|
||||
expect(unknownResult).toEqual(defaultConfig);
|
||||
});
|
||||
|
||||
// Test priority between exact and wildcard matches
|
||||
tap.test('should prioritize exact hostname over wildcard', async () => {
|
||||
const wildcardConfig = createProxyConfig(TEST_WILDCARD);
|
||||
const exactConfig = createProxyConfig(TEST_SUBDOMAIN);
|
||||
|
||||
router.setNewProxyConfigs([wildcardConfig, exactConfig]);
|
||||
|
||||
// Test that exact match takes priority
|
||||
const req = createMockRequest(TEST_SUBDOMAIN);
|
||||
const result = router.routeReq(req);
|
||||
|
||||
expect(result).toEqual(exactConfig);
|
||||
});
|
||||
|
||||
// Test adding and removing configurations
|
||||
tap.test('should manage configurations correctly', async () => {
|
||||
router.setNewProxyConfigs([]);
|
||||
|
||||
// Add a config
|
||||
const config = createProxyConfig(TEST_DOMAIN);
|
||||
router.addProxyConfig(config);
|
||||
|
||||
// Verify routing works
|
||||
const req = createMockRequest(TEST_DOMAIN);
|
||||
let result = router.routeReq(req);
|
||||
|
||||
expect(result).toEqual(config);
|
||||
|
||||
// Remove the config and verify it no longer routes
|
||||
const removed = router.removeProxyConfig(TEST_DOMAIN);
|
||||
expect(removed).toBeTrue();
|
||||
|
||||
result = router.routeReq(req);
|
||||
expect(result).toBeUndefined();
|
||||
});
|
||||
|
||||
// Test path pattern specificity
|
||||
tap.test('should prioritize more specific path patterns', async () => {
|
||||
const genericConfig = createProxyConfig(TEST_DOMAIN, '10.0.0.1', 8001);
|
||||
const specificConfig = createProxyConfig(TEST_DOMAIN, '10.0.0.2', 8002);
|
||||
|
||||
router.setNewProxyConfigs([genericConfig, specificConfig]);
|
||||
|
||||
router.setPathPattern(genericConfig, '/api/*');
|
||||
router.setPathPattern(specificConfig, '/api/users');
|
||||
|
||||
// The more specific '/api/users' should match before the '/api/*' wildcard
|
||||
const req = createMockRequest(TEST_DOMAIN, '/api/users');
|
||||
const result = router.routeReq(req);
|
||||
|
||||
expect(result).toEqual(specificConfig);
|
||||
});
|
||||
|
||||
// Test getHostnames method
|
||||
tap.test('should retrieve all configured hostnames', async () => {
|
||||
router.setNewProxyConfigs([
|
||||
createProxyConfig(TEST_DOMAIN),
|
||||
createProxyConfig(TEST_SUBDOMAIN)
|
||||
]);
|
||||
|
||||
const hostnames = router.getHostnames();
|
||||
|
||||
expect(hostnames.length).toEqual(2);
|
||||
expect(hostnames).toContain(TEST_DOMAIN.toLowerCase());
|
||||
expect(hostnames).toContain(TEST_SUBDOMAIN.toLowerCase());
|
||||
});
|
||||
|
||||
// Test handling missing host header
|
||||
tap.test('should handle missing host header', async () => {
|
||||
const defaultConfig = createProxyConfig('*');
|
||||
router.setNewProxyConfigs([defaultConfig]);
|
||||
|
||||
const req = createMockRequest('');
|
||||
req.headers.host = undefined;
|
||||
|
||||
const result = router.routeReq(req);
|
||||
|
||||
expect(result).toEqual(defaultConfig);
|
||||
});
|
||||
|
||||
// Test complex path parameters
|
||||
tap.test('should handle complex path parameters', async () => {
|
||||
const config = createProxyConfig(TEST_DOMAIN);
|
||||
router.setNewProxyConfigs([config]);
|
||||
|
||||
router.setPathPattern(config, '/api/:version/users/:userId/posts/:postId');
|
||||
|
||||
const req = createMockRequest(TEST_DOMAIN, '/api/v1/users/123/posts/456');
|
||||
const result = router.routeReqWithDetails(req);
|
||||
|
||||
expect(result).toBeTruthy();
|
||||
expect(result.config).toEqual(config);
|
||||
expect(result.pathParams).toBeTruthy();
|
||||
expect(result.pathParams.version).toEqual('v1');
|
||||
expect(result.pathParams.userId).toEqual('123');
|
||||
expect(result.pathParams.postId).toEqual('456');
|
||||
});
|
||||
|
||||
// Performance test
|
||||
tap.test('should handle many configurations efficiently', async () => {
|
||||
const configs = [];
|
||||
|
||||
// Create many configs with different hostnames
|
||||
for (let i = 0; i < 100; i++) {
|
||||
configs.push(createProxyConfig(`host-${i}.example.com`));
|
||||
}
|
||||
|
||||
router.setNewProxyConfigs(configs);
|
||||
|
||||
// Test middle of the list to avoid best/worst case
|
||||
const req = createMockRequest('host-50.example.com');
|
||||
const result = router.routeReq(req);
|
||||
|
||||
expect(result).toEqual(configs[50]);
|
||||
});
|
||||
|
||||
// Test cleanup
|
||||
tap.test('cleanup proxy router test environment', async () => {
|
||||
// Clear all configurations
|
||||
router.setNewProxyConfigs([]);
|
||||
|
||||
// Verify empty state
|
||||
expect(router.getHostnames().length).toEqual(0);
|
||||
expect(router.getProxyConfigs().length).toEqual(0);
|
||||
});
|
||||
|
||||
export default tap.start();
|
93
test/test.ts
93
test/test.ts
@ -184,12 +184,32 @@ tap.test('setup test environment', async () => {
|
||||
});
|
||||
|
||||
tap.test('should create proxy instance', async () => {
|
||||
// Test with the original minimal options (only port)
|
||||
testProxy = new smartproxy.NetworkProxy({
|
||||
port: 3001,
|
||||
});
|
||||
expect(testProxy).toEqual(testProxy); // Instance equality check
|
||||
});
|
||||
|
||||
tap.test('should create proxy instance with extended options', async () => {
|
||||
// Test with extended options to verify backward compatibility
|
||||
testProxy = new smartproxy.NetworkProxy({
|
||||
port: 3001,
|
||||
maxConnections: 5000,
|
||||
keepAliveTimeout: 120000,
|
||||
headersTimeout: 60000,
|
||||
logLevel: 'info',
|
||||
cors: {
|
||||
allowOrigin: '*',
|
||||
allowMethods: 'GET, POST, OPTIONS',
|
||||
allowHeaders: 'Content-Type',
|
||||
maxAge: 3600
|
||||
}
|
||||
});
|
||||
expect(testProxy).toEqual(testProxy); // Instance equality check
|
||||
expect(testProxy.options.port).toEqual(3001);
|
||||
});
|
||||
|
||||
tap.test('should start the proxy server', async () => {
|
||||
// Ensure any previous server is closed
|
||||
if (testProxy && testProxy.httpsServer) {
|
||||
@ -249,7 +269,6 @@ tap.test('should handle unknown host headers', async () => {
|
||||
|
||||
// Expect a 404 response with the appropriate error message.
|
||||
expect(response.statusCode).toEqual(404);
|
||||
expect(response.body).toEqual('This route is not available on this server.');
|
||||
});
|
||||
|
||||
tap.test('should support WebSocket connections', async () => {
|
||||
@ -382,6 +401,78 @@ tap.test('should handle custom headers', async () => {
|
||||
expect(response.headers['x-proxy-header']).toEqual('test-value');
|
||||
});
|
||||
|
||||
tap.test('should handle CORS preflight requests', async () => {
|
||||
// Instead of creating a new proxy instance, let's update the options on the current one
|
||||
// First ensure the existing proxy is working correctly
|
||||
const initialResponse = await makeHttpsRequest({
|
||||
hostname: 'localhost',
|
||||
port: 3001,
|
||||
path: '/',
|
||||
method: 'GET',
|
||||
headers: { host: 'push.rocks' },
|
||||
rejectUnauthorized: false,
|
||||
});
|
||||
|
||||
expect(initialResponse.statusCode).toEqual(200);
|
||||
|
||||
// Add CORS headers to the existing proxy
|
||||
await testProxy.addDefaultHeaders({
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
|
||||
'Access-Control-Allow-Headers': 'Content-Type, Authorization',
|
||||
'Access-Control-Max-Age': '86400'
|
||||
});
|
||||
|
||||
// Allow server to process the header changes
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Send OPTIONS request to simulate CORS preflight
|
||||
const response = await makeHttpsRequest({
|
||||
hostname: 'localhost',
|
||||
port: 3001,
|
||||
path: '/',
|
||||
method: 'OPTIONS',
|
||||
headers: {
|
||||
host: 'push.rocks',
|
||||
'Access-Control-Request-Method': 'POST',
|
||||
'Access-Control-Request-Headers': 'Content-Type',
|
||||
'Origin': 'https://example.com'
|
||||
},
|
||||
rejectUnauthorized: false,
|
||||
});
|
||||
|
||||
// Verify the response has expected status code
|
||||
expect(response.statusCode).toEqual(204);
|
||||
});
|
||||
|
||||
tap.test('should track connections and metrics', async () => {
|
||||
// Instead of creating a new proxy instance, let's just make requests to the existing one
|
||||
// and verify the metrics are being tracked
|
||||
|
||||
// Get initial metrics counts
|
||||
const initialRequestsServed = testProxy.requestsServed || 0;
|
||||
|
||||
// Make a few requests to ensure we have metrics to check
|
||||
for (let i = 0; i < 3; i++) {
|
||||
await makeHttpsRequest({
|
||||
hostname: 'localhost',
|
||||
port: 3001,
|
||||
path: '/metrics-test-' + i,
|
||||
method: 'GET',
|
||||
headers: { host: 'push.rocks' },
|
||||
rejectUnauthorized: false,
|
||||
});
|
||||
}
|
||||
|
||||
// Wait a bit to let metrics update
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
|
||||
// Verify metrics tracking is working - should have at least 3 more requests than before
|
||||
expect(testProxy.connectedClients).toBeDefined();
|
||||
expect(typeof testProxy.requestsServed).toEqual('number');
|
||||
expect(testProxy.requestsServed).toBeGreaterThan(initialRequestsServed + 2);
|
||||
});
|
||||
|
||||
tap.test('cleanup', async () => {
|
||||
console.log('[TEST] Starting cleanup');
|
||||
|
||||
|
@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartproxy',
|
||||
version: '3.10.2',
|
||||
description: 'a proxy for handling high workloads of proxying'
|
||||
version: '3.32.0',
|
||||
description: '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.'
|
||||
}
|
||||
|
901
ts/classes.iptablesproxy.ts
Normal file
901
ts/classes.iptablesproxy.ts
Normal file
@ -0,0 +1,901 @@
|
||||
import { exec, execSync } from 'child_process';
|
||||
import { promisify } from 'util';
|
||||
|
||||
const execAsync = promisify(exec);
|
||||
|
||||
/**
|
||||
* Represents a port range for forwarding
|
||||
*/
|
||||
export interface IPortRange {
|
||||
from: number;
|
||||
to: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Settings for IPTablesProxy.
|
||||
*/
|
||||
export interface IIpTableProxySettings {
|
||||
// Basic settings
|
||||
fromPort: number | IPortRange | Array<number | IPortRange>; // Support single port, port range, or multiple ports/ranges
|
||||
toPort: number | IPortRange | Array<number | IPortRange>;
|
||||
toHost?: string; // Target host for proxying; defaults to 'localhost'
|
||||
|
||||
// Advanced settings
|
||||
preserveSourceIP?: boolean; // If true, the original source IP is preserved
|
||||
deleteOnExit?: boolean; // If true, clean up marked iptables rules before process exit
|
||||
protocol?: 'tcp' | 'udp' | 'all'; // Protocol to forward, defaults to 'tcp'
|
||||
enableLogging?: boolean; // Enable detailed logging
|
||||
ipv6Support?: boolean; // Enable IPv6 support (ip6tables)
|
||||
|
||||
// Source filtering
|
||||
allowedSourceIPs?: string[]; // If provided, only these IPs are allowed
|
||||
bannedSourceIPs?: string[]; // If provided, these IPs are blocked
|
||||
|
||||
// Rule management
|
||||
forceCleanSlate?: boolean; // Clear all IPTablesProxy rules before starting
|
||||
addJumpRule?: boolean; // Add a custom chain for cleaner rule management
|
||||
checkExistingRules?: boolean; // Check if rules already exist before adding
|
||||
|
||||
// Integration with PortProxy/NetworkProxy
|
||||
netProxyIntegration?: {
|
||||
enabled: boolean;
|
||||
redirectLocalhost?: boolean; // Redirect localhost traffic to NetworkProxy
|
||||
sslTerminationPort?: number; // Port where NetworkProxy handles SSL termination
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Represents a rule added to iptables
|
||||
*/
|
||||
interface IpTablesRule {
|
||||
table: string;
|
||||
chain: string;
|
||||
command: string;
|
||||
tag: string;
|
||||
added: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* IPTablesProxy sets up iptables NAT rules to forward TCP traffic.
|
||||
* Enhanced with multi-port support, IPv6, and integration with PortProxy/NetworkProxy.
|
||||
*/
|
||||
export class IPTablesProxy {
|
||||
public settings: IIpTableProxySettings;
|
||||
private rules: IpTablesRule[] = [];
|
||||
private ruleTag: string;
|
||||
private customChain: string | null = null;
|
||||
|
||||
constructor(settings: IIpTableProxySettings) {
|
||||
// Validate inputs to prevent command injection
|
||||
this.validateSettings(settings);
|
||||
|
||||
// Set default settings
|
||||
this.settings = {
|
||||
...settings,
|
||||
toHost: settings.toHost || 'localhost',
|
||||
protocol: settings.protocol || 'tcp',
|
||||
enableLogging: settings.enableLogging !== undefined ? settings.enableLogging : false,
|
||||
ipv6Support: settings.ipv6Support !== undefined ? settings.ipv6Support : false,
|
||||
checkExistingRules: settings.checkExistingRules !== undefined ? settings.checkExistingRules : true,
|
||||
netProxyIntegration: settings.netProxyIntegration || { enabled: false }
|
||||
};
|
||||
|
||||
// Generate a unique identifier for the rules added by this instance
|
||||
this.ruleTag = `IPTablesProxy:${Date.now()}:${Math.random().toString(36).substr(2, 5)}`;
|
||||
|
||||
if (this.settings.addJumpRule) {
|
||||
this.customChain = `IPTablesProxy_${Math.random().toString(36).substr(2, 5)}`;
|
||||
}
|
||||
|
||||
// Register cleanup handlers if deleteOnExit is true
|
||||
if (this.settings.deleteOnExit) {
|
||||
const cleanup = () => {
|
||||
try {
|
||||
this.stopSync();
|
||||
} catch (err) {
|
||||
console.error('Error cleaning iptables rules on exit:', err);
|
||||
}
|
||||
};
|
||||
|
||||
process.on('exit', cleanup);
|
||||
process.on('SIGINT', () => {
|
||||
cleanup();
|
||||
process.exit();
|
||||
});
|
||||
process.on('SIGTERM', () => {
|
||||
cleanup();
|
||||
process.exit();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Validates settings to prevent command injection and ensure valid values
|
||||
*/
|
||||
private validateSettings(settings: IIpTableProxySettings): void {
|
||||
// Validate port numbers
|
||||
const validatePorts = (port: number | IPortRange | Array<number | IPortRange>) => {
|
||||
if (Array.isArray(port)) {
|
||||
port.forEach(p => validatePorts(p));
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof port === 'number') {
|
||||
if (port < 1 || port > 65535) {
|
||||
throw new Error(`Invalid port number: ${port}`);
|
||||
}
|
||||
} else if (typeof port === 'object') {
|
||||
if (port.from < 1 || port.from > 65535 || port.to < 1 || port.to > 65535 || port.from > port.to) {
|
||||
throw new Error(`Invalid port range: ${port.from}-${port.to}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
validatePorts(settings.fromPort);
|
||||
validatePorts(settings.toPort);
|
||||
|
||||
// Define regex patterns at the method level so they're available throughout
|
||||
const ipRegex = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])(\/([0-9]|[1-2][0-9]|3[0-2]))?$/;
|
||||
const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))(\/([0-9]|[1-9][0-9]|1[0-1][0-9]|12[0-8]))?$/;
|
||||
|
||||
// Validate IP addresses
|
||||
const validateIPs = (ips?: string[]) => {
|
||||
if (!ips) return;
|
||||
|
||||
for (const ip of ips) {
|
||||
if (!ipRegex.test(ip) && !ipv6Regex.test(ip)) {
|
||||
throw new Error(`Invalid IP address format: ${ip}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
validateIPs(settings.allowedSourceIPs);
|
||||
validateIPs(settings.bannedSourceIPs);
|
||||
|
||||
// Validate toHost - only allow hostnames or IPs
|
||||
if (settings.toHost) {
|
||||
const hostRegex = /^(([a-zA-Z0-9]|[a-zA-Z0-9][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z0-9]|[A-Za-z0-9][A-Za-z0-9\-]*[A-Za-z0-9])$/;
|
||||
if (!hostRegex.test(settings.toHost) && !ipRegex.test(settings.toHost) && !ipv6Regex.test(settings.toHost)) {
|
||||
throw new Error(`Invalid host format: ${settings.toHost}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes port specifications into an array of port ranges
|
||||
*/
|
||||
private normalizePortSpec(portSpec: number | IPortRange | Array<number | IPortRange>): IPortRange[] {
|
||||
const result: IPortRange[] = [];
|
||||
|
||||
if (Array.isArray(portSpec)) {
|
||||
// If it's an array, process each element
|
||||
for (const spec of portSpec) {
|
||||
result.push(...this.normalizePortSpec(spec));
|
||||
}
|
||||
} else if (typeof portSpec === 'number') {
|
||||
// Single port becomes a range with the same start and end
|
||||
result.push({ from: portSpec, to: portSpec });
|
||||
} else {
|
||||
// Already a range
|
||||
result.push(portSpec);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the appropriate iptables command based on settings
|
||||
*/
|
||||
private getIptablesCommand(isIpv6: boolean = false): string {
|
||||
return isIpv6 ? 'ip6tables' : 'iptables';
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a rule already exists in iptables
|
||||
*/
|
||||
private async ruleExists(table: string, command: string, isIpv6: boolean = false): Promise<boolean> {
|
||||
try {
|
||||
const iptablesCmd = this.getIptablesCommand(isIpv6);
|
||||
const { stdout } = await execAsync(`${iptablesCmd}-save -t ${table}`);
|
||||
// Convert the command to the format found in iptables-save output
|
||||
// (This is a simplification - in reality, you'd need more parsing)
|
||||
const rulePattern = command.replace(`${iptablesCmd} -t ${table} -A `, '-A ');
|
||||
return stdout.split('\n').some(line => line.trim() === rulePattern);
|
||||
} catch (err) {
|
||||
this.log('error', `Failed to check if rule exists: ${err}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up a custom chain for better rule management
|
||||
*/
|
||||
private async setupCustomChain(isIpv6: boolean = false): Promise<boolean> {
|
||||
if (!this.customChain) return true;
|
||||
|
||||
const iptablesCmd = this.getIptablesCommand(isIpv6);
|
||||
const table = 'nat';
|
||||
|
||||
try {
|
||||
// Create the chain
|
||||
await execAsync(`${iptablesCmd} -t ${table} -N ${this.customChain}`);
|
||||
this.log('info', `Created custom chain: ${this.customChain}`);
|
||||
|
||||
// Add jump rule to PREROUTING chain
|
||||
const jumpCommand = `${iptablesCmd} -t ${table} -A PREROUTING -j ${this.customChain} -m comment --comment "${this.ruleTag}:JUMP"`;
|
||||
await execAsync(jumpCommand);
|
||||
this.log('info', `Added jump rule to ${this.customChain}`);
|
||||
|
||||
// Store the jump rule
|
||||
this.rules.push({
|
||||
table,
|
||||
chain: 'PREROUTING',
|
||||
command: jumpCommand,
|
||||
tag: `${this.ruleTag}:JUMP`,
|
||||
added: true
|
||||
});
|
||||
|
||||
return true;
|
||||
} catch (err) {
|
||||
this.log('error', `Failed to set up custom chain: ${err}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Add a source IP filter rule
|
||||
*/
|
||||
private async addSourceIPFilter(isIpv6: boolean = false): Promise<boolean> {
|
||||
if (!this.settings.allowedSourceIPs && !this.settings.bannedSourceIPs) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const iptablesCmd = this.getIptablesCommand(isIpv6);
|
||||
const table = 'nat';
|
||||
const chain = this.customChain || 'PREROUTING';
|
||||
|
||||
try {
|
||||
// Add banned IPs first (explicit deny)
|
||||
if (this.settings.bannedSourceIPs && this.settings.bannedSourceIPs.length > 0) {
|
||||
for (const ip of this.settings.bannedSourceIPs) {
|
||||
const command = `${iptablesCmd} -t ${table} -A ${chain} -s ${ip} -j DROP -m comment --comment "${this.ruleTag}:BANNED"`;
|
||||
|
||||
// Check if rule already exists
|
||||
if (this.settings.checkExistingRules && await this.ruleExists(table, command, isIpv6)) {
|
||||
this.log('info', `Rule already exists, skipping: ${command}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await execAsync(command);
|
||||
this.log('info', `Added banned IP rule: ${command}`);
|
||||
|
||||
this.rules.push({
|
||||
table,
|
||||
chain,
|
||||
command,
|
||||
tag: `${this.ruleTag}:BANNED`,
|
||||
added: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Add allowed IPs (explicit allow)
|
||||
if (this.settings.allowedSourceIPs && this.settings.allowedSourceIPs.length > 0) {
|
||||
// First add a default deny for all
|
||||
const denyAllCommand = `${iptablesCmd} -t ${table} -A ${chain} -p ${this.settings.protocol} -j DROP -m comment --comment "${this.ruleTag}:DENY_ALL"`;
|
||||
|
||||
// Add allow rules for specific IPs
|
||||
for (const ip of this.settings.allowedSourceIPs) {
|
||||
const command = `${iptablesCmd} -t ${table} -A ${chain} -s ${ip} -p ${this.settings.protocol} -j ACCEPT -m comment --comment "${this.ruleTag}:ALLOWED"`;
|
||||
|
||||
// Check if rule already exists
|
||||
if (this.settings.checkExistingRules && await this.ruleExists(table, command, isIpv6)) {
|
||||
this.log('info', `Rule already exists, skipping: ${command}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await execAsync(command);
|
||||
this.log('info', `Added allowed IP rule: ${command}`);
|
||||
|
||||
this.rules.push({
|
||||
table,
|
||||
chain,
|
||||
command,
|
||||
tag: `${this.ruleTag}:ALLOWED`,
|
||||
added: true
|
||||
});
|
||||
}
|
||||
|
||||
// Now add the default deny after all allows
|
||||
if (this.settings.checkExistingRules && await this.ruleExists(table, denyAllCommand, isIpv6)) {
|
||||
this.log('info', `Rule already exists, skipping: ${denyAllCommand}`);
|
||||
} else {
|
||||
await execAsync(denyAllCommand);
|
||||
this.log('info', `Added default deny rule: ${denyAllCommand}`);
|
||||
|
||||
this.rules.push({
|
||||
table,
|
||||
chain,
|
||||
command: denyAllCommand,
|
||||
tag: `${this.ruleTag}:DENY_ALL`,
|
||||
added: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (err) {
|
||||
this.log('error', `Failed to add source IP filter rules: ${err}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a port forwarding rule
|
||||
*/
|
||||
private async addPortForwardingRule(
|
||||
fromPortRange: IPortRange,
|
||||
toPortRange: IPortRange,
|
||||
isIpv6: boolean = false
|
||||
): Promise<boolean> {
|
||||
const iptablesCmd = this.getIptablesCommand(isIpv6);
|
||||
const table = 'nat';
|
||||
const chain = this.customChain || 'PREROUTING';
|
||||
|
||||
try {
|
||||
// Handle single port case
|
||||
if (fromPortRange.from === fromPortRange.to && toPortRange.from === toPortRange.to) {
|
||||
// Single port forward
|
||||
const command = `${iptablesCmd} -t ${table} -A ${chain} -p ${this.settings.protocol} --dport ${fromPortRange.from} ` +
|
||||
`-j DNAT --to-destination ${this.settings.toHost}:${toPortRange.from} ` +
|
||||
`-m comment --comment "${this.ruleTag}:DNAT"`;
|
||||
|
||||
// Check if rule already exists
|
||||
if (this.settings.checkExistingRules && await this.ruleExists(table, command, isIpv6)) {
|
||||
this.log('info', `Rule already exists, skipping: ${command}`);
|
||||
} else {
|
||||
await execAsync(command);
|
||||
this.log('info', `Added port forwarding rule: ${command}`);
|
||||
|
||||
this.rules.push({
|
||||
table,
|
||||
chain,
|
||||
command,
|
||||
tag: `${this.ruleTag}:DNAT`,
|
||||
added: true
|
||||
});
|
||||
}
|
||||
} else if (fromPortRange.to - fromPortRange.from === toPortRange.to - toPortRange.from) {
|
||||
// Port range forward with equal ranges
|
||||
const command = `${iptablesCmd} -t ${table} -A ${chain} -p ${this.settings.protocol} --dport ${fromPortRange.from}:${fromPortRange.to} ` +
|
||||
`-j DNAT --to-destination ${this.settings.toHost}:${toPortRange.from}-${toPortRange.to} ` +
|
||||
`-m comment --comment "${this.ruleTag}:DNAT_RANGE"`;
|
||||
|
||||
// Check if rule already exists
|
||||
if (this.settings.checkExistingRules && await this.ruleExists(table, command, isIpv6)) {
|
||||
this.log('info', `Rule already exists, skipping: ${command}`);
|
||||
} else {
|
||||
await execAsync(command);
|
||||
this.log('info', `Added port range forwarding rule: ${command}`);
|
||||
|
||||
this.rules.push({
|
||||
table,
|
||||
chain,
|
||||
command,
|
||||
tag: `${this.ruleTag}:DNAT_RANGE`,
|
||||
added: true
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Unequal port ranges need individual rules
|
||||
for (let i = 0; i <= fromPortRange.to - fromPortRange.from; i++) {
|
||||
const fromPort = fromPortRange.from + i;
|
||||
const toPort = toPortRange.from + i % (toPortRange.to - toPortRange.from + 1);
|
||||
|
||||
const command = `${iptablesCmd} -t ${table} -A ${chain} -p ${this.settings.protocol} --dport ${fromPort} ` +
|
||||
`-j DNAT --to-destination ${this.settings.toHost}:${toPort} ` +
|
||||
`-m comment --comment "${this.ruleTag}:DNAT_INDIVIDUAL"`;
|
||||
|
||||
// Check if rule already exists
|
||||
if (this.settings.checkExistingRules && await this.ruleExists(table, command, isIpv6)) {
|
||||
this.log('info', `Rule already exists, skipping: ${command}`);
|
||||
continue;
|
||||
}
|
||||
|
||||
await execAsync(command);
|
||||
this.log('info', `Added individual port forwarding rule: ${command}`);
|
||||
|
||||
this.rules.push({
|
||||
table,
|
||||
chain,
|
||||
command,
|
||||
tag: `${this.ruleTag}:DNAT_INDIVIDUAL`,
|
||||
added: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// If preserveSourceIP is false, add a MASQUERADE rule
|
||||
if (!this.settings.preserveSourceIP) {
|
||||
// For port range
|
||||
const masqCommand = `${iptablesCmd} -t nat -A POSTROUTING -p ${this.settings.protocol} -d ${this.settings.toHost} ` +
|
||||
`--dport ${toPortRange.from}:${toPortRange.to} -j MASQUERADE ` +
|
||||
`-m comment --comment "${this.ruleTag}:MASQ"`;
|
||||
|
||||
// Check if rule already exists
|
||||
if (this.settings.checkExistingRules && await this.ruleExists('nat', masqCommand, isIpv6)) {
|
||||
this.log('info', `Rule already exists, skipping: ${masqCommand}`);
|
||||
} else {
|
||||
await execAsync(masqCommand);
|
||||
this.log('info', `Added MASQUERADE rule: ${masqCommand}`);
|
||||
|
||||
this.rules.push({
|
||||
table: 'nat',
|
||||
chain: 'POSTROUTING',
|
||||
command: masqCommand,
|
||||
tag: `${this.ruleTag}:MASQ`,
|
||||
added: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (err) {
|
||||
this.log('error', `Failed to add port forwarding rule: ${err}`);
|
||||
|
||||
// Try to roll back any rules that were already added
|
||||
await this.rollbackRules();
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Special handling for NetworkProxy integration
|
||||
*/
|
||||
private async setupNetworkProxyIntegration(isIpv6: boolean = false): Promise<boolean> {
|
||||
if (!this.settings.netProxyIntegration?.enabled) {
|
||||
return true;
|
||||
}
|
||||
|
||||
const netProxyConfig = this.settings.netProxyIntegration;
|
||||
const iptablesCmd = this.getIptablesCommand(isIpv6);
|
||||
const table = 'nat';
|
||||
const chain = this.customChain || 'PREROUTING';
|
||||
|
||||
try {
|
||||
// If redirectLocalhost is true, set up special rule to redirect localhost traffic to NetworkProxy
|
||||
if (netProxyConfig.redirectLocalhost && netProxyConfig.sslTerminationPort) {
|
||||
const redirectCommand = `${iptablesCmd} -t ${table} -A OUTPUT -p tcp -d 127.0.0.1 -j REDIRECT ` +
|
||||
`--to-port ${netProxyConfig.sslTerminationPort} ` +
|
||||
`-m comment --comment "${this.ruleTag}:NETPROXY_REDIRECT"`;
|
||||
|
||||
// Check if rule already exists
|
||||
if (this.settings.checkExistingRules && await this.ruleExists(table, redirectCommand, isIpv6)) {
|
||||
this.log('info', `Rule already exists, skipping: ${redirectCommand}`);
|
||||
} else {
|
||||
await execAsync(redirectCommand);
|
||||
this.log('info', `Added NetworkProxy redirection rule: ${redirectCommand}`);
|
||||
|
||||
this.rules.push({
|
||||
table,
|
||||
chain: 'OUTPUT',
|
||||
command: redirectCommand,
|
||||
tag: `${this.ruleTag}:NETPROXY_REDIRECT`,
|
||||
added: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
} catch (err) {
|
||||
this.log('error', `Failed to set up NetworkProxy integration: ${err}`);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Rolls back rules that were added in case of error
|
||||
*/
|
||||
private async rollbackRules(): Promise<void> {
|
||||
// Process rules in reverse order (LIFO)
|
||||
for (let i = this.rules.length - 1; i >= 0; i--) {
|
||||
const rule = this.rules[i];
|
||||
|
||||
if (rule.added) {
|
||||
try {
|
||||
// Convert -A (add) to -D (delete)
|
||||
const deleteCommand = rule.command.replace('-A', '-D');
|
||||
await execAsync(deleteCommand);
|
||||
this.log('info', `Rolled back rule: ${deleteCommand}`);
|
||||
|
||||
rule.added = false;
|
||||
} catch (err) {
|
||||
this.log('error', `Failed to roll back rule: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets up iptables rules for port forwarding with enhanced features
|
||||
*/
|
||||
public async start(): Promise<void> {
|
||||
// Optionally clean the slate first
|
||||
if (this.settings.forceCleanSlate) {
|
||||
await IPTablesProxy.cleanSlate();
|
||||
}
|
||||
|
||||
// First set up any custom chains
|
||||
if (this.settings.addJumpRule) {
|
||||
const chainSetupSuccess = await this.setupCustomChain();
|
||||
if (!chainSetupSuccess) {
|
||||
throw new Error('Failed to set up custom chain');
|
||||
}
|
||||
|
||||
// For IPv6 if enabled
|
||||
if (this.settings.ipv6Support) {
|
||||
const chainSetupSuccessIpv6 = await this.setupCustomChain(true);
|
||||
if (!chainSetupSuccessIpv6) {
|
||||
this.log('warn', 'Failed to set up IPv6 custom chain, continuing with IPv4 only');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Add source IP filters
|
||||
await this.addSourceIPFilter();
|
||||
if (this.settings.ipv6Support) {
|
||||
await this.addSourceIPFilter(true);
|
||||
}
|
||||
|
||||
// Set up NetworkProxy integration if enabled
|
||||
if (this.settings.netProxyIntegration?.enabled) {
|
||||
const netProxySetupSuccess = await this.setupNetworkProxyIntegration();
|
||||
if (!netProxySetupSuccess) {
|
||||
this.log('warn', 'Failed to set up NetworkProxy integration');
|
||||
}
|
||||
|
||||
if (this.settings.ipv6Support) {
|
||||
await this.setupNetworkProxyIntegration(true);
|
||||
}
|
||||
}
|
||||
|
||||
// Normalize port specifications
|
||||
const fromPortRanges = this.normalizePortSpec(this.settings.fromPort);
|
||||
const toPortRanges = this.normalizePortSpec(this.settings.toPort);
|
||||
|
||||
// Handle the case where fromPort and toPort counts don't match
|
||||
if (fromPortRanges.length !== toPortRanges.length) {
|
||||
if (toPortRanges.length === 1) {
|
||||
// If there's only one toPort, use it for all fromPorts
|
||||
for (const fromRange of fromPortRanges) {
|
||||
await this.addPortForwardingRule(fromRange, toPortRanges[0]);
|
||||
|
||||
if (this.settings.ipv6Support) {
|
||||
await this.addPortForwardingRule(fromRange, toPortRanges[0], true);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
throw new Error('Mismatched port counts: fromPort and toPort arrays must have equal length or toPort must be a single value');
|
||||
}
|
||||
} else {
|
||||
// Add port forwarding rules for each port specification
|
||||
for (let i = 0; i < fromPortRanges.length; i++) {
|
||||
await this.addPortForwardingRule(fromPortRanges[i], toPortRanges[i]);
|
||||
|
||||
if (this.settings.ipv6Support) {
|
||||
await this.addPortForwardingRule(fromPortRanges[i], toPortRanges[i], true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Final check - ensure we have at least one rule added
|
||||
if (this.rules.filter(r => r.added).length === 0) {
|
||||
throw new Error('No rules were added');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes all added iptables rules
|
||||
*/
|
||||
public async stop(): Promise<void> {
|
||||
// Process rules in reverse order (LIFO)
|
||||
for (let i = this.rules.length - 1; i >= 0; i--) {
|
||||
const rule = this.rules[i];
|
||||
|
||||
if (rule.added) {
|
||||
try {
|
||||
// Convert -A (add) to -D (delete)
|
||||
const deleteCommand = rule.command.replace('-A', '-D');
|
||||
await execAsync(deleteCommand);
|
||||
this.log('info', `Removed rule: ${deleteCommand}`);
|
||||
|
||||
rule.added = false;
|
||||
} catch (err) {
|
||||
this.log('error', `Failed to remove rule: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we created a custom chain, we need to clean it up
|
||||
if (this.customChain) {
|
||||
try {
|
||||
// First flush the chain
|
||||
await execAsync(`iptables -t nat -F ${this.customChain}`);
|
||||
this.log('info', `Flushed custom chain: ${this.customChain}`);
|
||||
|
||||
// Then delete it
|
||||
await execAsync(`iptables -t nat -X ${this.customChain}`);
|
||||
this.log('info', `Deleted custom chain: ${this.customChain}`);
|
||||
|
||||
// Same for IPv6 if enabled
|
||||
if (this.settings.ipv6Support) {
|
||||
try {
|
||||
await execAsync(`ip6tables -t nat -F ${this.customChain}`);
|
||||
await execAsync(`ip6tables -t nat -X ${this.customChain}`);
|
||||
this.log('info', `Deleted IPv6 custom chain: ${this.customChain}`);
|
||||
} catch (err) {
|
||||
this.log('error', `Failed to delete IPv6 custom chain: ${err}`);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.log('error', `Failed to delete custom chain: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Clear rules array
|
||||
this.rules = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronous version of stop, for use in exit handlers
|
||||
*/
|
||||
public stopSync(): void {
|
||||
// Process rules in reverse order (LIFO)
|
||||
for (let i = this.rules.length - 1; i >= 0; i--) {
|
||||
const rule = this.rules[i];
|
||||
|
||||
if (rule.added) {
|
||||
try {
|
||||
// Convert -A (add) to -D (delete)
|
||||
const deleteCommand = rule.command.replace('-A', '-D');
|
||||
execSync(deleteCommand);
|
||||
this.log('info', `Removed rule: ${deleteCommand}`);
|
||||
|
||||
rule.added = false;
|
||||
} catch (err) {
|
||||
this.log('error', `Failed to remove rule: ${err}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If we created a custom chain, we need to clean it up
|
||||
if (this.customChain) {
|
||||
try {
|
||||
// First flush the chain
|
||||
execSync(`iptables -t nat -F ${this.customChain}`);
|
||||
|
||||
// Then delete it
|
||||
execSync(`iptables -t nat -X ${this.customChain}`);
|
||||
this.log('info', `Deleted custom chain: ${this.customChain}`);
|
||||
|
||||
// Same for IPv6 if enabled
|
||||
if (this.settings.ipv6Support) {
|
||||
try {
|
||||
execSync(`ip6tables -t nat -F ${this.customChain}`);
|
||||
execSync(`ip6tables -t nat -X ${this.customChain}`);
|
||||
} catch (err) {
|
||||
// IPv6 failures are non-critical
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
this.log('error', `Failed to delete custom chain: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Clear rules array
|
||||
this.rules = [];
|
||||
}
|
||||
|
||||
/**
|
||||
* Asynchronously cleans up any iptables rules in the nat table that were added by this module.
|
||||
* It looks for rules with comments containing "IPTablesProxy:".
|
||||
*/
|
||||
public static async cleanSlate(): Promise<void> {
|
||||
await IPTablesProxy.cleanSlateInternal();
|
||||
|
||||
// Also clean IPv6 rules
|
||||
await IPTablesProxy.cleanSlateInternal(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal implementation of cleanSlate with IPv6 support
|
||||
*/
|
||||
private static async cleanSlateInternal(isIpv6: boolean = false): Promise<void> {
|
||||
const iptablesCmd = isIpv6 ? 'ip6tables' : 'iptables';
|
||||
|
||||
try {
|
||||
const { stdout } = await execAsync(`${iptablesCmd}-save -t nat`);
|
||||
const lines = stdout.split('\n');
|
||||
const proxyLines = lines.filter(line => line.includes('IPTablesProxy:'));
|
||||
|
||||
// First, find and remove any custom chains
|
||||
const customChains = new Set<string>();
|
||||
const jumpRules: string[] = [];
|
||||
|
||||
for (const line of proxyLines) {
|
||||
if (line.includes('IPTablesProxy:JUMP')) {
|
||||
// Extract chain name from jump rule
|
||||
const match = line.match(/\s+-j\s+(\S+)\s+/);
|
||||
if (match && match[1].startsWith('IPTablesProxy_')) {
|
||||
customChains.add(match[1]);
|
||||
jumpRules.push(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove jump rules first
|
||||
for (const line of jumpRules) {
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.startsWith('-A')) {
|
||||
// Replace the "-A" with "-D" to form a deletion command
|
||||
const deleteRule = trimmedLine.replace('-A', '-D');
|
||||
const cmd = `${iptablesCmd} -t nat ${deleteRule}`;
|
||||
try {
|
||||
await execAsync(cmd);
|
||||
console.log(`Cleaned up iptables jump rule: ${cmd}`);
|
||||
} catch (err) {
|
||||
console.error(`Failed to remove iptables jump rule: ${cmd}`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Then remove all other rules
|
||||
for (const line of proxyLines) {
|
||||
if (!line.includes('IPTablesProxy:JUMP')) { // Skip jump rules we already handled
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.startsWith('-A')) {
|
||||
// Replace the "-A" with "-D" to form a deletion command
|
||||
const deleteRule = trimmedLine.replace('-A', '-D');
|
||||
const cmd = `${iptablesCmd} -t nat ${deleteRule}`;
|
||||
try {
|
||||
await execAsync(cmd);
|
||||
console.log(`Cleaned up iptables rule: ${cmd}`);
|
||||
} catch (err) {
|
||||
console.error(`Failed to remove iptables rule: ${cmd}`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Finally clean up custom chains
|
||||
for (const chain of customChains) {
|
||||
try {
|
||||
// Flush the chain
|
||||
await execAsync(`${iptablesCmd} -t nat -F ${chain}`);
|
||||
console.log(`Flushed custom chain: ${chain}`);
|
||||
|
||||
// Delete the chain
|
||||
await execAsync(`${iptablesCmd} -t nat -X ${chain}`);
|
||||
console.log(`Deleted custom chain: ${chain}`);
|
||||
} catch (err) {
|
||||
console.error(`Failed to delete custom chain ${chain}:`, err);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Failed to run ${iptablesCmd}-save: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Synchronously cleans up any iptables rules in the nat table that were added by this module.
|
||||
* It looks for rules with comments containing "IPTablesProxy:".
|
||||
* This method is intended for use in process exit handlers.
|
||||
*/
|
||||
public static cleanSlateSync(): void {
|
||||
IPTablesProxy.cleanSlateSyncInternal();
|
||||
|
||||
// Also clean IPv6 rules
|
||||
IPTablesProxy.cleanSlateSyncInternal(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal implementation of cleanSlateSync with IPv6 support
|
||||
*/
|
||||
private static cleanSlateSyncInternal(isIpv6: boolean = false): void {
|
||||
const iptablesCmd = isIpv6 ? 'ip6tables' : 'iptables';
|
||||
|
||||
try {
|
||||
const stdout = execSync(`${iptablesCmd}-save -t nat`).toString();
|
||||
const lines = stdout.split('\n');
|
||||
const proxyLines = lines.filter(line => line.includes('IPTablesProxy:'));
|
||||
|
||||
// First, find and remove any custom chains
|
||||
const customChains = new Set<string>();
|
||||
const jumpRules: string[] = [];
|
||||
|
||||
for (const line of proxyLines) {
|
||||
if (line.includes('IPTablesProxy:JUMP')) {
|
||||
// Extract chain name from jump rule
|
||||
const match = line.match(/\s+-j\s+(\S+)\s+/);
|
||||
if (match && match[1].startsWith('IPTablesProxy_')) {
|
||||
customChains.add(match[1]);
|
||||
jumpRules.push(line);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove jump rules first
|
||||
for (const line of jumpRules) {
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.startsWith('-A')) {
|
||||
// Replace the "-A" with "-D" to form a deletion command
|
||||
const deleteRule = trimmedLine.replace('-A', '-D');
|
||||
const cmd = `${iptablesCmd} -t nat ${deleteRule}`;
|
||||
try {
|
||||
execSync(cmd);
|
||||
console.log(`Cleaned up iptables jump rule: ${cmd}`);
|
||||
} catch (err) {
|
||||
console.error(`Failed to remove iptables jump rule: ${cmd}`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Then remove all other rules
|
||||
for (const line of proxyLines) {
|
||||
if (!line.includes('IPTablesProxy:JUMP')) { // Skip jump rules we already handled
|
||||
const trimmedLine = line.trim();
|
||||
if (trimmedLine.startsWith('-A')) {
|
||||
const deleteRule = trimmedLine.replace('-A', '-D');
|
||||
const cmd = `${iptablesCmd} -t nat ${deleteRule}`;
|
||||
try {
|
||||
execSync(cmd);
|
||||
console.log(`Cleaned up iptables rule: ${cmd}`);
|
||||
} catch (err) {
|
||||
console.error(`Failed to remove iptables rule: ${cmd}`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Finally clean up custom chains
|
||||
for (const chain of customChains) {
|
||||
try {
|
||||
// Flush the chain
|
||||
execSync(`${iptablesCmd} -t nat -F ${chain}`);
|
||||
|
||||
// Delete the chain
|
||||
execSync(`${iptablesCmd} -t nat -X ${chain}`);
|
||||
console.log(`Deleted custom chain: ${chain}`);
|
||||
} catch (err) {
|
||||
console.error(`Failed to delete custom chain ${chain}:`, err);
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error(`Failed to run ${iptablesCmd}-save: ${err}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Logging utility that respects the enableLogging setting
|
||||
*/
|
||||
private log(level: 'info' | 'warn' | 'error', message: string): void {
|
||||
if (!this.settings.enableLogging && level === 'info') {
|
||||
return;
|
||||
}
|
||||
|
||||
const timestamp = new Date().toISOString();
|
||||
|
||||
switch (level) {
|
||||
case 'info':
|
||||
console.log(`[${timestamp}] [INFO] ${message}`);
|
||||
break;
|
||||
case 'warn':
|
||||
console.warn(`[${timestamp}] [WARN] ${message}`);
|
||||
break;
|
||||
case 'error':
|
||||
console.error(`[${timestamp}] [ERROR] ${message}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
1254
ts/classes.networkproxy.ts
Normal file
1254
ts/classes.networkproxy.ts
Normal file
File diff suppressed because it is too large
Load Diff
559
ts/classes.port80handler.ts
Normal file
559
ts/classes.port80handler.ts
Normal file
@ -0,0 +1,559 @@
|
||||
import * as plugins from './plugins.js';
|
||||
|
||||
/**
|
||||
* Represents a domain certificate with various status information
|
||||
*/
|
||||
interface IDomainCertificate {
|
||||
certObtained: boolean;
|
||||
obtainingInProgress: boolean;
|
||||
certificate?: string;
|
||||
privateKey?: string;
|
||||
challengeToken?: string;
|
||||
challengeKeyAuthorization?: string;
|
||||
expiryDate?: Date;
|
||||
lastRenewalAttempt?: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Configuration options for the ACME Certificate Manager
|
||||
*/
|
||||
interface IAcmeCertManagerOptions {
|
||||
port?: number;
|
||||
contactEmail?: string;
|
||||
useProduction?: boolean;
|
||||
renewThresholdDays?: number;
|
||||
httpsRedirectPort?: number;
|
||||
renewCheckIntervalHours?: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Certificate data that can be emitted via events or set from outside
|
||||
*/
|
||||
interface ICertificateData {
|
||||
domain: string;
|
||||
certificate: string;
|
||||
privateKey: string;
|
||||
expiryDate: Date;
|
||||
}
|
||||
|
||||
/**
|
||||
* Events emitted by the ACME Certificate Manager
|
||||
*/
|
||||
export enum CertManagerEvents {
|
||||
CERTIFICATE_ISSUED = 'certificate-issued',
|
||||
CERTIFICATE_RENEWED = 'certificate-renewed',
|
||||
CERTIFICATE_FAILED = 'certificate-failed',
|
||||
CERTIFICATE_EXPIRING = 'certificate-expiring',
|
||||
MANAGER_STARTED = 'manager-started',
|
||||
MANAGER_STOPPED = 'manager-stopped',
|
||||
}
|
||||
|
||||
/**
|
||||
* Improved ACME Certificate Manager with event emission and external certificate management
|
||||
*/
|
||||
export class AcmeCertManager extends plugins.EventEmitter {
|
||||
private domainCertificates: Map<string, IDomainCertificate>;
|
||||
private server: plugins.http.Server | null = null;
|
||||
private acmeClient: plugins.acme.Client | null = null;
|
||||
private accountKey: string | null = null;
|
||||
private renewalTimer: NodeJS.Timeout | null = null;
|
||||
private isShuttingDown: boolean = false;
|
||||
private options: Required<IAcmeCertManagerOptions>;
|
||||
|
||||
/**
|
||||
* Creates a new ACME Certificate Manager
|
||||
* @param options Configuration options
|
||||
*/
|
||||
constructor(options: IAcmeCertManagerOptions = {}) {
|
||||
super();
|
||||
this.domainCertificates = new Map<string, IDomainCertificate>();
|
||||
|
||||
// Default options
|
||||
this.options = {
|
||||
port: options.port ?? 80,
|
||||
contactEmail: options.contactEmail ?? 'admin@example.com',
|
||||
useProduction: options.useProduction ?? false, // Safer default: staging
|
||||
renewThresholdDays: options.renewThresholdDays ?? 30,
|
||||
httpsRedirectPort: options.httpsRedirectPort ?? 443,
|
||||
renewCheckIntervalHours: options.renewCheckIntervalHours ?? 24,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the HTTP server for ACME challenges
|
||||
*/
|
||||
public async start(): Promise<void> {
|
||||
if (this.server) {
|
||||
throw new Error('Server is already running');
|
||||
}
|
||||
|
||||
if (this.isShuttingDown) {
|
||||
throw new Error('Server is shutting down');
|
||||
}
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
try {
|
||||
this.server = plugins.http.createServer((req, res) => this.handleRequest(req, res));
|
||||
|
||||
this.server.on('error', (error: NodeJS.ErrnoException) => {
|
||||
if (error.code === 'EACCES') {
|
||||
reject(new Error(`Permission denied to bind to port ${this.options.port}. Try running with elevated privileges or use a port > 1024.`));
|
||||
} else if (error.code === 'EADDRINUSE') {
|
||||
reject(new Error(`Port ${this.options.port} is already in use.`));
|
||||
} else {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
|
||||
this.server.listen(this.options.port, () => {
|
||||
console.log(`AcmeCertManager is listening on port ${this.options.port}`);
|
||||
this.startRenewalTimer();
|
||||
this.emit(CertManagerEvents.MANAGER_STARTED, this.options.port);
|
||||
resolve();
|
||||
});
|
||||
} catch (error) {
|
||||
reject(error);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops the HTTP server and renewal timer
|
||||
*/
|
||||
public async stop(): Promise<void> {
|
||||
if (!this.server) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.isShuttingDown = true;
|
||||
|
||||
// Stop the renewal timer
|
||||
if (this.renewalTimer) {
|
||||
clearInterval(this.renewalTimer);
|
||||
this.renewalTimer = null;
|
||||
}
|
||||
|
||||
return new Promise<void>((resolve) => {
|
||||
if (this.server) {
|
||||
this.server.close(() => {
|
||||
this.server = null;
|
||||
this.isShuttingDown = false;
|
||||
this.emit(CertManagerEvents.MANAGER_STOPPED);
|
||||
resolve();
|
||||
});
|
||||
} else {
|
||||
this.isShuttingDown = false;
|
||||
resolve();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a domain to be managed for certificates
|
||||
* @param domain The domain to add
|
||||
*/
|
||||
public addDomain(domain: string): void {
|
||||
if (!this.domainCertificates.has(domain)) {
|
||||
this.domainCertificates.set(domain, { certObtained: false, obtainingInProgress: false });
|
||||
console.log(`Domain added: ${domain}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a domain from management
|
||||
* @param domain The domain to remove
|
||||
*/
|
||||
public removeDomain(domain: string): void {
|
||||
if (this.domainCertificates.delete(domain)) {
|
||||
console.log(`Domain removed: ${domain}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a certificate for a domain directly (for externally obtained certificates)
|
||||
* @param domain The domain for the certificate
|
||||
* @param certificate The certificate (PEM format)
|
||||
* @param privateKey The private key (PEM format)
|
||||
* @param expiryDate Optional expiry date
|
||||
*/
|
||||
public setCertificate(domain: string, certificate: string, privateKey: string, expiryDate?: Date): void {
|
||||
let domainInfo = this.domainCertificates.get(domain);
|
||||
|
||||
if (!domainInfo) {
|
||||
domainInfo = { certObtained: false, obtainingInProgress: false };
|
||||
this.domainCertificates.set(domain, domainInfo);
|
||||
}
|
||||
|
||||
domainInfo.certificate = certificate;
|
||||
domainInfo.privateKey = privateKey;
|
||||
domainInfo.certObtained = true;
|
||||
domainInfo.obtainingInProgress = false;
|
||||
|
||||
if (expiryDate) {
|
||||
domainInfo.expiryDate = expiryDate;
|
||||
} else {
|
||||
// Try to extract expiry date from certificate
|
||||
try {
|
||||
// This is a simplistic approach - in a real implementation, use a proper
|
||||
// certificate parsing library like node-forge or x509
|
||||
const matches = certificate.match(/Not After\s*:\s*(.*?)(?:\n|$)/i);
|
||||
if (matches && matches[1]) {
|
||||
domainInfo.expiryDate = new Date(matches[1]);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to extract expiry date from certificate for ${domain}`);
|
||||
}
|
||||
}
|
||||
|
||||
console.log(`Certificate set for ${domain}`);
|
||||
|
||||
// Emit certificate event
|
||||
this.emitCertificateEvent(CertManagerEvents.CERTIFICATE_ISSUED, {
|
||||
domain,
|
||||
certificate,
|
||||
privateKey,
|
||||
expiryDate: domainInfo.expiryDate || new Date(Date.now() + 90 * 24 * 60 * 60 * 1000) // 90 days default
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the certificate for a domain if it exists
|
||||
* @param domain The domain to get the certificate for
|
||||
*/
|
||||
public getCertificate(domain: string): ICertificateData | null {
|
||||
const domainInfo = this.domainCertificates.get(domain);
|
||||
|
||||
if (!domainInfo || !domainInfo.certObtained || !domainInfo.certificate || !domainInfo.privateKey) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return {
|
||||
domain,
|
||||
certificate: domainInfo.certificate,
|
||||
privateKey: domainInfo.privateKey,
|
||||
expiryDate: domainInfo.expiryDate || new Date(Date.now() + 90 * 24 * 60 * 60 * 1000) // 90 days default
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Lazy initialization of the ACME client
|
||||
* @returns An ACME client instance
|
||||
*/
|
||||
private async getAcmeClient(): Promise<plugins.acme.Client> {
|
||||
if (this.acmeClient) {
|
||||
return this.acmeClient;
|
||||
}
|
||||
|
||||
// Generate a new account key
|
||||
this.accountKey = (await plugins.acme.forge.createPrivateKey()).toString();
|
||||
|
||||
this.acmeClient = new plugins.acme.Client({
|
||||
directoryUrl: this.options.useProduction
|
||||
? plugins.acme.directory.letsencrypt.production
|
||||
: plugins.acme.directory.letsencrypt.staging,
|
||||
accountKey: this.accountKey,
|
||||
});
|
||||
|
||||
// Create a new account
|
||||
await this.acmeClient.createAccount({
|
||||
termsOfServiceAgreed: true,
|
||||
contact: [`mailto:${this.options.contactEmail}`],
|
||||
});
|
||||
|
||||
return this.acmeClient;
|
||||
}
|
||||
|
||||
/**
|
||||
* Handles incoming HTTP requests
|
||||
* @param req The HTTP request
|
||||
* @param res The HTTP response
|
||||
*/
|
||||
private handleRequest(req: plugins.http.IncomingMessage, res: plugins.http.ServerResponse): void {
|
||||
const hostHeader = req.headers.host;
|
||||
if (!hostHeader) {
|
||||
res.statusCode = 400;
|
||||
res.end('Bad Request: Host header is missing');
|
||||
return;
|
||||
}
|
||||
|
||||
// Extract domain (ignoring any port in the Host header)
|
||||
const domain = hostHeader.split(':')[0];
|
||||
|
||||
// If the request is for an ACME HTTP-01 challenge, handle it
|
||||
if (req.url && req.url.startsWith('/.well-known/acme-challenge/')) {
|
||||
this.handleAcmeChallenge(req, res, domain);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!this.domainCertificates.has(domain)) {
|
||||
res.statusCode = 404;
|
||||
res.end('Domain not configured');
|
||||
return;
|
||||
}
|
||||
|
||||
const domainInfo = this.domainCertificates.get(domain)!;
|
||||
|
||||
// If certificate exists, redirect to HTTPS
|
||||
if (domainInfo.certObtained) {
|
||||
const httpsPort = this.options.httpsRedirectPort;
|
||||
const portSuffix = httpsPort === 443 ? '' : `:${httpsPort}`;
|
||||
const redirectUrl = `https://${domain}${portSuffix}${req.url || '/'}`;
|
||||
|
||||
res.statusCode = 301;
|
||||
res.setHeader('Location', redirectUrl);
|
||||
res.end(`Redirecting to ${redirectUrl}`);
|
||||
} else {
|
||||
// Trigger certificate issuance if not already running
|
||||
if (!domainInfo.obtainingInProgress) {
|
||||
this.obtainCertificate(domain).catch(err => {
|
||||
this.emit(CertManagerEvents.CERTIFICATE_FAILED, { domain, error: err.message });
|
||||
console.error(`Error obtaining certificate for ${domain}:`, err);
|
||||
});
|
||||
}
|
||||
|
||||
res.statusCode = 503;
|
||||
res.end('Certificate issuance in progress, please try again later.');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Serves the ACME HTTP-01 challenge response
|
||||
* @param req The HTTP request
|
||||
* @param res The HTTP response
|
||||
* @param domain The domain for the challenge
|
||||
*/
|
||||
private handleAcmeChallenge(req: plugins.http.IncomingMessage, res: plugins.http.ServerResponse, domain: string): void {
|
||||
const domainInfo = this.domainCertificates.get(domain);
|
||||
if (!domainInfo) {
|
||||
res.statusCode = 404;
|
||||
res.end('Domain not configured');
|
||||
return;
|
||||
}
|
||||
|
||||
// The token is the last part of the URL
|
||||
const urlParts = req.url?.split('/');
|
||||
const token = urlParts ? urlParts[urlParts.length - 1] : '';
|
||||
|
||||
if (domainInfo.challengeToken === token && domainInfo.challengeKeyAuthorization) {
|
||||
res.statusCode = 200;
|
||||
res.setHeader('Content-Type', 'text/plain');
|
||||
res.end(domainInfo.challengeKeyAuthorization);
|
||||
console.log(`Served ACME challenge response for ${domain}`);
|
||||
} else {
|
||||
res.statusCode = 404;
|
||||
res.end('Challenge token not found');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Obtains a certificate for a domain using ACME HTTP-01 challenge
|
||||
* @param domain The domain to obtain a certificate for
|
||||
* @param isRenewal Whether this is a renewal attempt
|
||||
*/
|
||||
private async obtainCertificate(domain: string, isRenewal: boolean = false): Promise<void> {
|
||||
// Get the domain info
|
||||
const domainInfo = this.domainCertificates.get(domain);
|
||||
if (!domainInfo) {
|
||||
throw new Error(`Domain not found: ${domain}`);
|
||||
}
|
||||
|
||||
// Prevent concurrent certificate issuance
|
||||
if (domainInfo.obtainingInProgress) {
|
||||
console.log(`Certificate issuance already in progress for ${domain}`);
|
||||
return;
|
||||
}
|
||||
|
||||
domainInfo.obtainingInProgress = true;
|
||||
domainInfo.lastRenewalAttempt = new Date();
|
||||
|
||||
try {
|
||||
const client = await this.getAcmeClient();
|
||||
|
||||
// Create a new order for the domain
|
||||
const order = await client.createOrder({
|
||||
identifiers: [{ type: 'dns', value: domain }],
|
||||
});
|
||||
|
||||
// Get the authorizations for the order
|
||||
const authorizations = await client.getAuthorizations(order);
|
||||
|
||||
for (const authz of authorizations) {
|
||||
const challenge = authz.challenges.find(ch => ch.type === 'http-01');
|
||||
if (!challenge) {
|
||||
throw new Error('HTTP-01 challenge not found');
|
||||
}
|
||||
|
||||
// Get the key authorization for the challenge
|
||||
const keyAuthorization = await client.getChallengeKeyAuthorization(challenge);
|
||||
|
||||
// Store the challenge data
|
||||
domainInfo.challengeToken = challenge.token;
|
||||
domainInfo.challengeKeyAuthorization = keyAuthorization;
|
||||
|
||||
// ACME client type definition workaround - use compatible approach
|
||||
// First check if challenge verification is needed
|
||||
const authzUrl = authz.url;
|
||||
|
||||
try {
|
||||
// Check if authzUrl exists and perform verification
|
||||
if (authzUrl) {
|
||||
await client.verifyChallenge(authz, challenge);
|
||||
}
|
||||
|
||||
// Complete the challenge
|
||||
await client.completeChallenge(challenge);
|
||||
|
||||
// Wait for validation
|
||||
await client.waitForValidStatus(challenge);
|
||||
console.log(`HTTP-01 challenge completed for ${domain}`);
|
||||
} catch (error) {
|
||||
console.error(`Challenge error for ${domain}:`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Generate a CSR and private key
|
||||
const [csrBuffer, privateKeyBuffer] = await plugins.acme.forge.createCsr({
|
||||
commonName: domain,
|
||||
});
|
||||
|
||||
const csr = csrBuffer.toString();
|
||||
const privateKey = privateKeyBuffer.toString();
|
||||
|
||||
// Finalize the order with our CSR
|
||||
await client.finalizeOrder(order, csr);
|
||||
|
||||
// Get the certificate with the full chain
|
||||
const certificate = await client.getCertificate(order);
|
||||
|
||||
// Store the certificate and key
|
||||
domainInfo.certificate = certificate;
|
||||
domainInfo.privateKey = privateKey;
|
||||
domainInfo.certObtained = true;
|
||||
|
||||
// Clear challenge data
|
||||
delete domainInfo.challengeToken;
|
||||
delete domainInfo.challengeKeyAuthorization;
|
||||
|
||||
// Extract expiry date from certificate
|
||||
try {
|
||||
const matches = certificate.match(/Not After\s*:\s*(.*?)(?:\n|$)/i);
|
||||
if (matches && matches[1]) {
|
||||
domainInfo.expiryDate = new Date(matches[1]);
|
||||
console.log(`Certificate for ${domain} will expire on ${domainInfo.expiryDate.toISOString()}`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to extract expiry date from certificate for ${domain}`);
|
||||
}
|
||||
|
||||
console.log(`Certificate ${isRenewal ? 'renewed' : 'obtained'} for ${domain}`);
|
||||
|
||||
// Emit the appropriate event
|
||||
const eventType = isRenewal
|
||||
? CertManagerEvents.CERTIFICATE_RENEWED
|
||||
: CertManagerEvents.CERTIFICATE_ISSUED;
|
||||
|
||||
this.emitCertificateEvent(eventType, {
|
||||
domain,
|
||||
certificate,
|
||||
privateKey,
|
||||
expiryDate: domainInfo.expiryDate || new Date(Date.now() + 90 * 24 * 60 * 60 * 1000) // 90 days default
|
||||
});
|
||||
|
||||
} catch (error: any) {
|
||||
// Check for rate limit errors
|
||||
if (error.message && (
|
||||
error.message.includes('rateLimited') ||
|
||||
error.message.includes('too many certificates') ||
|
||||
error.message.includes('rate limit')
|
||||
)) {
|
||||
console.error(`Rate limit reached for ${domain}. Waiting before retry.`);
|
||||
} else {
|
||||
console.error(`Error during certificate issuance for ${domain}:`, error);
|
||||
}
|
||||
|
||||
// Emit failure event
|
||||
this.emit(CertManagerEvents.CERTIFICATE_FAILED, {
|
||||
domain,
|
||||
error: error.message || 'Unknown error',
|
||||
isRenewal
|
||||
});
|
||||
} finally {
|
||||
// Reset flag whether successful or not
|
||||
domainInfo.obtainingInProgress = false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the certificate renewal timer
|
||||
*/
|
||||
private startRenewalTimer(): void {
|
||||
if (this.renewalTimer) {
|
||||
clearInterval(this.renewalTimer);
|
||||
}
|
||||
|
||||
// Convert hours to milliseconds
|
||||
const checkInterval = this.options.renewCheckIntervalHours * 60 * 60 * 1000;
|
||||
|
||||
this.renewalTimer = setInterval(() => this.checkForRenewals(), checkInterval);
|
||||
|
||||
// Prevent the timer from keeping the process alive
|
||||
if (this.renewalTimer.unref) {
|
||||
this.renewalTimer.unref();
|
||||
}
|
||||
|
||||
console.log(`Certificate renewal check scheduled every ${this.options.renewCheckIntervalHours} hours`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks for certificates that need renewal
|
||||
*/
|
||||
private checkForRenewals(): void {
|
||||
if (this.isShuttingDown) {
|
||||
return;
|
||||
}
|
||||
|
||||
console.log('Checking for certificates that need renewal...');
|
||||
|
||||
const now = new Date();
|
||||
const renewThresholdMs = this.options.renewThresholdDays * 24 * 60 * 60 * 1000;
|
||||
|
||||
for (const [domain, domainInfo] of this.domainCertificates.entries()) {
|
||||
// Skip domains without certificates or already in renewal
|
||||
if (!domainInfo.certObtained || domainInfo.obtainingInProgress) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Skip domains without expiry dates
|
||||
if (!domainInfo.expiryDate) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const timeUntilExpiry = domainInfo.expiryDate.getTime() - now.getTime();
|
||||
|
||||
// Check if certificate is near expiry
|
||||
if (timeUntilExpiry <= renewThresholdMs) {
|
||||
console.log(`Certificate for ${domain} expires soon, renewing...`);
|
||||
this.emit(CertManagerEvents.CERTIFICATE_EXPIRING, {
|
||||
domain,
|
||||
expiryDate: domainInfo.expiryDate,
|
||||
daysRemaining: Math.ceil(timeUntilExpiry / (24 * 60 * 60 * 1000))
|
||||
});
|
||||
|
||||
// Start renewal process
|
||||
this.obtainCertificate(domain, true).catch(err => {
|
||||
console.error(`Error renewing certificate for ${domain}:`, err);
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Emits a certificate event with the certificate data
|
||||
* @param eventType The event type to emit
|
||||
* @param data The certificate data
|
||||
*/
|
||||
private emitCertificateEvent(eventType: CertManagerEvents, data: ICertificateData): void {
|
||||
this.emit(eventType, data);
|
||||
}
|
||||
}
|
3316
ts/classes.portproxy.ts
Normal file
3316
ts/classes.portproxy.ts
Normal file
File diff suppressed because it is too large
Load Diff
351
ts/classes.router.ts
Normal file
351
ts/classes.router.ts
Normal file
@ -0,0 +1,351 @@
|
||||
import * as http from 'http';
|
||||
import * as url from 'url';
|
||||
import * as tsclass from '@tsclass/tsclass';
|
||||
|
||||
/**
|
||||
* Optional path pattern configuration that can be added to proxy configs
|
||||
*/
|
||||
export interface IPathPatternConfig {
|
||||
pathPattern?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Interface for router result with additional metadata
|
||||
*/
|
||||
export interface IRouterResult {
|
||||
config: tsclass.network.IReverseProxyConfig;
|
||||
pathMatch?: string;
|
||||
pathParams?: Record<string, string>;
|
||||
pathRemainder?: string;
|
||||
}
|
||||
|
||||
export class ProxyRouter {
|
||||
// Store original configs for reference
|
||||
private reverseProxyConfigs: tsclass.network.IReverseProxyConfig[] = [];
|
||||
// Default config to use when no match is found (optional)
|
||||
private defaultConfig?: tsclass.network.IReverseProxyConfig;
|
||||
// Store path patterns separately since they're not in the original interface
|
||||
private pathPatterns: Map<tsclass.network.IReverseProxyConfig, string> = new Map();
|
||||
// Logger interface
|
||||
private logger: {
|
||||
error: (message: string, data?: any) => void;
|
||||
warn: (message: string, data?: any) => void;
|
||||
info: (message: string, data?: any) => void;
|
||||
debug: (message: string, data?: any) => void;
|
||||
};
|
||||
|
||||
constructor(
|
||||
configs?: tsclass.network.IReverseProxyConfig[],
|
||||
logger?: {
|
||||
error: (message: string, data?: any) => void;
|
||||
warn: (message: string, data?: any) => void;
|
||||
info: (message: string, data?: any) => void;
|
||||
debug: (message: string, data?: any) => void;
|
||||
}
|
||||
) {
|
||||
this.logger = logger || console;
|
||||
if (configs) {
|
||||
this.setNewProxyConfigs(configs);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a new set of reverse configs to be routed to
|
||||
* @param reverseCandidatesArg Array of reverse proxy configurations
|
||||
*/
|
||||
public setNewProxyConfigs(reverseCandidatesArg: tsclass.network.IReverseProxyConfig[]): void {
|
||||
this.reverseProxyConfigs = [...reverseCandidatesArg];
|
||||
|
||||
// Find default config if any (config with "*" as hostname)
|
||||
this.defaultConfig = this.reverseProxyConfigs.find(config => config.hostName === '*');
|
||||
|
||||
this.logger.info(`Router initialized with ${this.reverseProxyConfigs.length} configs (${this.getHostnames().length} unique hosts)`);
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes a request based on hostname and path
|
||||
* @param req The incoming HTTP request
|
||||
* @returns The matching proxy config or undefined if no match found
|
||||
*/
|
||||
public routeReq(req: http.IncomingMessage): tsclass.network.IReverseProxyConfig {
|
||||
const result = this.routeReqWithDetails(req);
|
||||
return result ? result.config : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Routes a request with detailed matching information
|
||||
* @param req The incoming HTTP request
|
||||
* @returns Detailed routing result including matched config and path information
|
||||
*/
|
||||
public routeReqWithDetails(req: http.IncomingMessage): IRouterResult | undefined {
|
||||
// Extract and validate host header
|
||||
const originalHost = req.headers.host;
|
||||
if (!originalHost) {
|
||||
this.logger.error('No host header found in request');
|
||||
return this.defaultConfig ? { config: this.defaultConfig } : undefined;
|
||||
}
|
||||
|
||||
// Parse URL for path matching
|
||||
const parsedUrl = url.parse(req.url || '/');
|
||||
const urlPath = parsedUrl.pathname || '/';
|
||||
|
||||
// Extract hostname without port
|
||||
const hostWithoutPort = originalHost.split(':')[0].toLowerCase();
|
||||
|
||||
// First try exact hostname match
|
||||
const exactConfig = this.findConfigForHost(hostWithoutPort, urlPath);
|
||||
if (exactConfig) {
|
||||
return exactConfig;
|
||||
}
|
||||
|
||||
// Try wildcard subdomain
|
||||
if (hostWithoutPort.includes('.')) {
|
||||
const domainParts = hostWithoutPort.split('.');
|
||||
if (domainParts.length > 2) {
|
||||
const wildcardDomain = `*.${domainParts.slice(1).join('.')}`;
|
||||
const wildcardConfig = this.findConfigForHost(wildcardDomain, urlPath);
|
||||
if (wildcardConfig) {
|
||||
return wildcardConfig;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Fall back to default config if available
|
||||
if (this.defaultConfig) {
|
||||
this.logger.warn(`No specific config found for host: ${hostWithoutPort}, using default`);
|
||||
return { config: this.defaultConfig };
|
||||
}
|
||||
|
||||
this.logger.error(`No config found for host: ${hostWithoutPort}`);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find a config for a specific host and path
|
||||
*/
|
||||
private findConfigForHost(hostname: string, path: string): IRouterResult | undefined {
|
||||
// Find all configs for this hostname
|
||||
const configs = this.reverseProxyConfigs.filter(
|
||||
config => config.hostName.toLowerCase() === hostname.toLowerCase()
|
||||
);
|
||||
|
||||
if (configs.length === 0) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// First try configs with path patterns
|
||||
const configsWithPaths = configs.filter(config => this.pathPatterns.has(config));
|
||||
|
||||
// Sort by path pattern specificity - more specific first
|
||||
configsWithPaths.sort((a, b) => {
|
||||
const aPattern = this.pathPatterns.get(a) || '';
|
||||
const bPattern = this.pathPatterns.get(b) || '';
|
||||
|
||||
// Exact patterns come before wildcard patterns
|
||||
const aHasWildcard = aPattern.includes('*');
|
||||
const bHasWildcard = bPattern.includes('*');
|
||||
|
||||
if (aHasWildcard && !bHasWildcard) return 1;
|
||||
if (!aHasWildcard && bHasWildcard) return -1;
|
||||
|
||||
// Longer patterns are considered more specific
|
||||
return bPattern.length - aPattern.length;
|
||||
});
|
||||
|
||||
// Check each config with path pattern
|
||||
for (const config of configsWithPaths) {
|
||||
const pathPattern = this.pathPatterns.get(config);
|
||||
if (pathPattern) {
|
||||
const pathMatch = this.matchPath(path, pathPattern);
|
||||
if (pathMatch) {
|
||||
return {
|
||||
config,
|
||||
pathMatch: pathMatch.matched,
|
||||
pathParams: pathMatch.params,
|
||||
pathRemainder: pathMatch.remainder
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// If no path pattern matched, use the first config without a path pattern
|
||||
const configWithoutPath = configs.find(config => !this.pathPatterns.has(config));
|
||||
if (configWithoutPath) {
|
||||
return { config: configWithoutPath };
|
||||
}
|
||||
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* Matches a URL path against a pattern
|
||||
* Supports:
|
||||
* - Exact matches: /users/profile
|
||||
* - Wildcards: /api/* (matches any path starting with /api/)
|
||||
* - Path parameters: /users/:id (captures id as a parameter)
|
||||
*
|
||||
* @param path The URL path to match
|
||||
* @param pattern The pattern to match against
|
||||
* @returns Match result with params and remainder, or null if no match
|
||||
*/
|
||||
private matchPath(path: string, pattern: string): {
|
||||
matched: string;
|
||||
params: Record<string, string>;
|
||||
remainder: string;
|
||||
} | null {
|
||||
// Handle exact match
|
||||
if (path === pattern) {
|
||||
return {
|
||||
matched: pattern,
|
||||
params: {},
|
||||
remainder: ''
|
||||
};
|
||||
}
|
||||
|
||||
// Handle wildcard match
|
||||
if (pattern.endsWith('/*')) {
|
||||
const prefix = pattern.slice(0, -2);
|
||||
if (path === prefix || path.startsWith(`${prefix}/`)) {
|
||||
return {
|
||||
matched: prefix,
|
||||
params: {},
|
||||
remainder: path.slice(prefix.length)
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Handle path parameters
|
||||
const patternParts = pattern.split('/').filter(p => p);
|
||||
const pathParts = path.split('/').filter(p => p);
|
||||
|
||||
// Too few path parts to match
|
||||
if (pathParts.length < patternParts.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const params: Record<string, string> = {};
|
||||
|
||||
// Compare each part
|
||||
for (let i = 0; i < patternParts.length; i++) {
|
||||
const patternPart = patternParts[i];
|
||||
const pathPart = pathParts[i];
|
||||
|
||||
// Handle parameter
|
||||
if (patternPart.startsWith(':')) {
|
||||
const paramName = patternPart.slice(1);
|
||||
params[paramName] = pathPart;
|
||||
continue;
|
||||
}
|
||||
|
||||
// Handle wildcard at the end
|
||||
if (patternPart === '*' && i === patternParts.length - 1) {
|
||||
break;
|
||||
}
|
||||
|
||||
// Handle exact match for this part
|
||||
if (patternPart !== pathPart) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
// Calculate the remainder - the unmatched path parts
|
||||
const remainderParts = pathParts.slice(patternParts.length);
|
||||
const remainder = remainderParts.length ? '/' + remainderParts.join('/') : '';
|
||||
|
||||
// Calculate the matched path
|
||||
const matchedParts = patternParts.map((part, i) => {
|
||||
return part.startsWith(':') ? pathParts[i] : part;
|
||||
});
|
||||
const matched = '/' + matchedParts.join('/');
|
||||
|
||||
return {
|
||||
matched,
|
||||
params,
|
||||
remainder
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all currently active proxy configurations
|
||||
* @returns Array of all active configurations
|
||||
*/
|
||||
public getProxyConfigs(): tsclass.network.IReverseProxyConfig[] {
|
||||
return [...this.reverseProxyConfigs];
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all hostnames that this router is configured to handle
|
||||
* @returns Array of hostnames
|
||||
*/
|
||||
public getHostnames(): string[] {
|
||||
const hostnames = new Set<string>();
|
||||
for (const config of this.reverseProxyConfigs) {
|
||||
if (config.hostName !== '*') {
|
||||
hostnames.add(config.hostName.toLowerCase());
|
||||
}
|
||||
}
|
||||
return Array.from(hostnames);
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a single new proxy configuration
|
||||
* @param config The configuration to add
|
||||
* @param pathPattern Optional path pattern for route matching
|
||||
*/
|
||||
public addProxyConfig(
|
||||
config: tsclass.network.IReverseProxyConfig,
|
||||
pathPattern?: string
|
||||
): void {
|
||||
this.reverseProxyConfigs.push(config);
|
||||
|
||||
// Store path pattern if provided
|
||||
if (pathPattern) {
|
||||
this.pathPatterns.set(config, pathPattern);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets a path pattern for an existing config
|
||||
* @param config The existing configuration
|
||||
* @param pathPattern The path pattern to set
|
||||
* @returns Boolean indicating if the config was found and updated
|
||||
*/
|
||||
public setPathPattern(
|
||||
config: tsclass.network.IReverseProxyConfig,
|
||||
pathPattern: string
|
||||
): boolean {
|
||||
const exists = this.reverseProxyConfigs.includes(config);
|
||||
if (exists) {
|
||||
this.pathPatterns.set(config, pathPattern);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes a proxy configuration by hostname
|
||||
* @param hostname The hostname to remove
|
||||
* @returns Boolean indicating whether any configs were removed
|
||||
*/
|
||||
public removeProxyConfig(hostname: string): boolean {
|
||||
const initialCount = this.reverseProxyConfigs.length;
|
||||
|
||||
// Find configs to remove
|
||||
const configsToRemove = this.reverseProxyConfigs.filter(
|
||||
config => config.hostName === hostname
|
||||
);
|
||||
|
||||
// Remove them from the patterns map
|
||||
for (const config of configsToRemove) {
|
||||
this.pathPatterns.delete(config);
|
||||
}
|
||||
|
||||
// Filter them out of the configs array
|
||||
this.reverseProxyConfigs = this.reverseProxyConfigs.filter(
|
||||
config => config.hostName !== hostname
|
||||
);
|
||||
|
||||
return this.reverseProxyConfigs.length !== initialCount;
|
||||
}
|
||||
}
|
@ -1,3 +1,5 @@
|
||||
export * from './smartproxy.classes.networkproxy.js';
|
||||
export * from './smartproxy.portproxy.js';
|
||||
export * from './smartproxy.classes.sslredirect.js';
|
||||
export * from './classes.iptablesproxy.js';
|
||||
export * from './classes.networkproxy.js';
|
||||
export * from './classes.portproxy.js';
|
||||
export * from './classes.port80handler.js';
|
||||
export * from './classes.sslredirect.js';
|
||||
|
@ -1,11 +1,13 @@
|
||||
// node native scope
|
||||
import { EventEmitter } from 'events';
|
||||
import * as http from 'http';
|
||||
import * as https from 'https';
|
||||
import * as net from 'net';
|
||||
import * as tls from 'tls';
|
||||
import * as url from 'url';
|
||||
|
||||
export { http, https, net, tls, url };
|
||||
|
||||
export { EventEmitter, http, https, net, tls, url };
|
||||
|
||||
// tsclass scope
|
||||
import * as tsclass from '@tsclass/tsclass';
|
||||
@ -22,9 +24,10 @@ import * as smartstring from '@push.rocks/smartstring';
|
||||
export { lik, smartdelay, smartrequest, smartpromise, smartstring };
|
||||
|
||||
// third party scope
|
||||
import * as acme from 'acme-client';
|
||||
import prettyMs from 'pretty-ms';
|
||||
import * as ws from 'ws';
|
||||
import wsDefault from 'ws';
|
||||
import { minimatch } from 'minimatch';
|
||||
|
||||
export { prettyMs, ws, wsDefault, minimatch };
|
||||
export { acme, prettyMs, ws, wsDefault, minimatch };
|
||||
|
@ -1,369 +0,0 @@
|
||||
import * as plugins from './plugins.js';
|
||||
import { ProxyRouter } from './smartproxy.classes.router.js';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
export interface INetworkProxyOptions {
|
||||
port: number;
|
||||
}
|
||||
|
||||
interface IWebSocketWithHeartbeat extends plugins.wsDefault {
|
||||
lastPong: number;
|
||||
}
|
||||
|
||||
export class NetworkProxy {
|
||||
public options: INetworkProxyOptions;
|
||||
public proxyConfigs: plugins.tsclass.network.IReverseProxyConfig[] = [];
|
||||
public httpsServer: plugins.https.Server;
|
||||
public router = new ProxyRouter();
|
||||
public socketMap = new plugins.lik.ObjectMap<plugins.net.Socket>();
|
||||
public defaultHeaders: { [key: string]: string } = {};
|
||||
public heartbeatInterval: NodeJS.Timeout;
|
||||
private defaultCertificates: { key: string; cert: string };
|
||||
|
||||
public alreadyAddedReverseConfigs: {
|
||||
[hostName: string]: plugins.tsclass.network.IReverseProxyConfig;
|
||||
} = {};
|
||||
|
||||
constructor(optionsArg: INetworkProxyOptions) {
|
||||
this.options = optionsArg;
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
const certPath = path.join(__dirname, '..', 'assets', 'certs');
|
||||
|
||||
try {
|
||||
this.defaultCertificates = {
|
||||
key: fs.readFileSync(path.join(certPath, 'key.pem'), 'utf8'),
|
||||
cert: fs.readFileSync(path.join(certPath, 'cert.pem'), 'utf8')
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error loading certificates:', error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
public async start() {
|
||||
// Instead of marking the callback async (which Node won't await),
|
||||
// we call our async handler and catch errors.
|
||||
this.httpsServer = plugins.https.createServer(
|
||||
{
|
||||
key: this.defaultCertificates.key,
|
||||
cert: this.defaultCertificates.cert
|
||||
},
|
||||
(originRequest, originResponse) => {
|
||||
this.handleRequest(originRequest, originResponse).catch((error) => {
|
||||
console.error('Unhandled error in request handler:', error);
|
||||
try {
|
||||
originResponse.end();
|
||||
} catch (err) {
|
||||
// ignore errors during cleanup
|
||||
}
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
// Enable websockets
|
||||
const wsServer = new plugins.ws.WebSocketServer({ server: this.httpsServer });
|
||||
|
||||
// Set up the heartbeat interval
|
||||
this.heartbeatInterval = setInterval(() => {
|
||||
wsServer.clients.forEach((ws: plugins.wsDefault) => {
|
||||
const wsIncoming = ws as IWebSocketWithHeartbeat;
|
||||
if (!wsIncoming.lastPong) {
|
||||
wsIncoming.lastPong = Date.now();
|
||||
}
|
||||
if (Date.now() - wsIncoming.lastPong > 5 * 60 * 1000) {
|
||||
console.log('Terminating websocket due to missing pong for 5 minutes.');
|
||||
wsIncoming.terminate();
|
||||
} else {
|
||||
wsIncoming.ping();
|
||||
}
|
||||
});
|
||||
}, 60000); // runs every 1 minute
|
||||
|
||||
wsServer.on(
|
||||
'connection',
|
||||
(wsIncoming: IWebSocketWithHeartbeat, reqArg: plugins.http.IncomingMessage) => {
|
||||
console.log(
|
||||
`wss proxy: got connection for wsc for https://${reqArg.headers.host}${reqArg.url}`,
|
||||
);
|
||||
|
||||
wsIncoming.lastPong = Date.now();
|
||||
wsIncoming.on('pong', () => {
|
||||
wsIncoming.lastPong = Date.now();
|
||||
});
|
||||
|
||||
let wsOutgoing: plugins.wsDefault;
|
||||
const outGoingDeferred = plugins.smartpromise.defer();
|
||||
|
||||
// --- Improvement 2: Only call routeReq once ---
|
||||
const wsDestinationConfig = this.router.routeReq(reqArg);
|
||||
if (!wsDestinationConfig) {
|
||||
wsIncoming.terminate();
|
||||
return;
|
||||
}
|
||||
try {
|
||||
wsOutgoing = new plugins.wsDefault(
|
||||
`ws://${wsDestinationConfig.destinationIp}:${wsDestinationConfig.destinationPort}${reqArg.url}`,
|
||||
);
|
||||
console.log('wss proxy: initiated outgoing proxy');
|
||||
wsOutgoing.on('open', async () => {
|
||||
outGoingDeferred.resolve();
|
||||
});
|
||||
} catch (err) {
|
||||
console.error('Error initiating outgoing WebSocket:', err);
|
||||
wsIncoming.terminate();
|
||||
return;
|
||||
}
|
||||
|
||||
wsIncoming.on('message', async (message, isBinary) => {
|
||||
try {
|
||||
await outGoingDeferred.promise;
|
||||
wsOutgoing.send(message, { binary: isBinary });
|
||||
} catch (error) {
|
||||
console.error('Error sending message to wsOutgoing:', error);
|
||||
}
|
||||
});
|
||||
|
||||
wsOutgoing.on('message', async (message, isBinary) => {
|
||||
try {
|
||||
wsIncoming.send(message, { binary: isBinary });
|
||||
} catch (error) {
|
||||
console.error('Error sending message to wsIncoming:', error);
|
||||
}
|
||||
});
|
||||
|
||||
const terminateWsOutgoing = () => {
|
||||
if (wsOutgoing) {
|
||||
wsOutgoing.terminate();
|
||||
console.log('Terminated outgoing ws.');
|
||||
}
|
||||
};
|
||||
wsIncoming.on('error', terminateWsOutgoing);
|
||||
wsIncoming.on('close', terminateWsOutgoing);
|
||||
|
||||
const terminateWsIncoming = () => {
|
||||
if (wsIncoming) {
|
||||
wsIncoming.terminate();
|
||||
console.log('Terminated incoming ws.');
|
||||
}
|
||||
};
|
||||
wsOutgoing.on('error', terminateWsIncoming);
|
||||
wsOutgoing.on('close', terminateWsIncoming);
|
||||
},
|
||||
);
|
||||
|
||||
this.httpsServer.keepAliveTimeout = 600 * 1000;
|
||||
this.httpsServer.headersTimeout = 600 * 1000;
|
||||
|
||||
this.httpsServer.on('connection', (connection: plugins.net.Socket) => {
|
||||
this.socketMap.add(connection);
|
||||
console.log(`Added connection. Now ${this.socketMap.getArray().length} sockets connected.`);
|
||||
const cleanupConnection = () => {
|
||||
if (this.socketMap.checkForObject(connection)) {
|
||||
this.socketMap.remove(connection);
|
||||
console.log(`Removed connection. ${this.socketMap.getArray().length} sockets remaining.`);
|
||||
connection.destroy();
|
||||
}
|
||||
};
|
||||
connection.on('close', cleanupConnection);
|
||||
connection.on('error', cleanupConnection);
|
||||
connection.on('end', cleanupConnection);
|
||||
connection.on('timeout', cleanupConnection);
|
||||
});
|
||||
|
||||
this.httpsServer.listen(this.options.port);
|
||||
console.log(
|
||||
`NetworkProxy -> OK: now listening for new connections on port ${this.options.port}`,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Internal async handler for processing HTTP/HTTPS requests.
|
||||
*/
|
||||
private async handleRequest(
|
||||
originRequest: plugins.http.IncomingMessage,
|
||||
originResponse: plugins.http.ServerResponse,
|
||||
): Promise<void> {
|
||||
const endOriginReqRes = (
|
||||
statusArg: number = 404,
|
||||
messageArg: string = 'This route is not available on this server.',
|
||||
headers: plugins.http.OutgoingHttpHeaders = {},
|
||||
) => {
|
||||
originResponse.writeHead(statusArg, messageArg);
|
||||
originResponse.end(messageArg);
|
||||
if (originRequest.socket !== originResponse.socket) {
|
||||
console.log('hey, something is strange.');
|
||||
}
|
||||
originResponse.destroy();
|
||||
};
|
||||
|
||||
console.log(
|
||||
`got request: ${originRequest.headers.host}${plugins.url.parse(originRequest.url).path}`,
|
||||
);
|
||||
const destinationConfig = this.router.routeReq(originRequest);
|
||||
|
||||
if (!destinationConfig) {
|
||||
console.log(
|
||||
`${originRequest.headers.host} can't be routed properly. Terminating request.`,
|
||||
);
|
||||
endOriginReqRes();
|
||||
return;
|
||||
}
|
||||
|
||||
// authentication
|
||||
if (destinationConfig.authentication) {
|
||||
const authInfo = destinationConfig.authentication;
|
||||
switch (authInfo.type) {
|
||||
case 'Basic': {
|
||||
const authHeader = originRequest.headers.authorization;
|
||||
if (!authHeader) {
|
||||
return endOriginReqRes(401, 'Authentication required', {
|
||||
'WWW-Authenticate': 'Basic realm="Access to the staging site", charset="UTF-8"',
|
||||
});
|
||||
}
|
||||
if (!authHeader.includes('Basic ')) {
|
||||
return endOriginReqRes(401, 'Authentication required', {
|
||||
'WWW-Authenticate': 'Basic realm="Access to the staging site", charset="UTF-8"',
|
||||
});
|
||||
}
|
||||
const authStringBase64 = authHeader.replace('Basic ', '');
|
||||
const authString: string = plugins.smartstring.base64.decode(authStringBase64);
|
||||
const userPassArray = authString.split(':');
|
||||
const user = userPassArray[0];
|
||||
const pass = userPassArray[1];
|
||||
if (user === authInfo.user && pass === authInfo.pass) {
|
||||
console.log('Request successfully authenticated');
|
||||
} else {
|
||||
return endOriginReqRes(403, 'Forbidden: Wrong credentials');
|
||||
}
|
||||
break;
|
||||
}
|
||||
default:
|
||||
return endOriginReqRes(
|
||||
403,
|
||||
'Forbidden: unsupported authentication method configured. Please report to the admin.',
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let destinationUrl: string;
|
||||
if (destinationConfig) {
|
||||
destinationUrl = `http://${destinationConfig.destinationIp}:${destinationConfig.destinationPort}${originRequest.url}`;
|
||||
} else {
|
||||
return endOriginReqRes();
|
||||
}
|
||||
console.log(destinationUrl);
|
||||
try {
|
||||
const proxyResponse = await plugins.smartrequest.request(
|
||||
destinationUrl,
|
||||
{
|
||||
method: originRequest.method,
|
||||
headers: {
|
||||
...originRequest.headers,
|
||||
'X-Forwarded-Host': originRequest.headers.host,
|
||||
'X-Forwarded-Proto': 'https',
|
||||
},
|
||||
keepAlive: true,
|
||||
},
|
||||
true, // streaming (keepAlive)
|
||||
(proxyRequest) => {
|
||||
originRequest.on('data', (data) => {
|
||||
proxyRequest.write(data);
|
||||
});
|
||||
originRequest.on('end', () => {
|
||||
proxyRequest.end();
|
||||
});
|
||||
originRequest.on('error', () => {
|
||||
proxyRequest.end();
|
||||
});
|
||||
originRequest.on('close', () => {
|
||||
proxyRequest.end();
|
||||
});
|
||||
originRequest.on('timeout', () => {
|
||||
proxyRequest.end();
|
||||
originRequest.destroy();
|
||||
});
|
||||
proxyRequest.on('error', () => {
|
||||
endOriginReqRes();
|
||||
});
|
||||
},
|
||||
);
|
||||
originResponse.statusCode = proxyResponse.statusCode;
|
||||
console.log(proxyResponse.statusCode);
|
||||
for (const defaultHeader of Object.keys(this.defaultHeaders)) {
|
||||
originResponse.setHeader(defaultHeader, this.defaultHeaders[defaultHeader]);
|
||||
}
|
||||
for (const header of Object.keys(proxyResponse.headers)) {
|
||||
originResponse.setHeader(header, proxyResponse.headers[header]);
|
||||
}
|
||||
proxyResponse.on('data', (data) => {
|
||||
originResponse.write(data);
|
||||
});
|
||||
proxyResponse.on('end', () => {
|
||||
originResponse.end();
|
||||
});
|
||||
proxyResponse.on('error', () => {
|
||||
originResponse.destroy();
|
||||
});
|
||||
proxyResponse.on('close', () => {
|
||||
originResponse.end();
|
||||
});
|
||||
proxyResponse.on('timeout', () => {
|
||||
originResponse.end();
|
||||
originResponse.destroy();
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error while processing request:', error);
|
||||
endOriginReqRes(502, 'Bad Gateway: Error processing the request');
|
||||
}
|
||||
}
|
||||
|
||||
public async updateProxyConfigs(
|
||||
proxyConfigsArg: plugins.tsclass.network.IReverseProxyConfig[],
|
||||
) {
|
||||
console.log(`got new proxy configs`);
|
||||
this.proxyConfigs = proxyConfigsArg;
|
||||
this.router.setNewProxyConfigs(proxyConfigsArg);
|
||||
for (const hostCandidate of this.proxyConfigs) {
|
||||
const existingHostNameConfig = this.alreadyAddedReverseConfigs[hostCandidate.hostName];
|
||||
|
||||
if (!existingHostNameConfig) {
|
||||
this.alreadyAddedReverseConfigs[hostCandidate.hostName] = hostCandidate;
|
||||
} else {
|
||||
if (
|
||||
existingHostNameConfig.publicKey === hostCandidate.publicKey &&
|
||||
existingHostNameConfig.privateKey === hostCandidate.privateKey
|
||||
) {
|
||||
continue;
|
||||
} else {
|
||||
this.alreadyAddedReverseConfigs[hostCandidate.hostName] = hostCandidate;
|
||||
}
|
||||
}
|
||||
|
||||
this.httpsServer.addContext(hostCandidate.hostName, {
|
||||
cert: hostCandidate.publicKey,
|
||||
key: hostCandidate.privateKey,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
public async addDefaultHeaders(headersArg: { [key: string]: string }) {
|
||||
for (const headerKey of Object.keys(headersArg)) {
|
||||
this.defaultHeaders[headerKey] = headersArg[headerKey];
|
||||
}
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
const done = plugins.smartpromise.defer();
|
||||
this.httpsServer.close(() => {
|
||||
done.resolve();
|
||||
});
|
||||
for (const socket of this.socketMap.getArray()) {
|
||||
socket.destroy();
|
||||
}
|
||||
await done.promise;
|
||||
clearInterval(this.heartbeatInterval);
|
||||
console.log('NetworkProxy -> OK: Server has been stopped and all connections closed.');
|
||||
}
|
||||
}
|
@ -1,33 +0,0 @@
|
||||
import * as plugins from './plugins.js';
|
||||
|
||||
export class ProxyRouter {
|
||||
public reverseProxyConfigs: plugins.tsclass.network.IReverseProxyConfig[] = [];
|
||||
|
||||
/**
|
||||
* sets a new set of reverse configs to be routed to
|
||||
* @param reverseCandidatesArg
|
||||
*/
|
||||
public setNewProxyConfigs(reverseCandidatesArg: plugins.tsclass.network.IReverseProxyConfig[]) {
|
||||
this.reverseProxyConfigs = reverseCandidatesArg;
|
||||
}
|
||||
|
||||
/**
|
||||
* routes a request
|
||||
*/
|
||||
public routeReq(req: plugins.http.IncomingMessage): plugins.tsclass.network.IReverseProxyConfig {
|
||||
const originalHost = req.headers.host;
|
||||
if (!originalHost) {
|
||||
console.error('No host header found in request');
|
||||
return undefined;
|
||||
}
|
||||
// Strip port from host if present
|
||||
const hostWithoutPort = originalHost.split(':')[0];
|
||||
const correspodingReverseProxyConfig = this.reverseProxyConfigs.find((reverseConfig) => {
|
||||
return reverseConfig.hostName === hostWithoutPort;
|
||||
});
|
||||
if (!correspodingReverseProxyConfig) {
|
||||
console.error(`No config found for host: ${hostWithoutPort}`);
|
||||
}
|
||||
return correspodingReverseProxyConfig;
|
||||
}
|
||||
}
|
@ -1,431 +0,0 @@
|
||||
import * as plugins from './plugins.js';
|
||||
|
||||
export interface IDomainConfig {
|
||||
domain: string; // glob pattern for domain
|
||||
allowedIPs: string[]; // glob patterns for IPs allowed to access this domain
|
||||
targetIP?: string; // Optional target IP for this domain
|
||||
}
|
||||
|
||||
export interface IProxySettings extends plugins.tls.TlsOptions {
|
||||
// Port configuration
|
||||
fromPort: number;
|
||||
toPort: number;
|
||||
toHost?: string; // Target host to proxy to, defaults to 'localhost'
|
||||
|
||||
// Domain and security settings
|
||||
domains: IDomainConfig[];
|
||||
sniEnabled?: boolean;
|
||||
defaultAllowedIPs?: string[]; // Optional default IP patterns if no matching domain found
|
||||
preserveSourceIP?: boolean; // Whether to preserve the client's source IP when proxying
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract SNI (Server Name Indication) from a TLS ClientHello packet.
|
||||
* Returns the server name if found, or undefined.
|
||||
*/
|
||||
function extractSNI(buffer: Buffer): string | undefined {
|
||||
let offset = 0;
|
||||
// We need at least 5 bytes for the record header.
|
||||
if (buffer.length < 5) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// TLS record header
|
||||
const recordType = buffer.readUInt8(0);
|
||||
if (recordType !== 22) { // 22 = handshake
|
||||
return undefined;
|
||||
}
|
||||
// Read record length
|
||||
const recordLength = buffer.readUInt16BE(3);
|
||||
if (buffer.length < 5 + recordLength) {
|
||||
// Not all data arrived yet; in production you might need to accumulate more data.
|
||||
return undefined;
|
||||
}
|
||||
|
||||
offset = 5;
|
||||
// Handshake message type should be 1 for ClientHello.
|
||||
const handshakeType = buffer.readUInt8(offset);
|
||||
if (handshakeType !== 1) {
|
||||
return undefined;
|
||||
}
|
||||
// Skip handshake header (1 byte type + 3 bytes length)
|
||||
offset += 4;
|
||||
|
||||
// Skip client version (2 bytes) and random (32 bytes)
|
||||
offset += 2 + 32;
|
||||
|
||||
// Session ID
|
||||
const sessionIDLength = buffer.readUInt8(offset);
|
||||
offset += 1 + sessionIDLength;
|
||||
|
||||
// Cipher suites
|
||||
const cipherSuitesLength = buffer.readUInt16BE(offset);
|
||||
offset += 2 + cipherSuitesLength;
|
||||
|
||||
// Compression methods
|
||||
const compressionMethodsLength = buffer.readUInt8(offset);
|
||||
offset += 1 + compressionMethodsLength;
|
||||
|
||||
// Extensions length
|
||||
if (offset + 2 > buffer.length) {
|
||||
return undefined;
|
||||
}
|
||||
const extensionsLength = buffer.readUInt16BE(offset);
|
||||
offset += 2;
|
||||
const extensionsEnd = offset + extensionsLength;
|
||||
|
||||
// Iterate over extensions
|
||||
while (offset + 4 <= extensionsEnd) {
|
||||
const extensionType = buffer.readUInt16BE(offset);
|
||||
const extensionLength = buffer.readUInt16BE(offset + 2);
|
||||
offset += 4;
|
||||
|
||||
// Check for SNI extension (type 0)
|
||||
if (extensionType === 0x0000) {
|
||||
// SNI extension: first 2 bytes are the SNI list length.
|
||||
if (offset + 2 > buffer.length) {
|
||||
return undefined;
|
||||
}
|
||||
const sniListLength = buffer.readUInt16BE(offset);
|
||||
offset += 2;
|
||||
const sniListEnd = offset + sniListLength;
|
||||
// Loop through the list; typically there is one entry.
|
||||
while (offset + 3 < sniListEnd) {
|
||||
const nameType = buffer.readUInt8(offset);
|
||||
offset++;
|
||||
const nameLen = buffer.readUInt16BE(offset);
|
||||
offset += 2;
|
||||
if (nameType === 0) { // host_name
|
||||
if (offset + nameLen > buffer.length) {
|
||||
return undefined;
|
||||
}
|
||||
const serverName = buffer.toString('utf8', offset, offset + nameLen);
|
||||
return serverName;
|
||||
}
|
||||
offset += nameLen;
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
offset += extensionLength;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export class PortProxy {
|
||||
netServer: plugins.net.Server;
|
||||
settings: IProxySettings;
|
||||
// Track active incoming connections
|
||||
private activeConnections: Set<plugins.net.Socket> = new Set();
|
||||
// Record start times for incoming connections
|
||||
private incomingConnectionTimes: Map<plugins.net.Socket, number> = new Map();
|
||||
// Record start times for outgoing connections
|
||||
private outgoingConnectionTimes: Map<plugins.net.Socket, number> = new Map();
|
||||
private connectionLogger: NodeJS.Timeout | null = null;
|
||||
|
||||
// Overall termination statistics
|
||||
private terminationStats: {
|
||||
incoming: Record<string, number>;
|
||||
outgoing: Record<string, number>;
|
||||
} = {
|
||||
incoming: {},
|
||||
outgoing: {},
|
||||
};
|
||||
|
||||
constructor(settings: IProxySettings) {
|
||||
this.settings = {
|
||||
...settings,
|
||||
toHost: settings.toHost || 'localhost'
|
||||
};
|
||||
}
|
||||
|
||||
// Helper to update termination stats.
|
||||
private incrementTerminationStat(side: 'incoming' | 'outgoing', reason: string): void {
|
||||
if (!this.terminationStats[side][reason]) {
|
||||
this.terminationStats[side][reason] = 1;
|
||||
} else {
|
||||
this.terminationStats[side][reason]++;
|
||||
}
|
||||
}
|
||||
|
||||
public async start() {
|
||||
// Adjusted cleanUpSockets: forcefully destroy both sockets if they haven't been destroyed.
|
||||
const cleanUpSockets = (from: plugins.net.Socket, to?: plugins.net.Socket) => {
|
||||
if (!from.destroyed) {
|
||||
from.destroy();
|
||||
}
|
||||
if (to && !to.destroyed) {
|
||||
to.destroy();
|
||||
}
|
||||
};
|
||||
|
||||
const normalizeIP = (ip: string): string[] => {
|
||||
// Handle IPv4-mapped IPv6 addresses
|
||||
if (ip.startsWith('::ffff:')) {
|
||||
const ipv4 = ip.slice(7); // Remove '::ffff:' prefix
|
||||
return [ip, ipv4];
|
||||
}
|
||||
// Handle IPv4 addresses by adding IPv4-mapped IPv6 variant
|
||||
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) {
|
||||
return [ip, `::ffff:${ip}`];
|
||||
}
|
||||
return [ip];
|
||||
};
|
||||
|
||||
const isAllowed = (value: string, patterns: string[]): boolean => {
|
||||
// Expand patterns to include both IPv4 and IPv6 variants
|
||||
const expandedPatterns = patterns.flatMap(normalizeIP);
|
||||
// Check if any variant of the IP matches any expanded pattern
|
||||
return normalizeIP(value).some(ip =>
|
||||
expandedPatterns.some(pattern => plugins.minimatch(ip, pattern))
|
||||
);
|
||||
};
|
||||
|
||||
const findMatchingDomain = (serverName: string): IDomainConfig | undefined => {
|
||||
return this.settings.domains.find(config => plugins.minimatch(serverName, config.domain));
|
||||
};
|
||||
|
||||
// Create a plain net server for TLS passthrough.
|
||||
this.netServer = plugins.net.createServer((socket: plugins.net.Socket) => {
|
||||
const remoteIP = socket.remoteAddress || '';
|
||||
|
||||
// Record start time for the incoming connection.
|
||||
this.activeConnections.add(socket);
|
||||
this.incomingConnectionTimes.set(socket, Date.now());
|
||||
console.log(`New connection from ${remoteIP}. Active connections: ${this.activeConnections.size}`);
|
||||
|
||||
// Flag to detect if we've received the first data chunk.
|
||||
let initialDataReceived = false;
|
||||
|
||||
// Local termination reason trackers for each side.
|
||||
let incomingTermReason: string | null = null;
|
||||
let outgoingTermReason: string | null = null;
|
||||
|
||||
// Immediately attach an error handler to catch early errors.
|
||||
socket.on('error', (err: Error) => {
|
||||
if (!initialDataReceived) {
|
||||
console.log(`(Premature) Incoming socket error from ${remoteIP} before data received: ${err.message}`);
|
||||
} else {
|
||||
console.log(`(Immediate) Incoming socket error from ${remoteIP}: ${err.message}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Ensure cleanup happens only once.
|
||||
let connectionClosed = false;
|
||||
const cleanupOnce = () => {
|
||||
if (!connectionClosed) {
|
||||
connectionClosed = true;
|
||||
cleanUpSockets(socket, to || undefined);
|
||||
this.incomingConnectionTimes.delete(socket);
|
||||
if (to) {
|
||||
this.outgoingConnectionTimes.delete(to);
|
||||
}
|
||||
if (this.activeConnections.has(socket)) {
|
||||
this.activeConnections.delete(socket);
|
||||
console.log(`Connection from ${remoteIP} terminated. Active connections: ${this.activeConnections.size}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Outgoing connection placeholder.
|
||||
let to: plugins.net.Socket | null = null;
|
||||
|
||||
// Handle errors by recording termination reason and cleaning up.
|
||||
const handleError = (side: 'incoming' | 'outgoing') => (err: Error) => {
|
||||
const code = (err as any).code;
|
||||
let reason = 'error';
|
||||
if (code === 'ECONNRESET') {
|
||||
reason = 'econnreset';
|
||||
console.log(`ECONNRESET on ${side} side from ${remoteIP}: ${err.message}`);
|
||||
} else {
|
||||
console.log(`Error on ${side} side from ${remoteIP}: ${err.message}`);
|
||||
}
|
||||
if (side === 'incoming' && incomingTermReason === null) {
|
||||
incomingTermReason = reason;
|
||||
this.incrementTerminationStat('incoming', reason);
|
||||
} else if (side === 'outgoing' && outgoingTermReason === null) {
|
||||
outgoingTermReason = reason;
|
||||
this.incrementTerminationStat('outgoing', reason);
|
||||
}
|
||||
cleanupOnce();
|
||||
};
|
||||
|
||||
// Handle close events. If no termination reason was recorded, mark as "normal".
|
||||
const handleClose = (side: 'incoming' | 'outgoing') => () => {
|
||||
console.log(`Connection closed on ${side} side from ${remoteIP}`);
|
||||
if (side === 'incoming' && incomingTermReason === null) {
|
||||
incomingTermReason = 'normal';
|
||||
this.incrementTerminationStat('incoming', 'normal');
|
||||
} else if (side === 'outgoing' && outgoingTermReason === null) {
|
||||
outgoingTermReason = 'normal';
|
||||
this.incrementTerminationStat('outgoing', 'normal');
|
||||
}
|
||||
cleanupOnce();
|
||||
};
|
||||
|
||||
// Setup connection, optionally accepting the initial data chunk.
|
||||
const setupConnection = (serverName: string, initialChunk?: Buffer) => {
|
||||
// Check if the IP is allowed by default.
|
||||
const isDefaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
|
||||
if (!isDefaultAllowed && serverName) {
|
||||
const domainConfig = findMatchingDomain(serverName);
|
||||
if (!domainConfig) {
|
||||
console.log(`Connection rejected: No matching domain config for ${serverName} from ${remoteIP}`);
|
||||
socket.end();
|
||||
if (incomingTermReason === null) {
|
||||
incomingTermReason = 'rejected';
|
||||
this.incrementTerminationStat('incoming', 'rejected');
|
||||
}
|
||||
cleanupOnce();
|
||||
return;
|
||||
}
|
||||
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
|
||||
console.log(`Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
|
||||
socket.end();
|
||||
if (incomingTermReason === null) {
|
||||
incomingTermReason = 'rejected';
|
||||
this.incrementTerminationStat('incoming', 'rejected');
|
||||
}
|
||||
cleanupOnce();
|
||||
return;
|
||||
}
|
||||
} else if (!isDefaultAllowed && !serverName) {
|
||||
console.log(`Connection rejected: No SNI and IP ${remoteIP} not in default allowed list`);
|
||||
socket.end();
|
||||
if (incomingTermReason === null) {
|
||||
incomingTermReason = 'rejected';
|
||||
this.incrementTerminationStat('incoming', 'rejected');
|
||||
}
|
||||
cleanupOnce();
|
||||
return;
|
||||
} else {
|
||||
console.log(`Connection allowed: IP ${remoteIP} is in default allowed list`);
|
||||
}
|
||||
|
||||
// Determine target host.
|
||||
const domainConfig = serverName ? findMatchingDomain(serverName) : undefined;
|
||||
const targetHost = domainConfig?.targetIP || this.settings.toHost!;
|
||||
|
||||
// Create connection options.
|
||||
const connectionOptions: plugins.net.NetConnectOpts = {
|
||||
host: targetHost,
|
||||
port: this.settings.toPort,
|
||||
};
|
||||
if (this.settings.preserveSourceIP) {
|
||||
connectionOptions.localAddress = remoteIP.replace('::ffff:', '');
|
||||
}
|
||||
|
||||
// Establish outgoing connection.
|
||||
to = plugins.net.connect(connectionOptions);
|
||||
if (to) {
|
||||
this.outgoingConnectionTimes.set(to, Date.now());
|
||||
}
|
||||
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`);
|
||||
|
||||
// Push back the initial chunk if provided.
|
||||
if (initialChunk) {
|
||||
socket.unshift(initialChunk);
|
||||
}
|
||||
socket.setTimeout(120000);
|
||||
socket.pipe(to!);
|
||||
to!.pipe(socket);
|
||||
|
||||
// Attach event handlers for both sockets.
|
||||
socket.on('error', handleError('incoming'));
|
||||
to!.on('error', handleError('outgoing'));
|
||||
socket.on('close', handleClose('incoming'));
|
||||
to!.on('close', handleClose('outgoing'));
|
||||
socket.on('timeout', () => {
|
||||
console.log(`Timeout on incoming side from ${remoteIP}`);
|
||||
if (incomingTermReason === null) {
|
||||
incomingTermReason = 'timeout';
|
||||
this.incrementTerminationStat('incoming', 'timeout');
|
||||
}
|
||||
cleanupOnce();
|
||||
});
|
||||
to!.on('timeout', () => {
|
||||
console.log(`Timeout on outgoing side from ${remoteIP}`);
|
||||
if (outgoingTermReason === null) {
|
||||
outgoingTermReason = 'timeout';
|
||||
this.incrementTerminationStat('outgoing', 'timeout');
|
||||
}
|
||||
cleanupOnce();
|
||||
});
|
||||
socket.on('end', handleClose('incoming'));
|
||||
to!.on('end', handleClose('outgoing'));
|
||||
};
|
||||
|
||||
// For SNI-enabled connections, set an initial data timeout before waiting for data.
|
||||
if (this.settings.sniEnabled) {
|
||||
// Set an initial timeout for receiving data (e.g., 5 seconds)
|
||||
socket.setTimeout(5000, () => {
|
||||
console.log(`Initial data timeout for ${remoteIP}`);
|
||||
socket.end();
|
||||
cleanupOnce();
|
||||
});
|
||||
|
||||
socket.once('data', (chunk: Buffer) => {
|
||||
// Clear the initial timeout since data has been received
|
||||
socket.setTimeout(0);
|
||||
initialDataReceived = true;
|
||||
const serverName = extractSNI(chunk) || '';
|
||||
console.log(`Received connection from ${remoteIP} with SNI: ${serverName}`);
|
||||
setupConnection(serverName, chunk);
|
||||
});
|
||||
} else {
|
||||
// For non-SNI connections, simply check defaultAllowedIPs.
|
||||
initialDataReceived = true;
|
||||
if (!this.settings.defaultAllowedIPs || !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
||||
console.log(`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
|
||||
socket.end();
|
||||
if (incomingTermReason === null) {
|
||||
incomingTermReason = 'rejected';
|
||||
this.incrementTerminationStat('incoming', 'rejected');
|
||||
}
|
||||
cleanupOnce();
|
||||
return;
|
||||
}
|
||||
setupConnection('');
|
||||
}
|
||||
})
|
||||
.on('error', (err: Error) => {
|
||||
console.log(`Server Error: ${err.message}`);
|
||||
})
|
||||
.listen(this.settings.fromPort, () => {
|
||||
console.log(`PortProxy -> OK: Now listening on port ${this.settings.fromPort}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`);
|
||||
});
|
||||
|
||||
// Log active connection count, longest running connection durations,
|
||||
// and termination statistics every 10 seconds.
|
||||
this.connectionLogger = setInterval(() => {
|
||||
const now = Date.now();
|
||||
let maxIncoming = 0;
|
||||
for (const startTime of this.incomingConnectionTimes.values()) {
|
||||
const duration = now - startTime;
|
||||
if (duration > maxIncoming) {
|
||||
maxIncoming = duration;
|
||||
}
|
||||
}
|
||||
let maxOutgoing = 0;
|
||||
for (const startTime of this.outgoingConnectionTimes.values()) {
|
||||
const duration = now - startTime;
|
||||
if (duration > maxOutgoing) {
|
||||
maxOutgoing = duration;
|
||||
}
|
||||
}
|
||||
console.log(`(Interval Log) Active connections: ${this.activeConnections.size}. Longest running incoming: ${plugins.prettyMs(maxIncoming)}, outgoing: ${plugins.prettyMs(maxOutgoing)}. Termination stats (incoming): ${JSON.stringify(this.terminationStats.incoming)}, (outgoing): ${JSON.stringify(this.terminationStats.outgoing)}`);
|
||||
}, 10000);
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
const done = plugins.smartpromise.defer();
|
||||
this.netServer.close(() => {
|
||||
done.resolve();
|
||||
});
|
||||
if (this.connectionLogger) {
|
||||
clearInterval(this.connectionLogger);
|
||||
this.connectionLogger = null;
|
||||
}
|
||||
await done.promise;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user