Compare commits
22 Commits
Author | SHA1 | Date | |
---|---|---|---|
1a586dcbd7 | |||
ee03224561 | |||
483cbb3634 | |||
c77b31b72c | |||
8cb8fa1a52 | |||
8e5bb12edb | |||
9be9a426ad | |||
32d875aed9 | |||
4747462cff | |||
70f69ef1ea | |||
2be1c57dd7 | |||
58bd6b4a85 | |||
63e1cd48e8 | |||
5150ddc18e | |||
4bee483954 | |||
4328d4365f | |||
21e9d0fd0d | |||
6c0c65bb1a | |||
23f61eb60b | |||
a4ad6c59c1 | |||
e67eff0fcc | |||
e5db2e171c |
74
changelog.md
74
changelog.md
@ -1,5 +1,79 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 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)
|
## 2025-02-04 - 3.1.4 - fix(core)
|
||||||
No uncommitted changes. Preparing for potential minor improvements or bug fixes.
|
No uncommitted changes. Preparing for potential minor improvements or bug fixes.
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@push.rocks/smartproxy",
|
"name": "@push.rocks/smartproxy",
|
||||||
"version": "3.1.4",
|
"version": "3.7.0",
|
||||||
"private": false,
|
"private": false,
|
||||||
"description": "a proxy for handling high workloads of proxying",
|
"description": "a proxy for handling high workloads of proxying",
|
||||||
"main": "dist_ts/index.js",
|
"main": "dist_ts/index.js",
|
||||||
@ -30,7 +30,9 @@
|
|||||||
"@push.rocks/smartstring": "^4.0.15",
|
"@push.rocks/smartstring": "^4.0.15",
|
||||||
"@tsclass/tsclass": "^4.4.0",
|
"@tsclass/tsclass": "^4.4.0",
|
||||||
"@types/ws": "^8.5.14",
|
"@types/ws": "^8.5.14",
|
||||||
"ws": "^8.18.0"
|
"ws": "^8.18.0",
|
||||||
|
"minimatch": "^9.0.3",
|
||||||
|
"@types/minimatch": "^5.1.2"
|
||||||
},
|
},
|
||||||
"files": [
|
"files": [
|
||||||
"ts/**/*",
|
"ts/**/*",
|
||||||
|
6
pnpm-lock.yaml
generated
6
pnpm-lock.yaml
generated
@ -26,9 +26,15 @@ importers:
|
|||||||
'@tsclass/tsclass':
|
'@tsclass/tsclass':
|
||||||
specifier: ^4.4.0
|
specifier: ^4.4.0
|
||||||
version: 4.4.0
|
version: 4.4.0
|
||||||
|
'@types/minimatch':
|
||||||
|
specifier: ^5.1.2
|
||||||
|
version: 5.1.2
|
||||||
'@types/ws':
|
'@types/ws':
|
||||||
specifier: ^8.5.14
|
specifier: ^8.5.14
|
||||||
version: 8.5.14
|
version: 8.5.14
|
||||||
|
minimatch:
|
||||||
|
specifier: ^9.0.3
|
||||||
|
version: 9.0.5
|
||||||
ws:
|
ws:
|
||||||
specifier: ^8.18.0
|
specifier: ^8.18.0
|
||||||
version: 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 = {
|
export const commitinfo = {
|
||||||
name: '@push.rocks/smartproxy',
|
name: '@push.rocks/smartproxy',
|
||||||
version: '3.1.4',
|
version: '3.7.0',
|
||||||
description: 'a proxy for handling high workloads of proxying'
|
description: 'a proxy for handling high workloads of proxying'
|
||||||
}
|
}
|
||||||
|
@ -2,9 +2,10 @@
|
|||||||
import * as http from 'http';
|
import * as http from 'http';
|
||||||
import * as https from 'https';
|
import * as https from 'https';
|
||||||
import * as net from 'net';
|
import * as net from 'net';
|
||||||
|
import * as tls from 'tls';
|
||||||
import * as url from 'url';
|
import * as url from 'url';
|
||||||
|
|
||||||
export { http, https, net, url };
|
export { http, https, net, tls, url };
|
||||||
|
|
||||||
// tsclass scope
|
// tsclass scope
|
||||||
import * as tsclass from '@tsclass/tsclass';
|
import * as tsclass from '@tsclass/tsclass';
|
||||||
@ -23,5 +24,6 @@ export { lik, smartdelay, smartrequest, smartpromise, smartstring };
|
|||||||
// third party scope
|
// third party scope
|
||||||
import * as ws from 'ws';
|
import * as ws from 'ws';
|
||||||
import wsDefault from 'ws';
|
import wsDefault from 'ws';
|
||||||
|
import { minimatch } from 'minimatch';
|
||||||
|
|
||||||
export { wsDefault, ws };
|
export { wsDefault, ws, minimatch };
|
||||||
|
@ -1,14 +1,34 @@
|
|||||||
import * as plugins from './smartproxy.plugins.js';
|
import * as plugins from './smartproxy.plugins.js';
|
||||||
import * as net from 'net';
|
|
||||||
|
|
||||||
export class PortProxy {
|
|
||||||
netServer: plugins.net.Server;
|
export interface DomainConfig {
|
||||||
|
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 ProxySettings extends plugins.tls.TlsOptions {
|
||||||
|
// Port configuration
|
||||||
fromPort: number;
|
fromPort: number;
|
||||||
toPort: number;
|
toPort: number;
|
||||||
|
toHost?: string; // Target host to proxy to, defaults to 'localhost'
|
||||||
|
|
||||||
constructor(fromPortArg: number, toPortArg: number) {
|
// Domain and security settings
|
||||||
this.fromPort = fromPortArg;
|
domains: DomainConfig[];
|
||||||
this.toPort = toPortArg;
|
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
|
||||||
|
}
|
||||||
|
|
||||||
|
export class PortProxy {
|
||||||
|
netServer: plugins.net.Server | plugins.tls.Server;
|
||||||
|
settings: ProxySettings;
|
||||||
|
|
||||||
|
constructor(settings: ProxySettings) {
|
||||||
|
this.settings = {
|
||||||
|
...settings,
|
||||||
|
toHost: settings.toHost || 'localhost'
|
||||||
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
public async start() {
|
public async start() {
|
||||||
@ -22,42 +42,141 @@ export class PortProxy {
|
|||||||
from.destroy();
|
from.destroy();
|
||||||
to.destroy();
|
to.destroy();
|
||||||
};
|
};
|
||||||
this.netServer = net
|
const normalizeIP = (ip: string): string[] => {
|
||||||
.createServer((from) => {
|
// Handle IPv4-mapped IPv6 addresses
|
||||||
const to = net.createConnection({
|
if (ip.startsWith('::ffff:')) {
|
||||||
host: 'localhost',
|
const ipv4 = ip.slice(7); // Remove '::ffff:' prefix
|
||||||
port: this.toPort,
|
return [ip, ipv4];
|
||||||
});
|
}
|
||||||
from.setTimeout(120000);
|
// Handle IPv4 addresses by adding IPv4-mapped IPv6 variant
|
||||||
from.pipe(to);
|
if (ip.match(/^\d{1,3}(\.\d{1,3}){3}$/)) {
|
||||||
to.pipe(from);
|
return [ip, `::ffff:${ip}`];
|
||||||
from.on('error', () => {
|
}
|
||||||
cleanUpSockets(from, to);
|
return [ip];
|
||||||
});
|
};
|
||||||
to.on('error', () => {
|
|
||||||
cleanUpSockets(from, to);
|
const isAllowed = (value: string, patterns: string[]): boolean => {
|
||||||
});
|
// Expand patterns to include both IPv4 and IPv6 variants
|
||||||
from.on('close', () => {
|
const expandedPatterns = patterns.flatMap(normalizeIP);
|
||||||
cleanUpSockets(from, to);
|
// Check if any variant of the IP matches any expanded pattern
|
||||||
});
|
return normalizeIP(value).some(ip =>
|
||||||
to.on('close', () => {
|
expandedPatterns.some(pattern => plugins.minimatch(ip, pattern))
|
||||||
cleanUpSockets(from, to);
|
);
|
||||||
});
|
};
|
||||||
from.on('timeout', () => {
|
|
||||||
cleanUpSockets(from, to);
|
const findMatchingDomain = (serverName: string): DomainConfig | undefined => {
|
||||||
});
|
return this.settings.domains.find(config => plugins.minimatch(serverName, config.domain));
|
||||||
to.on('timeout', () => {
|
};
|
||||||
cleanUpSockets(from, to);
|
|
||||||
});
|
const server = this.settings.sniEnabled
|
||||||
from.on('end', () => {
|
? plugins.tls.createServer({
|
||||||
cleanUpSockets(from, to);
|
...this.settings,
|
||||||
});
|
SNICallback: (serverName: string, cb: (err: Error | null, ctx?: plugins.tls.SecureContext) => void) => {
|
||||||
to.on('end', () => {
|
console.log(`SNI request for domain: ${serverName}`);
|
||||||
cleanUpSockets(from, to);
|
const domainConfig = findMatchingDomain(serverName);
|
||||||
});
|
if (!domainConfig) {
|
||||||
|
// Always allow SNI for default IPs, even if domain doesn't match
|
||||||
|
console.log(`SNI domain ${serverName} not found, will check IP during connection`);
|
||||||
|
}
|
||||||
|
// Create context with the provided TLS settings
|
||||||
|
const ctx = plugins.tls.createSecureContext(this.settings);
|
||||||
|
cb(null, ctx);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
: plugins.net.createServer();
|
||||||
|
|
||||||
|
const handleConnection = (from: plugins.net.Socket | plugins.tls.TLSSocket) => {
|
||||||
|
const remoteIP = from.remoteAddress || '';
|
||||||
|
let serverName = '';
|
||||||
|
|
||||||
|
// First check if this IP is in the default allowed list
|
||||||
|
const isDefaultAllowed = this.settings.defaultAllowedIPs && isAllowed(remoteIP, this.settings.defaultAllowedIPs);
|
||||||
|
|
||||||
|
if (this.settings.sniEnabled && from instanceof plugins.tls.TLSSocket) {
|
||||||
|
serverName = (from as any).servername || '';
|
||||||
|
console.log(`TLS Connection from ${remoteIP} for domain: ${serverName}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// If IP is in defaultAllowedIPs, allow the connection regardless of SNI
|
||||||
|
if (isDefaultAllowed) {
|
||||||
|
console.log(`Connection allowed: IP ${remoteIP} is in default allowed list`);
|
||||||
|
} else if (this.settings.sniEnabled && serverName) {
|
||||||
|
// For SNI connections that aren't in default list, check domain-specific rules
|
||||||
|
const domainConfig = findMatchingDomain(serverName);
|
||||||
|
if (!domainConfig) {
|
||||||
|
console.log(`Connection rejected: No matching domain config for ${serverName} from IP ${remoteIP}`);
|
||||||
|
from.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!isAllowed(remoteIP, domainConfig.allowedIPs)) {
|
||||||
|
console.log(`Connection rejected: IP ${remoteIP} not allowed for domain ${serverName}`);
|
||||||
|
from.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// Non-SNI connection and not in default list
|
||||||
|
console.log(`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
|
||||||
|
from.end();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Determine target host - use domain-specific targetIP if available
|
||||||
|
const domainConfig = serverName ? findMatchingDomain(serverName) : undefined;
|
||||||
|
const targetHost = domainConfig?.targetIP || this.settings.toHost!;
|
||||||
|
|
||||||
|
// Create connection, optionally preserving the client's source IP
|
||||||
|
const connectionOptions: plugins.net.NetConnectOpts = {
|
||||||
|
host: targetHost,
|
||||||
|
port: this.settings.toPort,
|
||||||
|
};
|
||||||
|
|
||||||
|
// Only set localAddress if preserveSourceIP is enabled
|
||||||
|
if (this.settings.preserveSourceIP) {
|
||||||
|
connectionOptions.localAddress = remoteIP.replace('::ffff:', ''); // Remove IPv6 mapping if present
|
||||||
|
}
|
||||||
|
|
||||||
|
const to = plugins.net.createConnection(connectionOptions);
|
||||||
|
console.log(`Connection established: ${remoteIP} -> ${targetHost}:${this.settings.toPort}${serverName ? ` (SNI: ${serverName})` : ''}`);
|
||||||
|
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);
|
||||||
|
});
|
||||||
|
to.on('timeout', () => {
|
||||||
|
cleanUpSockets(from, to);
|
||||||
|
});
|
||||||
|
from.on('end', () => {
|
||||||
|
cleanUpSockets(from, to);
|
||||||
|
});
|
||||||
|
to.on('end', () => {
|
||||||
|
cleanUpSockets(from, to);
|
||||||
|
});
|
||||||
|
};
|
||||||
|
|
||||||
|
this.netServer = server
|
||||||
|
.on('connection', handleConnection)
|
||||||
|
.on('secureConnection', handleConnection)
|
||||||
|
.on('tlsClientError', (err, tlsSocket) => {
|
||||||
|
console.log(`TLS Client Error: ${err.message}`);
|
||||||
})
|
})
|
||||||
.listen(this.fromPort);
|
.on('error', (err) => {
|
||||||
console.log(`PortProxy -> OK: Now listening on port ${this.fromPort}`);
|
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 enabled)' : ''}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
public async stop() {
|
public async stop() {
|
||||||
|
Reference in New Issue
Block a user