Compare commits
40 Commits
Author | SHA1 | Date | |
---|---|---|---|
ad8c667dec | |||
942e0649c8 | |||
59625167b4 | |||
385d984727 | |||
a959c2ad0e | |||
88f5436c9a | |||
06101cd1b1 | |||
438d65107d | |||
233b26c308 | |||
ba787729e8 | |||
4854d7c38d | |||
e841bda003 | |||
477b930a37 | |||
935bd95723 | |||
0e33ea4eb5 | |||
6181065963 | |||
1a586dcbd7 | |||
ee03224561 | |||
483cbb3634 | |||
c77b31b72c | |||
8cb8fa1a52 | |||
8e5bb12edb | |||
9be9a426ad | |||
32d875aed9 | |||
4747462cff | |||
70f69ef1ea | |||
2be1c57dd7 | |||
58bd6b4a85 | |||
63e1cd48e8 | |||
5150ddc18e | |||
4bee483954 | |||
4328d4365f | |||
21e9d0fd0d | |||
6c0c65bb1a | |||
23f61eb60b | |||
a4ad6c59c1 | |||
e67eff0fcc | |||
e5db2e171c | |||
7389072841 | |||
9dd56a9362 |
129
changelog.md
129
changelog.md
@ -1,5 +1,134 @@
|
||||
# Changelog
|
||||
|
||||
## 2025-02-21 - 3.9.2 - fix(PortProxy)
|
||||
Improve timeout handling for port proxy connections
|
||||
|
||||
- Added console logging for both incoming and outgoing side timeouts in the PortProxy class.
|
||||
- Updated the timeout event handlers to ensure proper cleanup of connections.
|
||||
|
||||
## 2025-02-21 - 3.9.1 - fix(dependencies)
|
||||
Ensure correct ordering of dependencies and improve logging format.
|
||||
|
||||
- Reorder dependencies in package.json for better readability.
|
||||
- Use pretty-ms for displaying time durations in logs.
|
||||
|
||||
## 2025-02-21 - 3.9.0 - feat(smartproxy.portproxy)
|
||||
Add logging of connection durations to PortProxy
|
||||
|
||||
- Track start times for incoming and outgoing connections.
|
||||
- Log duration of longest running incoming and outgoing connections every 10 seconds.
|
||||
|
||||
## 2025-02-21 - 3.8.1 - fix(plugins)
|
||||
Simplified plugin import structure across codebase
|
||||
|
||||
- Consolidated plugin imports under a single 'plugins.ts' file.
|
||||
- Replaced individual plugin imports in smartproxy files with the consolidated plugin imports.
|
||||
- Fixed error handling for early socket errors in PortProxy setup.
|
||||
|
||||
## 2025-02-21 - 3.8.0 - feat(PortProxy)
|
||||
Add active connection tracking and logging in PortProxy
|
||||
|
||||
- Implemented a feature to track active incoming connections in PortProxy.
|
||||
- Active connections are now logged every 10 seconds for monitoring purposes.
|
||||
- Refactored connection handling to ensure proper cleanup and logging.
|
||||
|
||||
## 2025-02-21 - 3.7.3 - fix(portproxy)
|
||||
Fix handling of connections in PortProxy to improve stability and performance.
|
||||
|
||||
- Improved IP normalization and matching
|
||||
- Better SNI extraction and handling for TLS
|
||||
- Streamlined connection handling with robust error management
|
||||
|
||||
## 2025-02-21 - 3.7.2 - fix(PortProxy)
|
||||
Improve SNICallback and connection handling in PortProxy
|
||||
|
||||
- Fixed SNICallback to create minimal TLS context for SNI.
|
||||
- Changed connection setup to use net.connect for raw passthrough.
|
||||
|
||||
## 2025-02-21 - 3.7.1 - fix(smartproxy.portproxy)
|
||||
Optimize SNI handling by simplifying context creation
|
||||
|
||||
- Removed unnecessary SecureContext creation for SNI requests in PortProxy
|
||||
- Improved handling of SNI passthrough by acknowledging requests without context creation
|
||||
|
||||
## 2025-02-21 - 3.7.0 - feat(PortProxy)
|
||||
Add optional source IP preservation support in PortProxy
|
||||
|
||||
- Added a feature to optionally preserve the client's source IP when proxying connections.
|
||||
- Enhanced test cases to include scenarios for source IP preservation.
|
||||
|
||||
## 2025-02-21 - 3.6.0 - feat(PortProxy)
|
||||
Add feature to preserve original client IP through chained proxies
|
||||
|
||||
- Added support to bind local address in PortProxy to preserve original client IP.
|
||||
- Implemented test for chained proxies to ensure client IP is preserved.
|
||||
|
||||
## 2025-02-21 - 3.5.0 - feat(PortProxy)
|
||||
Enhance PortProxy to support domain-specific target IPs
|
||||
|
||||
- Introduced support for domain-specific target IP configurations in PortProxy.
|
||||
- Updated connection handling to prioritize domain-specific target IPs if provided.
|
||||
- Added tests to verify forwarding based on domain-specific target IPs.
|
||||
|
||||
## 2025-02-21 - 3.4.4 - fix(PortProxy)
|
||||
Fixed handling of SNI domain connections and IP allowance checks
|
||||
|
||||
- Improved logic for handling SNI domain checks, ensuring IPs are correctly verified.
|
||||
- Fixed issue where default allowed IPs were not being checked correctly for non-SNI connections.
|
||||
- Revised the SNICallback behavior to handle connections more gracefully when domain configurations are unavailable.
|
||||
|
||||
## 2025-02-21 - 3.4.3 - fix(PortProxy)
|
||||
Fixed indentation issue and ensured proper cleanup of sockets in PortProxy
|
||||
|
||||
- Fixed inconsistent indentation in IP allowance check.
|
||||
- Ensured proper cleanup of sockets on connection end in PortProxy.
|
||||
|
||||
## 2025-02-21 - 3.4.2 - fix(smartproxy)
|
||||
Enhance SSL/TLS handling with SNI and error logging
|
||||
|
||||
- Improved handling for SNI-enabled and non-SNI connections
|
||||
- Added detailed logging for connection establishment and rejections
|
||||
- Introduced error logging for TLS client errors and server errors
|
||||
|
||||
## 2025-02-21 - 3.4.1 - fix(PortProxy)
|
||||
Normalize IP addresses for port proxy to handle IPv4-mapped IPv6 addresses.
|
||||
|
||||
- Improved IP normalization logic in PortProxy to support IPv4-mapped IPv6 addresses.
|
||||
- Updated isAllowed function to expand patterns for better matching accuracy.
|
||||
|
||||
## 2025-02-21 - 3.4.0 - feat(PortProxy)
|
||||
Enhanced PortProxy with custom target host and improved testing
|
||||
|
||||
- PortProxy constructor now accepts 'fromPort', 'toPort', and optional 'toHost' directly from settings
|
||||
- Refactored test cases to cover forwarding to the custom host
|
||||
- Added support to handle multiple concurrent connections
|
||||
- Refactored internal connection handling logic to utilize default configurations
|
||||
|
||||
## 2025-02-21 - 3.3.1 - fix(PortProxy)
|
||||
fixed import usage of net and tls libraries for PortProxy
|
||||
|
||||
- Corrected the use of plugins for importing 'tls' and 'net' libraries in the PortProxy module.
|
||||
- Updated the constructor of PortProxy to accept combined tls options with ProxySettings.
|
||||
|
||||
## 2025-02-21 - 3.3.0 - feat(PortProxy)
|
||||
Enhanced PortProxy with domain and IP filtering, SNI support, and minimatch integration
|
||||
|
||||
- Added new ProxySettings interface to configure domain patterns, SNI, and default allowed IPs.
|
||||
- Integrated minimatch to filter allowed IPs and domains.
|
||||
- Enabled SNI support for PortProxy connections.
|
||||
- Updated port proxy test to accommodate new settings.
|
||||
|
||||
## 2025-02-04 - 3.2.0 - feat(testing)
|
||||
Added a comprehensive test suite for the PortProxy class
|
||||
|
||||
- Set up a test environment for PortProxy using net.Server.
|
||||
- Test coverage includes starting and stopping the proxy, handling TCP connections, concurrent connections, and timeouts.
|
||||
- Ensures proper resource cleanup after tests.
|
||||
|
||||
## 2025-02-04 - 3.1.4 - fix(core)
|
||||
No uncommitted changes. Preparing for potential minor improvements or bug fixes.
|
||||
|
||||
|
||||
## 2025-02-04 - 3.1.3 - fix(networkproxy)
|
||||
Refactor and improve WebSocket handling and request processing
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@push.rocks/smartproxy",
|
||||
"version": "3.1.3",
|
||||
"version": "3.9.2",
|
||||
"private": false,
|
||||
"description": "a proxy for handling high workloads of proxying",
|
||||
"main": "dist_ts/index.js",
|
||||
@ -29,7 +29,10 @@
|
||||
"@push.rocks/smartrequest": "^2.0.23",
|
||||
"@push.rocks/smartstring": "^4.0.15",
|
||||
"@tsclass/tsclass": "^4.4.0",
|
||||
"@types/minimatch": "^5.1.2",
|
||||
"@types/ws": "^8.5.14",
|
||||
"minimatch": "^9.0.3",
|
||||
"pretty-ms": "^9.2.0",
|
||||
"ws": "^8.18.0"
|
||||
},
|
||||
"files": [
|
||||
|
9
pnpm-lock.yaml
generated
9
pnpm-lock.yaml
generated
@ -26,9 +26,18 @@ importers:
|
||||
'@tsclass/tsclass':
|
||||
specifier: ^4.4.0
|
||||
version: 4.4.0
|
||||
'@types/minimatch':
|
||||
specifier: ^5.1.2
|
||||
version: 5.1.2
|
||||
'@types/ws':
|
||||
specifier: ^8.5.14
|
||||
version: 8.5.14
|
||||
minimatch:
|
||||
specifier: ^9.0.3
|
||||
version: 9.0.5
|
||||
pretty-ms:
|
||||
specifier: ^9.2.0
|
||||
version: 9.2.0
|
||||
ws:
|
||||
specifier: ^8.18.0
|
||||
version: 8.18.0
|
||||
|
253
test/test.portproxy.ts
Normal file
253
test/test.portproxy.ts
Normal file
@ -0,0 +1,253 @@
|
||||
import { expect, tap } from '@push.rocks/tapbundle';
|
||||
import * as net from 'net';
|
||||
import { PortProxy } from '../ts/smartproxy.portproxy.js';
|
||||
|
||||
let testServer: net.Server;
|
||||
let portProxy: PortProxy;
|
||||
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> {
|
||||
return new Promise((resolve) => {
|
||||
const server = net.createServer((socket) => {
|
||||
socket.on('data', (data) => {
|
||||
// Echo the received data back
|
||||
socket.write(`Echo: ${data.toString()}`);
|
||||
});
|
||||
|
||||
socket.on('error', (error) => {
|
||||
console.error('[Test Server] Socket error:', error);
|
||||
});
|
||||
});
|
||||
|
||||
server.listen(port, () => {
|
||||
console.log(`[Test Server] Listening on port ${port}`);
|
||||
resolve(server);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Helper function to create a test client connection
|
||||
function createTestClient(port: number, data: string): Promise<string> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const client = new net.Socket();
|
||||
let response = '';
|
||||
|
||||
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', () => {
|
||||
resolve(response);
|
||||
});
|
||||
|
||||
client.on('error', (error) => {
|
||||
reject(error);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Setup test environment
|
||||
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: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1']
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('should start port proxy', async () => {
|
||||
await portProxy.start();
|
||||
expect(portProxy.netServer.listening).toBeTrue();
|
||||
});
|
||||
|
||||
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}`);
|
||||
});
|
||||
|
||||
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: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1']
|
||||
});
|
||||
|
||||
await customHostProxy.start();
|
||||
const response = await createTestClient(PROXY_PORT + 1, TEST_DATA);
|
||||
expect(response).toEqual(`Echo: ${TEST_DATA}`);
|
||||
await customHostProxy.stop();
|
||||
});
|
||||
|
||||
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);
|
||||
|
||||
// Create a proxy with domain-specific target 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']
|
||||
});
|
||||
|
||||
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}`);
|
||||
|
||||
await domainProxy.stop();
|
||||
await domainProxy2.stop();
|
||||
await new Promise<void>((resolve) => testServer2.close(() => resolve()));
|
||||
});
|
||||
|
||||
tap.test('should handle multiple concurrent connections', async () => {
|
||||
const concurrentRequests = 5;
|
||||
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}`);
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('should handle connection timeouts', async () => {
|
||||
const client = new net.Socket();
|
||||
|
||||
await new Promise<void>((resolve) => {
|
||||
client.connect(PROXY_PORT, 'localhost', () => {
|
||||
// Don't send any data, just wait for timeout
|
||||
client.on('close', () => {
|
||||
resolve();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
tap.test('should stop port proxy', async () => {
|
||||
await portProxy.stop();
|
||||
expect(portProxy.netServer.listening).toBeFalse();
|
||||
});
|
||||
|
||||
// Cleanup
|
||||
tap.test('should support optional source IP preservation in chained proxies', async () => {
|
||||
// Test 1: Without IP preservation (default behavior)
|
||||
const firstProxyDefault = new PortProxy({
|
||||
fromPort: PROXY_PORT + 4,
|
||||
toPort: PROXY_PORT + 5,
|
||||
toHost: 'localhost',
|
||||
domains: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1']
|
||||
});
|
||||
|
||||
const secondProxyDefault = new PortProxy({
|
||||
fromPort: PROXY_PORT + 5,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
toHost: 'localhost',
|
||||
domains: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1', '::ffff:127.0.0.1']
|
||||
});
|
||||
|
||||
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();
|
||||
|
||||
// Test 2: With IP preservation
|
||||
const firstProxyPreserved = new PortProxy({
|
||||
fromPort: PROXY_PORT + 6,
|
||||
toPort: PROXY_PORT + 7,
|
||||
toHost: 'localhost',
|
||||
domains: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
preserveSourceIP: true
|
||||
});
|
||||
|
||||
const secondProxyPreserved = new PortProxy({
|
||||
fromPort: PROXY_PORT + 7,
|
||||
toPort: TEST_SERVER_PORT,
|
||||
toHost: 'localhost',
|
||||
domains: [],
|
||||
sniEnabled: false,
|
||||
defaultAllowedIPs: ['127.0.0.1'],
|
||||
preserveSourceIP: true
|
||||
});
|
||||
|
||||
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();
|
||||
});
|
||||
|
||||
tap.test('cleanup port proxy test environment', async () => {
|
||||
await new Promise<void>((resolve) => testServer.close(() => resolve()));
|
||||
});
|
||||
|
||||
process.on('exit', () => {
|
||||
if (testServer) {
|
||||
testServer.close();
|
||||
}
|
||||
if (portProxy && portProxy.netServer) {
|
||||
portProxy.stop();
|
||||
}
|
||||
});
|
||||
|
||||
export default tap.start();
|
@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartproxy',
|
||||
version: '3.1.3',
|
||||
version: '3.9.2',
|
||||
description: 'a proxy for handling high workloads of proxying'
|
||||
}
|
||||
|
@ -2,9 +2,10 @@
|
||||
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, url };
|
||||
export { http, https, net, tls, url };
|
||||
|
||||
// tsclass scope
|
||||
import * as tsclass from '@tsclass/tsclass';
|
||||
@ -21,7 +22,9 @@ import * as smartstring from '@push.rocks/smartstring';
|
||||
export { lik, smartdelay, smartrequest, smartpromise, smartstring };
|
||||
|
||||
// third party scope
|
||||
import prettyMs from 'pretty-ms';
|
||||
import * as ws from 'ws';
|
||||
import wsDefault from 'ws';
|
||||
import { minimatch } from 'minimatch';
|
||||
|
||||
export { wsDefault, ws };
|
||||
export { prettyMs, ws, wsDefault, minimatch };
|
@ -1,4 +1,4 @@
|
||||
import * as plugins from './smartproxy.plugins.js';
|
||||
import * as plugins from './plugins.js';
|
||||
import { ProxyRouter } from './smartproxy.classes.router.js';
|
||||
import * as fs from 'fs';
|
||||
import * as path from 'path';
|
||||
|
@ -1,4 +1,4 @@
|
||||
import * as plugins from './smartproxy.plugins.js';
|
||||
import * as plugins from './plugins.js';
|
||||
|
||||
export class ProxyRouter {
|
||||
public reverseProxyConfigs: plugins.tsclass.network.IReverseProxyConfig[] = [];
|
||||
|
@ -1,4 +1,4 @@
|
||||
import * as plugins from './smartproxy.plugins.js';
|
||||
import * as plugins from './plugins.js';
|
||||
|
||||
export class SslRedirect {
|
||||
httpServer: plugins.http.Server;
|
||||
|
@ -1,14 +1,133 @@
|
||||
import * as plugins from './smartproxy.plugins.js';
|
||||
import * as net from 'net';
|
||||
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;
|
||||
fromPort: number;
|
||||
toPort: number;
|
||||
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;
|
||||
|
||||
constructor(fromPortArg: number, toPortArg: number) {
|
||||
this.fromPort = fromPortArg;
|
||||
this.toPort = toPortArg;
|
||||
constructor(settings: IProxySettings) {
|
||||
this.settings = {
|
||||
...settings,
|
||||
toHost: settings.toHost || 'localhost'
|
||||
};
|
||||
}
|
||||
|
||||
public async start() {
|
||||
@ -22,42 +141,202 @@ export class PortProxy {
|
||||
from.destroy();
|
||||
to.destroy();
|
||||
};
|
||||
this.netServer = net
|
||||
.createServer((from) => {
|
||||
const to = net.createConnection({
|
||||
host: 'localhost',
|
||||
port: this.toPort,
|
||||
});
|
||||
from.setTimeout(120000);
|
||||
from.pipe(to);
|
||||
to.pipe(from);
|
||||
from.on('error', () => {
|
||||
cleanUpSockets(from, to);
|
||||
});
|
||||
to.on('error', () => {
|
||||
cleanUpSockets(from, to);
|
||||
});
|
||||
from.on('close', () => {
|
||||
cleanUpSockets(from, to);
|
||||
});
|
||||
to.on('close', () => {
|
||||
cleanUpSockets(from, to);
|
||||
});
|
||||
from.on('timeout', () => {
|
||||
cleanUpSockets(from, to);
|
||||
|
||||
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;
|
||||
|
||||
// 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}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Flag to ensure cleanup happens only once.
|
||||
let connectionClosed = false;
|
||||
const cleanupOnce = () => {
|
||||
if (!connectionClosed) {
|
||||
connectionClosed = true;
|
||||
cleanUpSockets(socket, to);
|
||||
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}`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
let to: plugins.net.Socket;
|
||||
|
||||
const handleError = (side: 'incoming' | 'outgoing') => (err: Error) => {
|
||||
const code = (err as any).code;
|
||||
if (code === 'ECONNRESET') {
|
||||
console.log(`ECONNRESET on ${side} side from ${remoteIP}: ${err.message}`);
|
||||
} else {
|
||||
console.log(`Error on ${side} side from ${remoteIP}: ${err.message}`);
|
||||
}
|
||||
cleanupOnce();
|
||||
};
|
||||
|
||||
const handleClose = (side: 'incoming' | 'outgoing') => () => {
|
||||
console.log(`Connection closed on ${side} side from ${remoteIP}`);
|
||||
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();
|
||||
return;
|
||||
}
|
||||
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
|
||||
console.log(`Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
} else if (!isDefaultAllowed && !serverName) {
|
||||
console.log(`Connection rejected: No SNI and IP ${remoteIP} not in default allowed list`);
|
||||
socket.end();
|
||||
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);
|
||||
// Record start time for the outgoing connection.
|
||||
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 error and close 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}`);
|
||||
cleanupOnce();
|
||||
});
|
||||
to.on('timeout', () => {
|
||||
cleanUpSockets(from, to);
|
||||
console.log(`Timeout on outgoing side from ${remoteIP}`);
|
||||
cleanupOnce();
|
||||
});
|
||||
from.on('end', () => {
|
||||
cleanUpSockets(from, to);
|
||||
socket.on('end', handleClose('incoming'));
|
||||
to.on('end', handleClose('outgoing'));
|
||||
};
|
||||
|
||||
// For SNI-enabled connections, peek at the first chunk.
|
||||
if (this.settings.sniEnabled) {
|
||||
socket.once('data', (chunk: Buffer) => {
|
||||
initialDataReceived = true;
|
||||
// Try to extract the server name from the ClientHello.
|
||||
const serverName = extractSNI(chunk) || '';
|
||||
console.log(`Received connection from ${remoteIP} with SNI: ${serverName}`);
|
||||
setupConnection(serverName, chunk);
|
||||
});
|
||||
to.on('end', () => {
|
||||
cleanUpSockets(from, to);
|
||||
});
|
||||
})
|
||||
.listen(this.fromPort);
|
||||
console.log(`PortProxy -> OK: Now listening on port ${this.fromPort}`);
|
||||
} 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();
|
||||
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 and longest running connections 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)}`);
|
||||
}, 10000);
|
||||
}
|
||||
|
||||
public async stop() {
|
||||
@ -65,6 +344,10 @@ export class PortProxy {
|
||||
this.netServer.close(() => {
|
||||
done.resolve();
|
||||
});
|
||||
if (this.connectionLogger) {
|
||||
clearInterval(this.connectionLogger);
|
||||
this.connectionLogger = null;
|
||||
}
|
||||
await done.promise;
|
||||
}
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user