Compare commits
4 Commits
Author | SHA1 | Date | |
---|---|---|---|
f3fd903231 | |||
0e605d9a9d | |||
1718a3b2f2 | |||
568f77e65b |
14
changelog.md
14
changelog.md
@ -1,5 +1,19 @@
|
||||
# Changelog
|
||||
|
||||
## 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
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@push.rocks/smartproxy",
|
||||
"version": "3.27.0",
|
||||
"version": "3.28.1",
|
||||
"private": false,
|
||||
"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",
|
||||
|
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();
|
@ -3,6 +3,6 @@
|
||||
*/
|
||||
export const commitinfo = {
|
||||
name: '@push.rocks/smartproxy',
|
||||
version: '3.27.0',
|
||||
version: '3.28.1',
|
||||
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.'
|
||||
}
|
||||
|
@ -90,7 +90,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
||||
try {
|
||||
// Check if buffer is too small for TLS
|
||||
if (buffer.length < 5) {
|
||||
if (enableLogging) console.log("Buffer too small for TLS header");
|
||||
if (enableLogging) console.log('Buffer too small for TLS header');
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@ -109,7 +109,10 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
||||
// Check record length
|
||||
const recordLength = buffer.readUInt16BE(3);
|
||||
if (buffer.length < 5 + recordLength) {
|
||||
if (enableLogging) console.log(`Buffer too small for TLS record. Expected: ${5 + recordLength}, Got: ${buffer.length}`);
|
||||
if (enableLogging)
|
||||
console.log(
|
||||
`Buffer too small for TLS record. Expected: ${5 + recordLength}, Got: ${buffer.length}`
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@ -136,7 +139,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
||||
|
||||
// Cipher suites
|
||||
if (offset + 2 > buffer.length) {
|
||||
if (enableLogging) console.log("Buffer too small for cipher suites length");
|
||||
if (enableLogging) console.log('Buffer too small for cipher suites length');
|
||||
return undefined;
|
||||
}
|
||||
const cipherSuitesLength = buffer.readUInt16BE(offset);
|
||||
@ -145,7 +148,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
||||
|
||||
// Compression methods
|
||||
if (offset + 1 > buffer.length) {
|
||||
if (enableLogging) console.log("Buffer too small for compression methods length");
|
||||
if (enableLogging) console.log('Buffer too small for compression methods length');
|
||||
return undefined;
|
||||
}
|
||||
const compressionMethodsLength = buffer.readUInt8(offset);
|
||||
@ -154,7 +157,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
||||
|
||||
// Extensions
|
||||
if (offset + 2 > buffer.length) {
|
||||
if (enableLogging) console.log("Buffer too small for extensions length");
|
||||
if (enableLogging) console.log('Buffer too small for extensions length');
|
||||
return undefined;
|
||||
}
|
||||
const extensionsLength = buffer.readUInt16BE(offset);
|
||||
@ -163,7 +166,10 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
||||
const extensionsEnd = offset + extensionsLength;
|
||||
|
||||
if (extensionsEnd > buffer.length) {
|
||||
if (enableLogging) console.log(`Buffer too small for extensions. Expected end: ${extensionsEnd}, Buffer length: ${buffer.length}`);
|
||||
if (enableLogging)
|
||||
console.log(
|
||||
`Buffer too small for extensions. Expected end: ${extensionsEnd}, Buffer length: ${buffer.length}`
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@ -172,13 +178,15 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
||||
const extensionType = buffer.readUInt16BE(offset);
|
||||
const extensionLength = buffer.readUInt16BE(offset + 2);
|
||||
|
||||
if (enableLogging) console.log(`Extension Type: 0x${extensionType.toString(16)}, Length: ${extensionLength}`);
|
||||
if (enableLogging)
|
||||
console.log(`Extension Type: 0x${extensionType.toString(16)}, Length: ${extensionLength}`);
|
||||
|
||||
offset += 4;
|
||||
|
||||
if (extensionType === 0x0000) { // SNI extension
|
||||
if (extensionType === 0x0000) {
|
||||
// SNI extension
|
||||
if (offset + 2 > buffer.length) {
|
||||
if (enableLogging) console.log("Buffer too small for SNI list length");
|
||||
if (enableLogging) console.log('Buffer too small for SNI list length');
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@ -188,7 +196,10 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
||||
const sniListEnd = offset + sniListLength;
|
||||
|
||||
if (sniListEnd > buffer.length) {
|
||||
if (enableLogging) console.log(`Buffer too small for SNI list. Expected end: ${sniListEnd}, Buffer length: ${buffer.length}`);
|
||||
if (enableLogging)
|
||||
console.log(
|
||||
`Buffer too small for SNI list. Expected end: ${sniListEnd}, Buffer length: ${buffer.length}`
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@ -199,9 +210,15 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
||||
|
||||
if (enableLogging) console.log(`Name Type: ${nameType}, Name Length: ${nameLen}`);
|
||||
|
||||
if (nameType === 0) { // host_name
|
||||
if (nameType === 0) {
|
||||
// host_name
|
||||
if (offset + nameLen > buffer.length) {
|
||||
if (enableLogging) console.log(`Buffer too small for hostname. Expected: ${offset + nameLen}, Got: ${buffer.length}`);
|
||||
if (enableLogging)
|
||||
console.log(
|
||||
`Buffer too small for hostname. Expected: ${offset + nameLen}, Got: ${
|
||||
buffer.length
|
||||
}`
|
||||
);
|
||||
return undefined;
|
||||
}
|
||||
|
||||
@ -218,7 +235,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
||||
}
|
||||
}
|
||||
|
||||
if (enableLogging) console.log("No SNI extension found");
|
||||
if (enableLogging) console.log('No SNI extension found');
|
||||
return undefined;
|
||||
} catch (err) {
|
||||
console.log(`Error extracting SNI: ${err}`);
|
||||
@ -228,7 +245,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
||||
|
||||
// Helper: Check if a port falls within any of the given port ranges
|
||||
const isPortInRanges = (port: number, ranges: Array<{ from: number; to: number }>): boolean => {
|
||||
return ranges.some(range => port >= range.from && port <= range.to);
|
||||
return ranges.some((range) => port >= range.from && port <= range.to);
|
||||
};
|
||||
|
||||
// Helper: Check if a given IP matches any of the glob patterns
|
||||
@ -251,8 +268,8 @@ const isAllowed = (ip: string, patterns: string[]): boolean => {
|
||||
if (normalizedIPVariants.length === 0) return false;
|
||||
|
||||
const expandedPatterns = patterns.flatMap(normalizeIP);
|
||||
return normalizedIPVariants.some(ipVariant =>
|
||||
expandedPatterns.some(pattern => plugins.minimatch(ipVariant, pattern))
|
||||
return normalizedIPVariants.some((ipVariant) =>
|
||||
expandedPatterns.some((pattern) => plugins.minimatch(ipVariant, pattern))
|
||||
);
|
||||
};
|
||||
|
||||
@ -309,11 +326,11 @@ export class PortProxy {
|
||||
targetIP: settingsArg.targetIP || 'localhost',
|
||||
|
||||
// Timeout settings with our enhanced defaults
|
||||
initialDataTimeout: settingsArg.initialDataTimeout || 60000, // 60 seconds for initial data
|
||||
socketTimeout: settingsArg.socketTimeout || 3600000, // 1 hour socket timeout
|
||||
initialDataTimeout: settingsArg.initialDataTimeout || 60000, // 60 seconds for initial handshake
|
||||
socketTimeout: settingsArg.socketTimeout || 2592000000, // 30 days socket timeout
|
||||
inactivityCheckInterval: settingsArg.inactivityCheckInterval || 60000, // 60 seconds interval
|
||||
maxConnectionLifetime: settingsArg.maxConnectionLifetime || 3600000, // 1 hour default lifetime
|
||||
inactivityTimeout: settingsArg.inactivityTimeout || 3600000, // 1 hour inactivity timeout
|
||||
maxConnectionLifetime: settingsArg.maxConnectionLifetime || 2592000000, // 30 days max lifetime
|
||||
inactivityTimeout: settingsArg.inactivityTimeout || 14400000, // 4 hours inactivity timeout
|
||||
|
||||
gracefulShutdownTimeout: settingsArg.gracefulShutdownTimeout || 30000, // 30 seconds
|
||||
|
||||
@ -356,7 +373,7 @@ export class PortProxy {
|
||||
}
|
||||
|
||||
// Get timestamps and filter out entries older than 1 minute
|
||||
const timestamps = this.connectionRateByIP.get(ip)!.filter(time => now - time < minute);
|
||||
const timestamps = this.connectionRateByIP.get(ip)!.filter((time) => now - time < minute);
|
||||
timestamps.push(now);
|
||||
this.connectionRateByIP.set(ip, timestamps);
|
||||
|
||||
@ -505,11 +522,17 @@ export class PortProxy {
|
||||
|
||||
// Log connection details
|
||||
if (this.settings.enableDetailedLogging) {
|
||||
console.log(`[${record.id}] Connection from ${record.remoteIP} on port ${record.localPort} terminated (${reason}).` +
|
||||
` Duration: ${plugins.prettyMs(duration)}, Bytes IN: ${bytesReceived}, OUT: ${bytesSent}, ` +
|
||||
`TLS: ${record.isTLS ? 'Yes' : 'No'}`);
|
||||
console.log(
|
||||
`[${record.id}] Connection from ${record.remoteIP} on port ${record.localPort} terminated (${reason}).` +
|
||||
` Duration: ${plugins.prettyMs(
|
||||
duration
|
||||
)}, Bytes IN: ${bytesReceived}, OUT: ${bytesSent}, ` +
|
||||
`TLS: ${record.isTLS ? 'Yes' : 'No'}`
|
||||
);
|
||||
} else {
|
||||
console.log(`[${record.id}] Connection from ${record.remoteIP} terminated (${reason}). Active connections: ${this.connectionRecords.size}`);
|
||||
console.log(
|
||||
`[${record.id}] Connection from ${record.remoteIP} terminated (${reason}). Active connections: ${this.connectionRecords.size}`
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -556,16 +579,22 @@ export class PortProxy {
|
||||
const localPort = socket.localPort || 0; // The port on which this connection was accepted.
|
||||
|
||||
// Check rate limits
|
||||
if (this.settings.maxConnectionsPerIP &&
|
||||
this.getConnectionCountByIP(remoteIP) >= this.settings.maxConnectionsPerIP) {
|
||||
console.log(`Connection rejected from ${remoteIP}: Maximum connections per IP (${this.settings.maxConnectionsPerIP}) exceeded`);
|
||||
if (
|
||||
this.settings.maxConnectionsPerIP &&
|
||||
this.getConnectionCountByIP(remoteIP) >= this.settings.maxConnectionsPerIP
|
||||
) {
|
||||
console.log(
|
||||
`Connection rejected from ${remoteIP}: Maximum connections per IP (${this.settings.maxConnectionsPerIP}) exceeded`
|
||||
);
|
||||
socket.end();
|
||||
socket.destroy();
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.settings.connectionRateLimitPerMinute && !this.checkConnectionRate(remoteIP)) {
|
||||
console.log(`Connection rejected from ${remoteIP}: Connection rate limit (${this.settings.connectionRateLimitPerMinute}/min) exceeded`);
|
||||
console.log(
|
||||
`Connection rejected from ${remoteIP}: Connection rate limit (${this.settings.connectionRateLimitPerMinute}/min) exceeded`
|
||||
);
|
||||
socket.end();
|
||||
socket.destroy();
|
||||
return;
|
||||
@ -611,7 +640,7 @@ export class PortProxy {
|
||||
localPort: localPort,
|
||||
isTLS: false,
|
||||
tlsHandshakeComplete: false,
|
||||
hasReceivedInitialData: false
|
||||
hasReceivedInitialData: false,
|
||||
};
|
||||
|
||||
// Track connection by IP
|
||||
@ -619,9 +648,13 @@ export class PortProxy {
|
||||
this.connectionRecords.set(connectionId, connectionRecord);
|
||||
|
||||
if (this.settings.enableDetailedLogging) {
|
||||
console.log(`[${connectionId}] New connection from ${remoteIP} on port ${localPort}. Active connections: ${this.connectionRecords.size}`);
|
||||
console.log(
|
||||
`[${connectionId}] New connection from ${remoteIP} on port ${localPort}. Active connections: ${this.connectionRecords.size}`
|
||||
);
|
||||
} else {
|
||||
console.log(`New connection from ${remoteIP} on port ${localPort}. Active connections: ${this.connectionRecords.size}`);
|
||||
console.log(
|
||||
`New connection from ${remoteIP} on port ${localPort}. Active connections: ${this.connectionRecords.size}`
|
||||
);
|
||||
}
|
||||
|
||||
let initialDataReceived = false;
|
||||
@ -661,7 +694,9 @@ export class PortProxy {
|
||||
if (this.settings.sniEnabled) {
|
||||
initialTimeout = setTimeout(() => {
|
||||
if (!initialDataReceived) {
|
||||
console.log(`[${connectionId}] Initial data timeout (${this.settings.initialDataTimeout}ms) for connection from ${remoteIP} on port ${localPort}`);
|
||||
console.log(
|
||||
`[${connectionId}] Initial data timeout (${this.settings.initialDataTimeout}ms) for connection from ${remoteIP} on port ${localPort}`
|
||||
);
|
||||
if (incomingTerminationReason === null) {
|
||||
incomingTerminationReason = 'initial_timeout';
|
||||
this.incrementTerminationStat('incoming', 'initial_timeout');
|
||||
@ -694,7 +729,9 @@ export class PortProxy {
|
||||
connectionRecord.isTLS = true;
|
||||
|
||||
if (this.settings.enableTlsDebugLogging) {
|
||||
console.log(`[${connectionId}] TLS handshake detected from ${remoteIP}, ${chunk.length} bytes`);
|
||||
console.log(
|
||||
`[${connectionId}] TLS handshake detected from ${remoteIP}, ${chunk.length} bytes`
|
||||
);
|
||||
// Try to extract SNI and log detailed debug info
|
||||
extractSNI(chunk, true);
|
||||
}
|
||||
@ -711,12 +748,30 @@ export class PortProxy {
|
||||
|
||||
if (code === 'ECONNRESET') {
|
||||
reason = 'econnreset';
|
||||
console.log(`[${connectionId}] ECONNRESET on ${side} side from ${remoteIP}: ${err.message}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(lastActivityAge)} ago`);
|
||||
console.log(
|
||||
`[${connectionId}] ECONNRESET on ${side} side from ${remoteIP}: ${
|
||||
err.message
|
||||
}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(
|
||||
lastActivityAge
|
||||
)} ago`
|
||||
);
|
||||
} else if (code === 'ETIMEDOUT') {
|
||||
reason = 'etimedout';
|
||||
console.log(`[${connectionId}] ETIMEDOUT on ${side} side from ${remoteIP}: ${err.message}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(lastActivityAge)} ago`);
|
||||
console.log(
|
||||
`[${connectionId}] ETIMEDOUT on ${side} side from ${remoteIP}: ${
|
||||
err.message
|
||||
}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(
|
||||
lastActivityAge
|
||||
)} ago`
|
||||
);
|
||||
} else {
|
||||
console.log(`[${connectionId}] Error on ${side} side from ${remoteIP}: ${err.message}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(lastActivityAge)} ago`);
|
||||
console.log(
|
||||
`[${connectionId}] Error on ${side} side from ${remoteIP}: ${
|
||||
err.message
|
||||
}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(
|
||||
lastActivityAge
|
||||
)} ago`
|
||||
);
|
||||
}
|
||||
|
||||
if (side === 'incoming' && incomingTerminationReason === null) {
|
||||
@ -755,7 +810,12 @@ export class PortProxy {
|
||||
* @param forcedDomain - If provided, overrides SNI/domain lookup (used for port-based routing).
|
||||
* @param overridePort - If provided, use this port for the outgoing connection.
|
||||
*/
|
||||
const setupConnection = (serverName: string, initialChunk?: Buffer, forcedDomain?: IDomainConfig, overridePort?: number) => {
|
||||
const setupConnection = (
|
||||
serverName: string,
|
||||
initialChunk?: Buffer,
|
||||
forcedDomain?: IDomainConfig,
|
||||
overridePort?: number
|
||||
) => {
|
||||
// Clear the initial timeout since we've received data
|
||||
if (initialTimeout) {
|
||||
clearTimeout(initialTimeout);
|
||||
@ -771,16 +831,20 @@ export class PortProxy {
|
||||
connectionRecord.isTLS = true;
|
||||
|
||||
if (this.settings.enableTlsDebugLogging) {
|
||||
console.log(`[${connectionId}] TLS handshake detected in setup, ${initialChunk.length} bytes`);
|
||||
console.log(
|
||||
`[${connectionId}] TLS handshake detected in setup, ${initialChunk.length} bytes`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// If a forcedDomain is provided (port-based routing), use it; otherwise, use SNI-based lookup.
|
||||
const domainConfig = forcedDomain
|
||||
? forcedDomain
|
||||
: (serverName ? this.settings.domainConfigs.find(config =>
|
||||
config.domains.some(d => plugins.minimatch(serverName, d))
|
||||
) : undefined);
|
||||
: serverName
|
||||
? this.settings.domainConfigs.find((config) =>
|
||||
config.domains.some((d) => plugins.minimatch(serverName, d))
|
||||
)
|
||||
: undefined;
|
||||
|
||||
// Save domain config in connection record
|
||||
connectionRecord.domainConfig = domainConfig;
|
||||
@ -789,20 +853,37 @@ export class PortProxy {
|
||||
if (domainConfig) {
|
||||
const effectiveAllowedIPs: string[] = [
|
||||
...domainConfig.allowedIPs,
|
||||
...(this.settings.defaultAllowedIPs || [])
|
||||
...(this.settings.defaultAllowedIPs || []),
|
||||
];
|
||||
const effectiveBlockedIPs: string[] = [
|
||||
...(domainConfig.blockedIPs || []),
|
||||
...(this.settings.defaultBlockedIPs || [])
|
||||
...(this.settings.defaultBlockedIPs || []),
|
||||
];
|
||||
|
||||
// Skip IP validation if allowedIPs is empty
|
||||
if (domainConfig.allowedIPs.length > 0 && !isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)) {
|
||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed for domain ${domainConfig.domains.join(', ')}`);
|
||||
if (
|
||||
domainConfig.allowedIPs.length > 0 &&
|
||||
!isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)
|
||||
) {
|
||||
return rejectIncomingConnection(
|
||||
'rejected',
|
||||
`Connection rejected: IP ${remoteIP} not allowed for domain ${domainConfig.domains.join(
|
||||
', '
|
||||
)}`
|
||||
);
|
||||
}
|
||||
} else if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0) {
|
||||
if (!isGlobIPAllowed(remoteIP, this.settings.defaultAllowedIPs, this.settings.defaultBlockedIPs || [])) {
|
||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed by default allowed list`);
|
||||
if (
|
||||
!isGlobIPAllowed(
|
||||
remoteIP,
|
||||
this.settings.defaultAllowedIPs,
|
||||
this.settings.defaultBlockedIPs || []
|
||||
)
|
||||
) {
|
||||
return rejectIncomingConnection(
|
||||
'rejected',
|
||||
`Connection rejected: IP ${remoteIP} not allowed by default allowed list`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -828,7 +909,9 @@ export class PortProxy {
|
||||
connectionRecord.isTLS = true;
|
||||
|
||||
if (this.settings.enableTlsDebugLogging) {
|
||||
console.log(`[${connectionId}] TLS handshake detected in tempDataHandler, ${chunk.length} bytes`);
|
||||
console.log(
|
||||
`[${connectionId}] TLS handshake detected in tempDataHandler, ${chunk.length} bytes`
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@ -836,7 +919,9 @@ export class PortProxy {
|
||||
const newSize = connectionRecord.pendingDataSize + chunk.length;
|
||||
|
||||
if (this.settings.maxPendingDataSize && newSize > this.settings.maxPendingDataSize) {
|
||||
console.log(`[${connectionId}] Buffer limit exceeded for connection from ${remoteIP}: ${newSize} bytes > ${this.settings.maxPendingDataSize} bytes`);
|
||||
console.log(
|
||||
`[${connectionId}] Buffer limit exceeded for connection from ${remoteIP}: ${newSize} bytes > ${this.settings.maxPendingDataSize} bytes`
|
||||
);
|
||||
socket.end(); // Gracefully close the socket
|
||||
return initiateCleanupOnce('buffer_limit_exceeded');
|
||||
}
|
||||
@ -886,17 +971,25 @@ export class PortProxy {
|
||||
targetSocket.once('error', (err) => {
|
||||
// This handler runs only once during the initial connection phase
|
||||
const code = (err as any).code;
|
||||
console.log(`[${connectionId}] Connection setup error to ${targetHost}:${connectionOptions.port}: ${err.message} (${code})`);
|
||||
console.log(
|
||||
`[${connectionId}] Connection setup error to ${targetHost}:${connectionOptions.port}: ${err.message} (${code})`
|
||||
);
|
||||
|
||||
// Resume the incoming socket to prevent it from hanging
|
||||
socket.resume();
|
||||
|
||||
if (code === 'ECONNREFUSED') {
|
||||
console.log(`[${connectionId}] Target ${targetHost}:${connectionOptions.port} refused connection`);
|
||||
console.log(
|
||||
`[${connectionId}] Target ${targetHost}:${connectionOptions.port} refused connection`
|
||||
);
|
||||
} else if (code === 'ETIMEDOUT') {
|
||||
console.log(`[${connectionId}] Connection to ${targetHost}:${connectionOptions.port} timed out`);
|
||||
console.log(
|
||||
`[${connectionId}] Connection to ${targetHost}:${connectionOptions.port} timed out`
|
||||
);
|
||||
} else if (code === 'ECONNRESET') {
|
||||
console.log(`[${connectionId}] Connection to ${targetHost}:${connectionOptions.port} was reset`);
|
||||
console.log(
|
||||
`[${connectionId}] Connection to ${targetHost}:${connectionOptions.port} was reset`
|
||||
);
|
||||
} else if (code === 'EHOSTUNREACH') {
|
||||
console.log(`[${connectionId}] Host ${targetHost} is unreachable`);
|
||||
}
|
||||
@ -922,7 +1015,11 @@ export class PortProxy {
|
||||
|
||||
// Handle timeouts
|
||||
socket.on('timeout', () => {
|
||||
console.log(`[${connectionId}] Timeout on incoming side from ${remoteIP} after ${plugins.prettyMs(this.settings.socketTimeout || 3600000)}`);
|
||||
console.log(
|
||||
`[${connectionId}] Timeout on incoming side from ${remoteIP} after ${plugins.prettyMs(
|
||||
this.settings.socketTimeout || 3600000
|
||||
)}`
|
||||
);
|
||||
if (incomingTerminationReason === null) {
|
||||
incomingTerminationReason = 'timeout';
|
||||
this.incrementTerminationStat('incoming', 'timeout');
|
||||
@ -931,7 +1028,11 @@ export class PortProxy {
|
||||
});
|
||||
|
||||
targetSocket.on('timeout', () => {
|
||||
console.log(`[${connectionId}] Timeout on outgoing side from ${remoteIP} after ${plugins.prettyMs(this.settings.socketTimeout || 3600000)}`);
|
||||
console.log(
|
||||
`[${connectionId}] Timeout on outgoing side from ${remoteIP} after ${plugins.prettyMs(
|
||||
this.settings.socketTimeout || 3600000
|
||||
)}`
|
||||
);
|
||||
if (outgoingTerminationReason === null) {
|
||||
outgoingTerminationReason = 'timeout';
|
||||
this.incrementTerminationStat('outgoing', 'timeout');
|
||||
@ -965,7 +1066,9 @@ export class PortProxy {
|
||||
const combinedData = Buffer.concat(connectionRecord.pendingData);
|
||||
targetSocket.write(combinedData, (err) => {
|
||||
if (err) {
|
||||
console.log(`[${connectionId}] Error writing pending data to target: ${err.message}`);
|
||||
console.log(
|
||||
`[${connectionId}] Error writing pending data to target: ${err.message}`
|
||||
);
|
||||
return initiateCleanupOnce('write_error');
|
||||
}
|
||||
|
||||
@ -977,13 +1080,25 @@ export class PortProxy {
|
||||
if (this.settings.enableDetailedLogging) {
|
||||
console.log(
|
||||
`[${connectionId}] Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
||||
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})` : ''}` +
|
||||
`${
|
||||
serverName
|
||||
? ` (SNI: ${serverName})`
|
||||
: forcedDomain
|
||||
? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})`
|
||||
: ''
|
||||
}` +
|
||||
` TLS: ${connectionRecord.isTLS ? 'Yes' : 'No'}`
|
||||
);
|
||||
} else {
|
||||
console.log(
|
||||
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
||||
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})` : ''}`
|
||||
`${
|
||||
serverName
|
||||
? ` (SNI: ${serverName})`
|
||||
: forcedDomain
|
||||
? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})`
|
||||
: ''
|
||||
}`
|
||||
);
|
||||
}
|
||||
});
|
||||
@ -996,13 +1111,25 @@ export class PortProxy {
|
||||
if (this.settings.enableDetailedLogging) {
|
||||
console.log(
|
||||
`[${connectionId}] Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
||||
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})` : ''}` +
|
||||
`${
|
||||
serverName
|
||||
? ` (SNI: ${serverName})`
|
||||
: forcedDomain
|
||||
? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})`
|
||||
: ''
|
||||
}` +
|
||||
` TLS: ${connectionRecord.isTLS ? 'Yes' : 'No'}`
|
||||
);
|
||||
} else {
|
||||
console.log(
|
||||
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
||||
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})` : ''}`
|
||||
`${
|
||||
serverName
|
||||
? ` (SNI: ${serverName})`
|
||||
: forcedDomain
|
||||
? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})`
|
||||
: ''
|
||||
}`
|
||||
);
|
||||
}
|
||||
}
|
||||
@ -1019,13 +1146,19 @@ export class PortProxy {
|
||||
// Try to extract SNI from potential renegotiation
|
||||
const newSNI = extractSNI(renegChunk, this.settings.enableTlsDebugLogging);
|
||||
if (newSNI && newSNI !== connectionRecord.lockedDomain) {
|
||||
console.log(`[${connectionId}] Rehandshake detected with different SNI: ${newSNI} vs locked ${connectionRecord.lockedDomain}. Terminating connection.`);
|
||||
console.log(
|
||||
`[${connectionId}] Rehandshake detected with different SNI: ${newSNI} vs locked ${connectionRecord.lockedDomain}. Terminating connection.`
|
||||
);
|
||||
initiateCleanupOnce('sni_mismatch');
|
||||
} else if (newSNI && this.settings.enableDetailedLogging) {
|
||||
console.log(`[${connectionId}] Rehandshake detected with same SNI: ${newSNI}. Allowing.`);
|
||||
console.log(
|
||||
`[${connectionId}] Rehandshake detected with same SNI: ${newSNI}. Allowing.`
|
||||
);
|
||||
}
|
||||
} catch (err) {
|
||||
console.log(`[${connectionId}] Error processing potential renegotiation: ${err}. Allowing connection to continue.`);
|
||||
console.log(
|
||||
`[${connectionId}] Error processing potential renegotiation: ${err}. Allowing connection to continue.`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -1039,7 +1172,11 @@ export class PortProxy {
|
||||
// Set timeout based on domain config or default
|
||||
const connectionTimeout = this.getConnectionTimeout(connectionRecord);
|
||||
connectionRecord.cleanupTimer = setTimeout(() => {
|
||||
console.log(`[${connectionId}] Connection from ${remoteIP} exceeded max lifetime (${plugins.prettyMs(connectionTimeout)}), forcing cleanup.`);
|
||||
console.log(
|
||||
`[${connectionId}] Connection from ${remoteIP} exceeded max lifetime (${plugins.prettyMs(
|
||||
connectionTimeout
|
||||
)}), forcing cleanup.`
|
||||
);
|
||||
initiateCleanupOnce('connection_timeout');
|
||||
}, connectionTimeout);
|
||||
|
||||
@ -1053,7 +1190,9 @@ export class PortProxy {
|
||||
connectionRecord.tlsHandshakeComplete = true;
|
||||
|
||||
if (this.settings.enableTlsDebugLogging) {
|
||||
console.log(`[${connectionId}] TLS handshake complete for connection from ${remoteIP}`);
|
||||
console.log(
|
||||
`[${connectionId}] TLS handshake complete for connection from ${remoteIP}`
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
@ -1061,45 +1200,72 @@ export class PortProxy {
|
||||
|
||||
// --- PORT RANGE-BASED HANDLING ---
|
||||
// Only apply port-based rules if the incoming port is within one of the global port ranges.
|
||||
if (this.settings.globalPortRanges && isPortInRanges(localPort, this.settings.globalPortRanges)) {
|
||||
if (
|
||||
this.settings.globalPortRanges &&
|
||||
isPortInRanges(localPort, this.settings.globalPortRanges)
|
||||
) {
|
||||
if (this.settings.forwardAllGlobalRanges) {
|
||||
if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0 && !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
||||
console.log(`[${connectionId}] Connection from ${remoteIP} rejected: IP ${remoteIP} not allowed in global default allowed list.`);
|
||||
if (
|
||||
this.settings.defaultAllowedIPs &&
|
||||
this.settings.defaultAllowedIPs.length > 0 &&
|
||||
!isAllowed(remoteIP, this.settings.defaultAllowedIPs)
|
||||
) {
|
||||
console.log(
|
||||
`[${connectionId}] Connection from ${remoteIP} rejected: IP ${remoteIP} not allowed in global default allowed list.`
|
||||
);
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
if (this.settings.enableDetailedLogging) {
|
||||
console.log(`[${connectionId}] Port-based connection from ${remoteIP} on port ${localPort} forwarded to global target IP ${this.settings.targetIP}.`);
|
||||
console.log(
|
||||
`[${connectionId}] Port-based connection from ${remoteIP} on port ${localPort} forwarded to global target IP ${this.settings.targetIP}.`
|
||||
);
|
||||
}
|
||||
setupConnection('', undefined, {
|
||||
setupConnection(
|
||||
'',
|
||||
undefined,
|
||||
{
|
||||
domains: ['global'],
|
||||
allowedIPs: this.settings.defaultAllowedIPs || [],
|
||||
blockedIPs: this.settings.defaultBlockedIPs || [],
|
||||
targetIPs: [this.settings.targetIP!],
|
||||
portRanges: []
|
||||
}, localPort);
|
||||
portRanges: [],
|
||||
},
|
||||
localPort
|
||||
);
|
||||
return;
|
||||
} else {
|
||||
// Attempt to find a matching forced domain config based on the local port.
|
||||
const forcedDomain = this.settings.domainConfigs.find(
|
||||
domain => domain.portRanges && domain.portRanges.length > 0 && isPortInRanges(localPort, domain.portRanges)
|
||||
(domain) =>
|
||||
domain.portRanges &&
|
||||
domain.portRanges.length > 0 &&
|
||||
isPortInRanges(localPort, domain.portRanges)
|
||||
);
|
||||
if (forcedDomain) {
|
||||
const effectiveAllowedIPs: string[] = [
|
||||
...forcedDomain.allowedIPs,
|
||||
...(this.settings.defaultAllowedIPs || [])
|
||||
...(this.settings.defaultAllowedIPs || []),
|
||||
];
|
||||
const effectiveBlockedIPs: string[] = [
|
||||
...(forcedDomain.blockedIPs || []),
|
||||
...(this.settings.defaultBlockedIPs || [])
|
||||
...(this.settings.defaultBlockedIPs || []),
|
||||
];
|
||||
if (!isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)) {
|
||||
console.log(`[${connectionId}] Connection from ${remoteIP} rejected: IP not allowed for domain ${forcedDomain.domains.join(', ')} on port ${localPort}.`);
|
||||
console.log(
|
||||
`[${connectionId}] Connection from ${remoteIP} rejected: IP not allowed for domain ${forcedDomain.domains.join(
|
||||
', '
|
||||
)} on port ${localPort}.`
|
||||
);
|
||||
socket.end();
|
||||
return;
|
||||
}
|
||||
if (this.settings.enableDetailedLogging) {
|
||||
console.log(`[${connectionId}] Port-based connection from ${remoteIP} on port ${localPort} matched domain ${forcedDomain.domains.join(', ')}.`);
|
||||
console.log(
|
||||
`[${connectionId}] Port-based connection from ${remoteIP} on port ${localPort} matched domain ${forcedDomain.domains.join(
|
||||
', '
|
||||
)}.`
|
||||
);
|
||||
}
|
||||
setupConnection('', undefined, forcedDomain, localPort);
|
||||
return;
|
||||
@ -1127,7 +1293,9 @@ export class PortProxy {
|
||||
connectionRecord.isTLS = true;
|
||||
|
||||
if (this.settings.enableTlsDebugLogging) {
|
||||
console.log(`[${connectionId}] Extracting SNI from TLS handshake, ${chunk.length} bytes`);
|
||||
console.log(
|
||||
`[${connectionId}] Extracting SNI from TLS handshake, ${chunk.length} bytes`
|
||||
);
|
||||
}
|
||||
|
||||
serverName = extractSNI(chunk, this.settings.enableTlsDebugLogging) || '';
|
||||
@ -1137,7 +1305,11 @@ export class PortProxy {
|
||||
connectionRecord.lockedDomain = serverName;
|
||||
|
||||
if (this.settings.enableDetailedLogging) {
|
||||
console.log(`[${connectionId}] Received connection from ${remoteIP} with SNI: ${serverName || '(empty)'}`);
|
||||
console.log(
|
||||
`[${connectionId}] Received connection from ${remoteIP} with SNI: ${
|
||||
serverName || '(empty)'
|
||||
}`
|
||||
);
|
||||
}
|
||||
|
||||
setupConnection(serverName, chunk);
|
||||
@ -1146,8 +1318,15 @@ export class PortProxy {
|
||||
initialDataReceived = true;
|
||||
connectionRecord.hasReceivedInitialData = true;
|
||||
|
||||
if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0 && !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
|
||||
if (
|
||||
this.settings.defaultAllowedIPs &&
|
||||
this.settings.defaultAllowedIPs.length > 0 &&
|
||||
!isAllowed(remoteIP, this.settings.defaultAllowedIPs)
|
||||
) {
|
||||
return rejectIncomingConnection(
|
||||
'rejected',
|
||||
`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`
|
||||
);
|
||||
}
|
||||
|
||||
setupConnection('');
|
||||
@ -1172,13 +1351,15 @@ export class PortProxy {
|
||||
|
||||
// Create a server for each port.
|
||||
for (const port of listeningPorts) {
|
||||
const server = plugins.net
|
||||
.createServer(connectionHandler)
|
||||
.on('error', (err: Error) => {
|
||||
const server = plugins.net.createServer(connectionHandler).on('error', (err: Error) => {
|
||||
console.log(`Server Error on port ${port}: ${err.message}`);
|
||||
});
|
||||
server.listen(port, () => {
|
||||
console.log(`PortProxy -> OK: Now listening on port ${port}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`);
|
||||
console.log(
|
||||
`PortProxy -> OK: Now listening on port ${port}${
|
||||
this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''
|
||||
}`
|
||||
);
|
||||
});
|
||||
this.netServers.push(server);
|
||||
}
|
||||
@ -1221,19 +1402,33 @@ export class PortProxy {
|
||||
}
|
||||
|
||||
// Parity check: if outgoing socket closed and incoming remains active
|
||||
if (record.outgoingClosedTime &&
|
||||
if (
|
||||
record.outgoingClosedTime &&
|
||||
!record.incoming.destroyed &&
|
||||
!record.connectionClosed &&
|
||||
(now - record.outgoingClosedTime > 120000)) {
|
||||
now - record.outgoingClosedTime > 120000
|
||||
) {
|
||||
const remoteIP = record.remoteIP;
|
||||
console.log(`[${id}] Parity check: Incoming socket for ${remoteIP} still active ${plugins.prettyMs(now - record.outgoingClosedTime)} after outgoing closed.`);
|
||||
console.log(
|
||||
`[${id}] Parity check: Incoming socket for ${remoteIP} still active ${plugins.prettyMs(
|
||||
now - record.outgoingClosedTime
|
||||
)} after outgoing closed.`
|
||||
);
|
||||
this.cleanupConnection(record, 'parity_check');
|
||||
}
|
||||
|
||||
// Check for stalled connections waiting for initial data
|
||||
if (!record.hasReceivedInitialData &&
|
||||
(now - record.incomingStartTime > this.settings.initialDataTimeout! / 2)) {
|
||||
console.log(`[${id}] Warning: Connection from ${record.remoteIP} has not received initial data after ${plugins.prettyMs(now - record.incomingStartTime)}`);
|
||||
if (
|
||||
!record.hasReceivedInitialData &&
|
||||
now - record.incomingStartTime > this.settings.initialDataTimeout! / 2
|
||||
) {
|
||||
console.log(
|
||||
`[${id}] Warning: Connection from ${
|
||||
record.remoteIP
|
||||
} has not received initial data after ${plugins.prettyMs(
|
||||
now - record.incomingStartTime
|
||||
)}`
|
||||
);
|
||||
}
|
||||
|
||||
// Skip inactivity check if disabled
|
||||
@ -1243,7 +1438,11 @@ export class PortProxy {
|
||||
|
||||
const inactivityTime = now - record.lastActivity;
|
||||
if (inactivityTime > inactivityThreshold && !record.connectionClosed) {
|
||||
console.log(`[${id}] Inactivity check: No activity on connection from ${record.remoteIP} for ${plugins.prettyMs(inactivityTime)}.`);
|
||||
console.log(
|
||||
`[${id}] Inactivity check: No activity on connection from ${
|
||||
record.remoteIP
|
||||
} for ${plugins.prettyMs(inactivityTime)}.`
|
||||
);
|
||||
this.cleanupConnection(record, 'inactivity');
|
||||
}
|
||||
}
|
||||
@ -1253,8 +1452,13 @@ export class PortProxy {
|
||||
console.log(
|
||||
`Active connections: ${this.connectionRecords.size}. ` +
|
||||
`Types: TLS=${tlsConnections} (Completed=${completedTlsHandshakes}, Pending=${pendingTlsHandshakes}), Non-TLS=${nonTlsConnections}. ` +
|
||||
`Longest running: IN=${plugins.prettyMs(maxIncoming)}, OUT=${plugins.prettyMs(maxOutgoing)}. ` +
|
||||
`Termination stats: ${JSON.stringify({IN: this.terminationStats.incoming, OUT: this.terminationStats.outgoing})}`
|
||||
`Longest running: IN=${plugins.prettyMs(maxIncoming)}, OUT=${plugins.prettyMs(
|
||||
maxOutgoing
|
||||
)}. ` +
|
||||
`Termination stats: ${JSON.stringify({
|
||||
IN: this.terminationStats.incoming,
|
||||
OUT: this.terminationStats.outgoing,
|
||||
})}`
|
||||
);
|
||||
}, this.settings.inactivityCheckInterval || 60000);
|
||||
|
||||
@ -1268,12 +1472,12 @@ export class PortProxy {
|
||||
* Gracefully shut down the proxy
|
||||
*/
|
||||
public async stop() {
|
||||
console.log("PortProxy shutting down...");
|
||||
console.log('PortProxy shutting down...');
|
||||
this.isShuttingDown = true;
|
||||
|
||||
// Stop accepting new connections
|
||||
const closeServerPromises: Promise<void>[] = this.netServers.map(
|
||||
server =>
|
||||
(server) =>
|
||||
new Promise<void>((resolve) => {
|
||||
if (!server.listening) {
|
||||
resolve();
|
||||
@ -1296,7 +1500,7 @@ export class PortProxy {
|
||||
|
||||
// Wait for servers to close
|
||||
await Promise.all(closeServerPromises);
|
||||
console.log("All servers closed. Cleaning up active connections...");
|
||||
console.log('All servers closed. Cleaning up active connections...');
|
||||
|
||||
// Force destroy all active connections immediately
|
||||
const connectionIds = [...this.connectionRecords.keys()];
|
||||
@ -1328,7 +1532,7 @@ export class PortProxy {
|
||||
}
|
||||
|
||||
// Short delay to allow graceful ends to process
|
||||
await new Promise(resolve => setTimeout(resolve, 100));
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
|
||||
// Second pass: Force destroy everything
|
||||
for (const id of connectionIds) {
|
||||
@ -1365,9 +1569,9 @@ export class PortProxy {
|
||||
// Reset termination stats
|
||||
this.terminationStats = {
|
||||
incoming: {},
|
||||
outgoing: {}
|
||||
outgoing: {},
|
||||
};
|
||||
|
||||
console.log("PortProxy shutdown complete.");
|
||||
console.log('PortProxy shutdown complete.');
|
||||
}
|
||||
}
|
@ -1,4 +1,6 @@
|
||||
import * as plugins from './plugins.js';
|
||||
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
|
||||
@ -11,31 +13,37 @@ export interface IPathPatternConfig {
|
||||
* Interface for router result with additional metadata
|
||||
*/
|
||||
export interface IRouterResult {
|
||||
config: plugins.tsclass.network.IReverseProxyConfig;
|
||||
config: tsclass.network.IReverseProxyConfig;
|
||||
pathMatch?: string;
|
||||
pathParams?: Record<string, string>;
|
||||
pathRemainder?: string;
|
||||
}
|
||||
|
||||
export class ProxyRouter {
|
||||
// Using a Map for O(1) hostname lookups instead of array search
|
||||
private hostMap: Map<string, plugins.tsclass.network.IReverseProxyConfig[]> = new Map();
|
||||
// Store original configs for reference
|
||||
private reverseProxyConfigs: plugins.tsclass.network.IReverseProxyConfig[] = [];
|
||||
private reverseProxyConfigs: tsclass.network.IReverseProxyConfig[] = [];
|
||||
// Default config to use when no match is found (optional)
|
||||
private defaultConfig?: plugins.tsclass.network.IReverseProxyConfig;
|
||||
private defaultConfig?: tsclass.network.IReverseProxyConfig;
|
||||
// Store path patterns separately since they're not in the original interface
|
||||
private pathPatterns: Map<plugins.tsclass.network.IReverseProxyConfig, string> = new Map();
|
||||
|
||||
constructor(
|
||||
configs?: plugins.tsclass.network.IReverseProxyConfig[],
|
||||
private readonly logger: {
|
||||
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;
|
||||
} = console
|
||||
};
|
||||
|
||||
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);
|
||||
}
|
||||
@ -45,61 +53,13 @@ export class ProxyRouter {
|
||||
* Sets a new set of reverse configs to be routed to
|
||||
* @param reverseCandidatesArg Array of reverse proxy configurations
|
||||
*/
|
||||
public setNewProxyConfigs(reverseCandidatesArg: plugins.tsclass.network.IReverseProxyConfig[]): void {
|
||||
public setNewProxyConfigs(reverseCandidatesArg: tsclass.network.IReverseProxyConfig[]): void {
|
||||
this.reverseProxyConfigs = [...reverseCandidatesArg];
|
||||
|
||||
// Reset the host map and path patterns
|
||||
this.hostMap.clear();
|
||||
this.pathPatterns.clear();
|
||||
|
||||
// Find default config if any (config with "*" as hostname)
|
||||
this.defaultConfig = this.reverseProxyConfigs.find(config => config.hostName === '*');
|
||||
|
||||
// Group configs by hostname for faster lookups
|
||||
for (const config of this.reverseProxyConfigs) {
|
||||
// Skip the default config as it's stored separately
|
||||
if (config.hostName === '*') continue;
|
||||
|
||||
const hostname = config.hostName.toLowerCase(); // Case-insensitive hostname lookup
|
||||
|
||||
if (!this.hostMap.has(hostname)) {
|
||||
this.hostMap.set(hostname, []);
|
||||
}
|
||||
|
||||
// Check for path pattern in extended properties
|
||||
// (using any to access custom properties not in the interface)
|
||||
const extendedConfig = config as any;
|
||||
if (extendedConfig.pathPattern) {
|
||||
this.pathPatterns.set(config, extendedConfig.pathPattern);
|
||||
}
|
||||
|
||||
// Add to the list of configs for this hostname
|
||||
this.hostMap.get(hostname).push(config);
|
||||
}
|
||||
|
||||
// Sort configs for each hostname by specificity
|
||||
// More specific path patterns should be checked first
|
||||
for (const [hostname, configs] of this.hostMap.entries()) {
|
||||
if (configs.length > 1) {
|
||||
// Sort by pathPattern - most specific first
|
||||
// (null comes last, exact paths before patterns with wildcards)
|
||||
configs.sort((a, b) => {
|
||||
const aPattern = this.pathPatterns.get(a);
|
||||
const bPattern = this.pathPatterns.get(b);
|
||||
|
||||
// If one has a path and the other doesn't, the one with a path comes first
|
||||
if (!aPattern && bPattern) return 1;
|
||||
if (aPattern && !bPattern) return -1;
|
||||
if (!aPattern && !bPattern) return 0;
|
||||
|
||||
// Both have path patterns - more specific (longer) first
|
||||
// This is a simple heuristic; we could use a more sophisticated approach
|
||||
return bPattern.length - aPattern.length;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
this.logger.info(`Router initialized with ${this.reverseProxyConfigs.length} configs (${this.hostMap.size} unique hosts)`);
|
||||
this.logger.info(`Router initialized with ${this.reverseProxyConfigs.length} configs (${this.getHostnames().length} unique hosts)`);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -107,7 +67,7 @@ export class ProxyRouter {
|
||||
* @param req The incoming HTTP request
|
||||
* @returns The matching proxy config or undefined if no match found
|
||||
*/
|
||||
public routeReq(req: plugins.http.IncomingMessage): plugins.tsclass.network.IReverseProxyConfig {
|
||||
public routeReq(req: http.IncomingMessage): tsclass.network.IReverseProxyConfig {
|
||||
const result = this.routeReqWithDetails(req);
|
||||
return result ? result.config : undefined;
|
||||
}
|
||||
@ -117,7 +77,7 @@ export class ProxyRouter {
|
||||
* @param req The incoming HTTP request
|
||||
* @returns Detailed routing result including matched config and path information
|
||||
*/
|
||||
public routeReqWithDetails(req: plugins.http.IncomingMessage): IRouterResult | undefined {
|
||||
public routeReqWithDetails(req: http.IncomingMessage): IRouterResult | undefined {
|
||||
// Extract and validate host header
|
||||
const originalHost = req.headers.host;
|
||||
if (!originalHost) {
|
||||
@ -126,52 +86,27 @@ export class ProxyRouter {
|
||||
}
|
||||
|
||||
// Parse URL for path matching
|
||||
const urlPath = new URL(
|
||||
req.url || '/',
|
||||
`http://${originalHost}`
|
||||
).pathname;
|
||||
const parsedUrl = url.parse(req.url || '/');
|
||||
const urlPath = parsedUrl.pathname || '/';
|
||||
|
||||
// Extract hostname without port
|
||||
const hostWithoutPort = originalHost.split(':')[0].toLowerCase();
|
||||
|
||||
// Find configs for this hostname
|
||||
const configs = this.hostMap.get(hostWithoutPort);
|
||||
|
||||
if (configs && configs.length > 0) {
|
||||
// Check each config for path matching
|
||||
for (const config of configs) {
|
||||
// Get the path pattern if any
|
||||
const pathPattern = this.pathPatterns.get(config);
|
||||
|
||||
// If no path pattern specified, this config matches all paths
|
||||
if (!pathPattern) {
|
||||
return { config };
|
||||
// First try exact hostname match
|
||||
const exactConfig = this.findConfigForHost(hostWithoutPort, urlPath);
|
||||
if (exactConfig) {
|
||||
return exactConfig;
|
||||
}
|
||||
|
||||
// Check if path matches the pattern
|
||||
const pathMatch = this.matchPath(urlPath, pathPattern);
|
||||
if (pathMatch) {
|
||||
return {
|
||||
config,
|
||||
pathMatch: pathMatch.matched,
|
||||
pathParams: pathMatch.params,
|
||||
pathRemainder: pathMatch.remainder
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Try wildcard subdomains if no direct match found
|
||||
// For example, if request is for sub.example.com, try *.example.com
|
||||
// Try wildcard subdomain
|
||||
if (hostWithoutPort.includes('.')) {
|
||||
const domainParts = hostWithoutPort.split('.');
|
||||
if (domainParts.length > 2) {
|
||||
const wildcardDomain = `*.${domainParts.slice(1).join('.')}`;
|
||||
const wildcardConfigs = this.hostMap.get(wildcardDomain);
|
||||
|
||||
if (wildcardConfigs && wildcardConfigs.length > 0) {
|
||||
// Use the first matching wildcard config
|
||||
// Could add path matching logic here as well
|
||||
return { config: wildcardConfigs[0] };
|
||||
const wildcardConfig = this.findConfigForHost(wildcardDomain, urlPath);
|
||||
if (wildcardConfig) {
|
||||
return wildcardConfig;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@ -186,21 +121,60 @@ export class ProxyRouter {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
* Find a config for a specific host and path
|
||||
*/
|
||||
public setPathPattern(
|
||||
config: plugins.tsclass.network.IReverseProxyConfig,
|
||||
pathPattern: string
|
||||
): boolean {
|
||||
const exists = this.reverseProxyConfigs.includes(config);
|
||||
if (exists) {
|
||||
this.pathPatterns.set(config, pathPattern);
|
||||
return true;
|
||||
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;
|
||||
}
|
||||
return false;
|
||||
|
||||
// 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -242,62 +216,51 @@ export class ProxyRouter {
|
||||
}
|
||||
|
||||
// Handle path parameters
|
||||
const patternParts = pattern.split('/');
|
||||
const pathParts = path.split('/');
|
||||
const patternParts = pattern.split('/').filter(p => p);
|
||||
const pathParts = path.split('/').filter(p => p);
|
||||
|
||||
// Check if paths are compatible length
|
||||
if (
|
||||
// If pattern doesn't end with wildcard, paths must have the same number of parts
|
||||
(!pattern.endsWith('/*') && patternParts.length !== pathParts.length) ||
|
||||
// If pattern ends with wildcard, path must have at least as many parts as the pattern
|
||||
(pattern.endsWith('/*') && pathParts.length < patternParts.length - 1)
|
||||
) {
|
||||
// Too few path parts to match
|
||||
if (pathParts.length < patternParts.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const params: Record<string, string> = {};
|
||||
const matchedParts: string[] = [];
|
||||
|
||||
// Compare path parts
|
||||
// Compare each part
|
||||
for (let i = 0; i < patternParts.length; i++) {
|
||||
const patternPart = patternParts[i];
|
||||
|
||||
// Handle wildcard at the end
|
||||
if (patternPart === '*' && i === patternParts.length - 1) {
|
||||
break;
|
||||
}
|
||||
|
||||
// If pathParts[i] doesn't exist, we've reached the end of the path
|
||||
if (i >= pathParts.length) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const pathPart = pathParts[i];
|
||||
|
||||
// Handle parameter
|
||||
if (patternPart.startsWith(':')) {
|
||||
const paramName = patternPart.slice(1);
|
||||
params[paramName] = pathPart;
|
||||
matchedParts.push(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;
|
||||
}
|
||||
|
||||
matchedParts.push(pathPart);
|
||||
}
|
||||
|
||||
// Calculate the remainder
|
||||
let remainder = '';
|
||||
if (pattern.endsWith('/*')) {
|
||||
remainder = '/' + pathParts.slice(patternParts.length - 1).join('/');
|
||||
}
|
||||
// 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: matchedParts.join('/'),
|
||||
matched,
|
||||
params,
|
||||
remainder
|
||||
};
|
||||
@ -307,7 +270,7 @@ export class ProxyRouter {
|
||||
* Gets all currently active proxy configurations
|
||||
* @returns Array of all active configurations
|
||||
*/
|
||||
public getProxyConfigs(): plugins.tsclass.network.IReverseProxyConfig[] {
|
||||
public getProxyConfigs(): tsclass.network.IReverseProxyConfig[] {
|
||||
return [...this.reverseProxyConfigs];
|
||||
}
|
||||
|
||||
@ -316,7 +279,13 @@ export class ProxyRouter {
|
||||
* @returns Array of hostnames
|
||||
*/
|
||||
public getHostnames(): string[] {
|
||||
return Array.from(this.hostMap.keys());
|
||||
const hostnames = new Set<string>();
|
||||
for (const config of this.reverseProxyConfigs) {
|
||||
if (config.hostName !== '*') {
|
||||
hostnames.add(config.hostName.toLowerCase());
|
||||
}
|
||||
}
|
||||
return Array.from(hostnames);
|
||||
}
|
||||
|
||||
/**
|
||||
@ -325,7 +294,7 @@ export class ProxyRouter {
|
||||
* @param pathPattern Optional path pattern for route matching
|
||||
*/
|
||||
public addProxyConfig(
|
||||
config: plugins.tsclass.network.IReverseProxyConfig,
|
||||
config: tsclass.network.IReverseProxyConfig,
|
||||
pathPattern?: string
|
||||
): void {
|
||||
this.reverseProxyConfigs.push(config);
|
||||
@ -334,8 +303,24 @@ export class ProxyRouter {
|
||||
if (pathPattern) {
|
||||
this.pathPatterns.set(config, pathPattern);
|
||||
}
|
||||
}
|
||||
|
||||
this.setNewProxyConfigs(this.reverseProxyConfigs);
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
/**
|
||||
@ -345,15 +330,22 @@ export class ProxyRouter {
|
||||
*/
|
||||
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
|
||||
);
|
||||
|
||||
if (initialCount !== this.reverseProxyConfigs.length) {
|
||||
this.setNewProxyConfigs(this.reverseProxyConfigs);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
return this.reverseProxyConfigs.length !== initialCount;
|
||||
}
|
||||
}
|
Reference in New Issue
Block a user