fix(PortProxy): Improved code formatting and readability in PortProxy class by adjusting spacing and comments.
This commit is contained in:
parent
1718a3b2f2
commit
0e605d9a9d
@ -1,5 +1,11 @@
|
|||||||
# Changelog
|
# 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)
|
## 2025-03-06 - 3.28.0 - feat(router)
|
||||||
Add detailed routing tests and refactor ProxyRouter for improved path matching
|
Add detailed routing tests and refactor ProxyRouter for improved path matching
|
||||||
|
|
||||||
|
@ -3,6 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
export const commitinfo = {
|
export const commitinfo = {
|
||||||
name: '@push.rocks/smartproxy',
|
name: '@push.rocks/smartproxy',
|
||||||
version: '3.28.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.'
|
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.'
|
||||||
}
|
}
|
||||||
|
@ -2,10 +2,10 @@ import * as plugins from './plugins.js';
|
|||||||
|
|
||||||
/** Domain configuration with per-domain allowed port ranges */
|
/** Domain configuration with per-domain allowed port ranges */
|
||||||
export interface IDomainConfig {
|
export interface IDomainConfig {
|
||||||
domains: string[]; // Glob patterns for domain(s)
|
domains: string[]; // Glob patterns for domain(s)
|
||||||
allowedIPs: string[]; // Glob patterns for allowed IPs
|
allowedIPs: string[]; // Glob patterns for allowed IPs
|
||||||
blockedIPs?: string[]; // Glob patterns for blocked IPs
|
blockedIPs?: string[]; // Glob patterns for blocked IPs
|
||||||
targetIPs?: string[]; // If multiple targetIPs are given, use round robin.
|
targetIPs?: string[]; // If multiple targetIPs are given, use round robin.
|
||||||
portRanges?: Array<{ from: number; to: number }>; // Optional port ranges
|
portRanges?: Array<{ from: number; to: number }>; // Optional port ranges
|
||||||
// Allow domain-specific timeout override
|
// Allow domain-specific timeout override
|
||||||
connectionTimeout?: number; // Connection timeout override (ms)
|
connectionTimeout?: number; // Connection timeout override (ms)
|
||||||
@ -23,31 +23,31 @@ export interface IPortProxySettings extends plugins.tls.TlsOptions {
|
|||||||
preserveSourceIP?: boolean;
|
preserveSourceIP?: boolean;
|
||||||
|
|
||||||
// Timeout settings
|
// Timeout settings
|
||||||
initialDataTimeout?: number; // Timeout for initial data/SNI (ms), default: 60000 (60s)
|
initialDataTimeout?: number; // Timeout for initial data/SNI (ms), default: 60000 (60s)
|
||||||
socketTimeout?: number; // Socket inactivity timeout (ms), default: 3600000 (1h)
|
socketTimeout?: number; // Socket inactivity timeout (ms), default: 3600000 (1h)
|
||||||
inactivityCheckInterval?: number; // How often to check for inactive connections (ms), default: 60000 (60s)
|
inactivityCheckInterval?: number; // How often to check for inactive connections (ms), default: 60000 (60s)
|
||||||
maxConnectionLifetime?: number; // Default max connection lifetime (ms), default: 3600000 (1h)
|
maxConnectionLifetime?: number; // Default max connection lifetime (ms), default: 3600000 (1h)
|
||||||
inactivityTimeout?: number; // Inactivity timeout (ms), default: 3600000 (1h)
|
inactivityTimeout?: number; // Inactivity timeout (ms), default: 3600000 (1h)
|
||||||
|
|
||||||
gracefulShutdownTimeout?: number; // (ms) maximum time to wait for connections to close during shutdown
|
gracefulShutdownTimeout?: number; // (ms) maximum time to wait for connections to close during shutdown
|
||||||
globalPortRanges: Array<{ from: number; to: number }>; // Global allowed port ranges
|
globalPortRanges: Array<{ from: number; to: number }>; // Global allowed port ranges
|
||||||
forwardAllGlobalRanges?: boolean; // When true, forwards all connections on global port ranges to the global targetIP
|
forwardAllGlobalRanges?: boolean; // When true, forwards all connections on global port ranges to the global targetIP
|
||||||
|
|
||||||
// Socket optimization settings
|
// Socket optimization settings
|
||||||
noDelay?: boolean; // Disable Nagle's algorithm (default: true)
|
noDelay?: boolean; // Disable Nagle's algorithm (default: true)
|
||||||
keepAlive?: boolean; // Enable TCP keepalive (default: true)
|
keepAlive?: boolean; // Enable TCP keepalive (default: true)
|
||||||
keepAliveInitialDelay?: number; // Initial delay before sending keepalive probes (ms)
|
keepAliveInitialDelay?: number; // Initial delay before sending keepalive probes (ms)
|
||||||
maxPendingDataSize?: number; // Maximum bytes to buffer during connection setup
|
maxPendingDataSize?: number; // Maximum bytes to buffer during connection setup
|
||||||
|
|
||||||
// Enhanced features
|
// Enhanced features
|
||||||
disableInactivityCheck?: boolean; // Disable inactivity checking entirely
|
disableInactivityCheck?: boolean; // Disable inactivity checking entirely
|
||||||
enableKeepAliveProbes?: boolean; // Enable TCP keep-alive probes
|
enableKeepAliveProbes?: boolean; // Enable TCP keep-alive probes
|
||||||
enableDetailedLogging?: boolean; // Enable detailed connection logging
|
enableDetailedLogging?: boolean; // Enable detailed connection logging
|
||||||
enableTlsDebugLogging?: boolean; // Enable TLS handshake debug logging
|
enableTlsDebugLogging?: boolean; // Enable TLS handshake debug logging
|
||||||
enableRandomizedTimeouts?: boolean; // Randomize timeouts slightly to prevent thundering herd
|
enableRandomizedTimeouts?: boolean; // Randomize timeouts slightly to prevent thundering herd
|
||||||
|
|
||||||
// Rate limiting and security
|
// Rate limiting and security
|
||||||
maxConnectionsPerIP?: number; // Maximum simultaneous connections from a single IP
|
maxConnectionsPerIP?: number; // Maximum simultaneous connections from a single IP
|
||||||
connectionRateLimitPerMinute?: number; // Max new connections per minute from a single IP
|
connectionRateLimitPerMinute?: number; // Max new connections per minute from a single IP
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -55,28 +55,28 @@ export interface IPortProxySettings extends plugins.tls.TlsOptions {
|
|||||||
* Enhanced connection record
|
* Enhanced connection record
|
||||||
*/
|
*/
|
||||||
interface IConnectionRecord {
|
interface IConnectionRecord {
|
||||||
id: string; // Unique connection identifier
|
id: string; // Unique connection identifier
|
||||||
incoming: plugins.net.Socket;
|
incoming: plugins.net.Socket;
|
||||||
outgoing: plugins.net.Socket | null;
|
outgoing: plugins.net.Socket | null;
|
||||||
incomingStartTime: number;
|
incomingStartTime: number;
|
||||||
outgoingStartTime?: number;
|
outgoingStartTime?: number;
|
||||||
outgoingClosedTime?: number;
|
outgoingClosedTime?: number;
|
||||||
lockedDomain?: string; // Used to lock this connection to the initial SNI
|
lockedDomain?: string; // Used to lock this connection to the initial SNI
|
||||||
connectionClosed: boolean; // Flag to prevent multiple cleanup attempts
|
connectionClosed: boolean; // Flag to prevent multiple cleanup attempts
|
||||||
cleanupTimer?: NodeJS.Timeout; // Timer for max lifetime/inactivity
|
cleanupTimer?: NodeJS.Timeout; // Timer for max lifetime/inactivity
|
||||||
lastActivity: number; // Last activity timestamp for inactivity detection
|
lastActivity: number; // Last activity timestamp for inactivity detection
|
||||||
pendingData: Buffer[]; // Buffer to hold data during connection setup
|
pendingData: Buffer[]; // Buffer to hold data during connection setup
|
||||||
pendingDataSize: number; // Track total size of pending data
|
pendingDataSize: number; // Track total size of pending data
|
||||||
|
|
||||||
// Enhanced tracking fields
|
// Enhanced tracking fields
|
||||||
bytesReceived: number; // Total bytes received
|
bytesReceived: number; // Total bytes received
|
||||||
bytesSent: number; // Total bytes sent
|
bytesSent: number; // Total bytes sent
|
||||||
remoteIP: string; // Remote IP (cached for logging after socket close)
|
remoteIP: string; // Remote IP (cached for logging after socket close)
|
||||||
localPort: number; // Local port (cached for logging)
|
localPort: number; // Local port (cached for logging)
|
||||||
isTLS: boolean; // Whether this connection is a TLS connection
|
isTLS: boolean; // Whether this connection is a TLS connection
|
||||||
tlsHandshakeComplete: boolean; // Whether the TLS handshake is complete
|
tlsHandshakeComplete: boolean; // Whether the TLS handshake is complete
|
||||||
hasReceivedInitialData: boolean; // Whether initial data has been received
|
hasReceivedInitialData: boolean; // Whether initial data has been received
|
||||||
domainConfig?: IDomainConfig; // Associated domain config for this connection
|
domainConfig?: IDomainConfig; // Associated domain config for this connection
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -90,7 +90,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
try {
|
try {
|
||||||
// Check if buffer is too small for TLS
|
// Check if buffer is too small for TLS
|
||||||
if (buffer.length < 5) {
|
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;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -109,7 +109,10 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
// Check record length
|
// Check record length
|
||||||
const recordLength = buffer.readUInt16BE(3);
|
const recordLength = buffer.readUInt16BE(3);
|
||||||
if (buffer.length < 5 + recordLength) {
|
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;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -136,7 +139,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
|
|
||||||
// Cipher suites
|
// Cipher suites
|
||||||
if (offset + 2 > buffer.length) {
|
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;
|
return undefined;
|
||||||
}
|
}
|
||||||
const cipherSuitesLength = buffer.readUInt16BE(offset);
|
const cipherSuitesLength = buffer.readUInt16BE(offset);
|
||||||
@ -145,7 +148,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
|
|
||||||
// Compression methods
|
// Compression methods
|
||||||
if (offset + 1 > buffer.length) {
|
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;
|
return undefined;
|
||||||
}
|
}
|
||||||
const compressionMethodsLength = buffer.readUInt8(offset);
|
const compressionMethodsLength = buffer.readUInt8(offset);
|
||||||
@ -154,7 +157,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
|
|
||||||
// Extensions
|
// Extensions
|
||||||
if (offset + 2 > buffer.length) {
|
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;
|
return undefined;
|
||||||
}
|
}
|
||||||
const extensionsLength = buffer.readUInt16BE(offset);
|
const extensionsLength = buffer.readUInt16BE(offset);
|
||||||
@ -163,7 +166,10 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
const extensionsEnd = offset + extensionsLength;
|
const extensionsEnd = offset + extensionsLength;
|
||||||
|
|
||||||
if (extensionsEnd > buffer.length) {
|
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;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -172,13 +178,15 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
const extensionType = buffer.readUInt16BE(offset);
|
const extensionType = buffer.readUInt16BE(offset);
|
||||||
const extensionLength = buffer.readUInt16BE(offset + 2);
|
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;
|
offset += 4;
|
||||||
|
|
||||||
if (extensionType === 0x0000) { // SNI extension
|
if (extensionType === 0x0000) {
|
||||||
|
// SNI extension
|
||||||
if (offset + 2 > buffer.length) {
|
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;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -188,7 +196,10 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
const sniListEnd = offset + sniListLength;
|
const sniListEnd = offset + sniListLength;
|
||||||
|
|
||||||
if (sniListEnd > buffer.length) {
|
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;
|
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 (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 (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;
|
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;
|
return undefined;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(`Error extracting SNI: ${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
|
// Helper: Check if a port falls within any of the given port ranges
|
||||||
const isPortInRanges = (port: number, ranges: Array<{ from: number; to: number }>): boolean => {
|
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
|
// 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;
|
if (normalizedIPVariants.length === 0) return false;
|
||||||
|
|
||||||
const expandedPatterns = patterns.flatMap(normalizeIP);
|
const expandedPatterns = patterns.flatMap(normalizeIP);
|
||||||
return normalizedIPVariants.some(ipVariant =>
|
return normalizedIPVariants.some((ipVariant) =>
|
||||||
expandedPatterns.some(pattern => plugins.minimatch(ipVariant, pattern))
|
expandedPatterns.some((pattern) => plugins.minimatch(ipVariant, pattern))
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -309,11 +326,11 @@ export class PortProxy {
|
|||||||
targetIP: settingsArg.targetIP || 'localhost',
|
targetIP: settingsArg.targetIP || 'localhost',
|
||||||
|
|
||||||
// Timeout settings with our enhanced defaults
|
// Timeout settings with our enhanced defaults
|
||||||
initialDataTimeout: settingsArg.initialDataTimeout || 60000, // 60 seconds for initial data
|
initialDataTimeout: settingsArg.initialDataTimeout || 60000, // 60 seconds for initial handshake
|
||||||
socketTimeout: settingsArg.socketTimeout || 3600000, // 1 hour socket timeout
|
socketTimeout: settingsArg.socketTimeout || 2592000000, // 30 days socket timeout
|
||||||
inactivityCheckInterval: settingsArg.inactivityCheckInterval || 60000, // 60 seconds interval
|
inactivityCheckInterval: settingsArg.inactivityCheckInterval || 60000, // 60 seconds interval
|
||||||
maxConnectionLifetime: settingsArg.maxConnectionLifetime || 3600000, // 1 hour default lifetime
|
maxConnectionLifetime: settingsArg.maxConnectionLifetime || 2592000000, // 30 days max lifetime
|
||||||
inactivityTimeout: settingsArg.inactivityTimeout || 3600000, // 1 hour inactivity timeout
|
inactivityTimeout: settingsArg.inactivityTimeout || 14400000, // 4 hours inactivity timeout
|
||||||
|
|
||||||
gracefulShutdownTimeout: settingsArg.gracefulShutdownTimeout || 30000, // 30 seconds
|
gracefulShutdownTimeout: settingsArg.gracefulShutdownTimeout || 30000, // 30 seconds
|
||||||
|
|
||||||
@ -356,7 +373,7 @@ export class PortProxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get timestamps and filter out entries older than 1 minute
|
// 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);
|
timestamps.push(now);
|
||||||
this.connectionRateByIP.set(ip, timestamps);
|
this.connectionRateByIP.set(ip, timestamps);
|
||||||
|
|
||||||
@ -505,11 +522,17 @@ export class PortProxy {
|
|||||||
|
|
||||||
// Log connection details
|
// Log connection details
|
||||||
if (this.settings.enableDetailedLogging) {
|
if (this.settings.enableDetailedLogging) {
|
||||||
console.log(`[${record.id}] Connection from ${record.remoteIP} on port ${record.localPort} terminated (${reason}).` +
|
console.log(
|
||||||
` Duration: ${plugins.prettyMs(duration)}, Bytes IN: ${bytesReceived}, OUT: ${bytesSent}, ` +
|
`[${record.id}] Connection from ${record.remoteIP} on port ${record.localPort} terminated (${reason}).` +
|
||||||
`TLS: ${record.isTLS ? 'Yes' : 'No'}`);
|
` Duration: ${plugins.prettyMs(
|
||||||
|
duration
|
||||||
|
)}, Bytes IN: ${bytesReceived}, OUT: ${bytesSent}, ` +
|
||||||
|
`TLS: ${record.isTLS ? 'Yes' : 'No'}`
|
||||||
|
);
|
||||||
} else {
|
} 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.
|
const localPort = socket.localPort || 0; // The port on which this connection was accepted.
|
||||||
|
|
||||||
// Check rate limits
|
// Check rate limits
|
||||||
if (this.settings.maxConnectionsPerIP &&
|
if (
|
||||||
this.getConnectionCountByIP(remoteIP) >= this.settings.maxConnectionsPerIP) {
|
this.settings.maxConnectionsPerIP &&
|
||||||
console.log(`Connection rejected from ${remoteIP}: Maximum connections per IP (${this.settings.maxConnectionsPerIP}) exceeded`);
|
this.getConnectionCountByIP(remoteIP) >= this.settings.maxConnectionsPerIP
|
||||||
|
) {
|
||||||
|
console.log(
|
||||||
|
`Connection rejected from ${remoteIP}: Maximum connections per IP (${this.settings.maxConnectionsPerIP}) exceeded`
|
||||||
|
);
|
||||||
socket.end();
|
socket.end();
|
||||||
socket.destroy();
|
socket.destroy();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.settings.connectionRateLimitPerMinute && !this.checkConnectionRate(remoteIP)) {
|
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.end();
|
||||||
socket.destroy();
|
socket.destroy();
|
||||||
return;
|
return;
|
||||||
@ -611,7 +640,7 @@ export class PortProxy {
|
|||||||
localPort: localPort,
|
localPort: localPort,
|
||||||
isTLS: false,
|
isTLS: false,
|
||||||
tlsHandshakeComplete: false,
|
tlsHandshakeComplete: false,
|
||||||
hasReceivedInitialData: false
|
hasReceivedInitialData: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Track connection by IP
|
// Track connection by IP
|
||||||
@ -619,9 +648,13 @@ export class PortProxy {
|
|||||||
this.connectionRecords.set(connectionId, connectionRecord);
|
this.connectionRecords.set(connectionId, connectionRecord);
|
||||||
|
|
||||||
if (this.settings.enableDetailedLogging) {
|
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 {
|
} 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;
|
let initialDataReceived = false;
|
||||||
@ -661,7 +694,9 @@ export class PortProxy {
|
|||||||
if (this.settings.sniEnabled) {
|
if (this.settings.sniEnabled) {
|
||||||
initialTimeout = setTimeout(() => {
|
initialTimeout = setTimeout(() => {
|
||||||
if (!initialDataReceived) {
|
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) {
|
if (incomingTerminationReason === null) {
|
||||||
incomingTerminationReason = 'initial_timeout';
|
incomingTerminationReason = 'initial_timeout';
|
||||||
this.incrementTerminationStat('incoming', 'initial_timeout');
|
this.incrementTerminationStat('incoming', 'initial_timeout');
|
||||||
@ -694,7 +729,9 @@ export class PortProxy {
|
|||||||
connectionRecord.isTLS = true;
|
connectionRecord.isTLS = true;
|
||||||
|
|
||||||
if (this.settings.enableTlsDebugLogging) {
|
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
|
// Try to extract SNI and log detailed debug info
|
||||||
extractSNI(chunk, true);
|
extractSNI(chunk, true);
|
||||||
}
|
}
|
||||||
@ -711,12 +748,30 @@ export class PortProxy {
|
|||||||
|
|
||||||
if (code === 'ECONNRESET') {
|
if (code === 'ECONNRESET') {
|
||||||
reason = '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') {
|
} else if (code === 'ETIMEDOUT') {
|
||||||
reason = '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 {
|
} 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) {
|
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 forcedDomain - If provided, overrides SNI/domain lookup (used for port-based routing).
|
||||||
* @param overridePort - If provided, use this port for the outgoing connection.
|
* @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
|
// Clear the initial timeout since we've received data
|
||||||
if (initialTimeout) {
|
if (initialTimeout) {
|
||||||
clearTimeout(initialTimeout);
|
clearTimeout(initialTimeout);
|
||||||
@ -771,16 +831,20 @@ export class PortProxy {
|
|||||||
connectionRecord.isTLS = true;
|
connectionRecord.isTLS = true;
|
||||||
|
|
||||||
if (this.settings.enableTlsDebugLogging) {
|
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.
|
// If a forcedDomain is provided (port-based routing), use it; otherwise, use SNI-based lookup.
|
||||||
const domainConfig = forcedDomain
|
const domainConfig = forcedDomain
|
||||||
? forcedDomain
|
? forcedDomain
|
||||||
: (serverName ? this.settings.domainConfigs.find(config =>
|
: serverName
|
||||||
config.domains.some(d => plugins.minimatch(serverName, d))
|
? this.settings.domainConfigs.find((config) =>
|
||||||
) : undefined);
|
config.domains.some((d) => plugins.minimatch(serverName, d))
|
||||||
|
)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
// Save domain config in connection record
|
// Save domain config in connection record
|
||||||
connectionRecord.domainConfig = domainConfig;
|
connectionRecord.domainConfig = domainConfig;
|
||||||
@ -789,20 +853,37 @@ export class PortProxy {
|
|||||||
if (domainConfig) {
|
if (domainConfig) {
|
||||||
const effectiveAllowedIPs: string[] = [
|
const effectiveAllowedIPs: string[] = [
|
||||||
...domainConfig.allowedIPs,
|
...domainConfig.allowedIPs,
|
||||||
...(this.settings.defaultAllowedIPs || [])
|
...(this.settings.defaultAllowedIPs || []),
|
||||||
];
|
];
|
||||||
const effectiveBlockedIPs: string[] = [
|
const effectiveBlockedIPs: string[] = [
|
||||||
...(domainConfig.blockedIPs || []),
|
...(domainConfig.blockedIPs || []),
|
||||||
...(this.settings.defaultBlockedIPs || [])
|
...(this.settings.defaultBlockedIPs || []),
|
||||||
];
|
];
|
||||||
|
|
||||||
// Skip IP validation if allowedIPs is empty
|
// Skip IP validation if allowedIPs is empty
|
||||||
if (domainConfig.allowedIPs.length > 0 && !isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)) {
|
if (
|
||||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed for domain ${domainConfig.domains.join(', ')}`);
|
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) {
|
} else if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0) {
|
||||||
if (!isGlobIPAllowed(remoteIP, this.settings.defaultAllowedIPs, this.settings.defaultBlockedIPs || [])) {
|
if (
|
||||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed by default allowed list`);
|
!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;
|
connectionRecord.isTLS = true;
|
||||||
|
|
||||||
if (this.settings.enableTlsDebugLogging) {
|
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;
|
const newSize = connectionRecord.pendingDataSize + chunk.length;
|
||||||
|
|
||||||
if (this.settings.maxPendingDataSize && newSize > this.settings.maxPendingDataSize) {
|
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
|
socket.end(); // Gracefully close the socket
|
||||||
return initiateCleanupOnce('buffer_limit_exceeded');
|
return initiateCleanupOnce('buffer_limit_exceeded');
|
||||||
}
|
}
|
||||||
@ -886,17 +971,25 @@ export class PortProxy {
|
|||||||
targetSocket.once('error', (err) => {
|
targetSocket.once('error', (err) => {
|
||||||
// This handler runs only once during the initial connection phase
|
// This handler runs only once during the initial connection phase
|
||||||
const code = (err as any).code;
|
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
|
// Resume the incoming socket to prevent it from hanging
|
||||||
socket.resume();
|
socket.resume();
|
||||||
|
|
||||||
if (code === 'ECONNREFUSED') {
|
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') {
|
} 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') {
|
} 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') {
|
} else if (code === 'EHOSTUNREACH') {
|
||||||
console.log(`[${connectionId}] Host ${targetHost} is unreachable`);
|
console.log(`[${connectionId}] Host ${targetHost} is unreachable`);
|
||||||
}
|
}
|
||||||
@ -922,7 +1015,11 @@ export class PortProxy {
|
|||||||
|
|
||||||
// Handle timeouts
|
// Handle timeouts
|
||||||
socket.on('timeout', () => {
|
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) {
|
if (incomingTerminationReason === null) {
|
||||||
incomingTerminationReason = 'timeout';
|
incomingTerminationReason = 'timeout';
|
||||||
this.incrementTerminationStat('incoming', 'timeout');
|
this.incrementTerminationStat('incoming', 'timeout');
|
||||||
@ -931,7 +1028,11 @@ export class PortProxy {
|
|||||||
});
|
});
|
||||||
|
|
||||||
targetSocket.on('timeout', () => {
|
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) {
|
if (outgoingTerminationReason === null) {
|
||||||
outgoingTerminationReason = 'timeout';
|
outgoingTerminationReason = 'timeout';
|
||||||
this.incrementTerminationStat('outgoing', 'timeout');
|
this.incrementTerminationStat('outgoing', 'timeout');
|
||||||
@ -965,7 +1066,9 @@ export class PortProxy {
|
|||||||
const combinedData = Buffer.concat(connectionRecord.pendingData);
|
const combinedData = Buffer.concat(connectionRecord.pendingData);
|
||||||
targetSocket.write(combinedData, (err) => {
|
targetSocket.write(combinedData, (err) => {
|
||||||
if (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');
|
return initiateCleanupOnce('write_error');
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -977,13 +1080,25 @@ export class PortProxy {
|
|||||||
if (this.settings.enableDetailedLogging) {
|
if (this.settings.enableDetailedLogging) {
|
||||||
console.log(
|
console.log(
|
||||||
`[${connectionId}] Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
`[${connectionId}] Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
||||||
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})` : ''}` +
|
`${
|
||||||
` TLS: ${connectionRecord.isTLS ? 'Yes' : 'No'}`
|
serverName
|
||||||
|
? ` (SNI: ${serverName})`
|
||||||
|
: forcedDomain
|
||||||
|
? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})`
|
||||||
|
: ''
|
||||||
|
}` +
|
||||||
|
` TLS: ${connectionRecord.isTLS ? 'Yes' : 'No'}`
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
console.log(
|
console.log(
|
||||||
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
`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) {
|
if (this.settings.enableDetailedLogging) {
|
||||||
console.log(
|
console.log(
|
||||||
`[${connectionId}] Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
`[${connectionId}] Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
||||||
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})` : ''}` +
|
`${
|
||||||
` TLS: ${connectionRecord.isTLS ? 'Yes' : 'No'}`
|
serverName
|
||||||
|
? ` (SNI: ${serverName})`
|
||||||
|
: forcedDomain
|
||||||
|
? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})`
|
||||||
|
: ''
|
||||||
|
}` +
|
||||||
|
` TLS: ${connectionRecord.isTLS ? 'Yes' : 'No'}`
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
console.log(
|
console.log(
|
||||||
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
`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
|
// Try to extract SNI from potential renegotiation
|
||||||
const newSNI = extractSNI(renegChunk, this.settings.enableTlsDebugLogging);
|
const newSNI = extractSNI(renegChunk, this.settings.enableTlsDebugLogging);
|
||||||
if (newSNI && newSNI !== connectionRecord.lockedDomain) {
|
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');
|
initiateCleanupOnce('sni_mismatch');
|
||||||
} else if (newSNI && this.settings.enableDetailedLogging) {
|
} 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) {
|
} 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
|
// Set timeout based on domain config or default
|
||||||
const connectionTimeout = this.getConnectionTimeout(connectionRecord);
|
const connectionTimeout = this.getConnectionTimeout(connectionRecord);
|
||||||
connectionRecord.cleanupTimer = setTimeout(() => {
|
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');
|
initiateCleanupOnce('connection_timeout');
|
||||||
}, connectionTimeout);
|
}, connectionTimeout);
|
||||||
|
|
||||||
@ -1053,7 +1190,9 @@ export class PortProxy {
|
|||||||
connectionRecord.tlsHandshakeComplete = true;
|
connectionRecord.tlsHandshakeComplete = true;
|
||||||
|
|
||||||
if (this.settings.enableTlsDebugLogging) {
|
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 ---
|
// --- PORT RANGE-BASED HANDLING ---
|
||||||
// Only apply port-based rules if the incoming port is within one of the global port ranges.
|
// 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.forwardAllGlobalRanges) {
|
||||||
if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0 && !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
if (
|
||||||
console.log(`[${connectionId}] Connection from ${remoteIP} rejected: IP ${remoteIP} not allowed in global default allowed list.`);
|
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();
|
socket.end();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (this.settings.enableDetailedLogging) {
|
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(
|
||||||
domains: ['global'],
|
'',
|
||||||
allowedIPs: this.settings.defaultAllowedIPs || [],
|
undefined,
|
||||||
blockedIPs: this.settings.defaultBlockedIPs || [],
|
{
|
||||||
targetIPs: [this.settings.targetIP!],
|
domains: ['global'],
|
||||||
portRanges: []
|
allowedIPs: this.settings.defaultAllowedIPs || [],
|
||||||
}, localPort);
|
blockedIPs: this.settings.defaultBlockedIPs || [],
|
||||||
|
targetIPs: [this.settings.targetIP!],
|
||||||
|
portRanges: [],
|
||||||
|
},
|
||||||
|
localPort
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
// Attempt to find a matching forced domain config based on the local port.
|
// Attempt to find a matching forced domain config based on the local port.
|
||||||
const forcedDomain = this.settings.domainConfigs.find(
|
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) {
|
if (forcedDomain) {
|
||||||
const effectiveAllowedIPs: string[] = [
|
const effectiveAllowedIPs: string[] = [
|
||||||
...forcedDomain.allowedIPs,
|
...forcedDomain.allowedIPs,
|
||||||
...(this.settings.defaultAllowedIPs || [])
|
...(this.settings.defaultAllowedIPs || []),
|
||||||
];
|
];
|
||||||
const effectiveBlockedIPs: string[] = [
|
const effectiveBlockedIPs: string[] = [
|
||||||
...(forcedDomain.blockedIPs || []),
|
...(forcedDomain.blockedIPs || []),
|
||||||
...(this.settings.defaultBlockedIPs || [])
|
...(this.settings.defaultBlockedIPs || []),
|
||||||
];
|
];
|
||||||
if (!isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)) {
|
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();
|
socket.end();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (this.settings.enableDetailedLogging) {
|
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);
|
setupConnection('', undefined, forcedDomain, localPort);
|
||||||
return;
|
return;
|
||||||
@ -1127,7 +1293,9 @@ export class PortProxy {
|
|||||||
connectionRecord.isTLS = true;
|
connectionRecord.isTLS = true;
|
||||||
|
|
||||||
if (this.settings.enableTlsDebugLogging) {
|
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) || '';
|
serverName = extractSNI(chunk, this.settings.enableTlsDebugLogging) || '';
|
||||||
@ -1137,7 +1305,11 @@ export class PortProxy {
|
|||||||
connectionRecord.lockedDomain = serverName;
|
connectionRecord.lockedDomain = serverName;
|
||||||
|
|
||||||
if (this.settings.enableDetailedLogging) {
|
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);
|
setupConnection(serverName, chunk);
|
||||||
@ -1146,8 +1318,15 @@ export class PortProxy {
|
|||||||
initialDataReceived = true;
|
initialDataReceived = true;
|
||||||
connectionRecord.hasReceivedInitialData = true;
|
connectionRecord.hasReceivedInitialData = true;
|
||||||
|
|
||||||
if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0 && !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
if (
|
||||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
|
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('');
|
setupConnection('');
|
||||||
@ -1172,13 +1351,15 @@ export class PortProxy {
|
|||||||
|
|
||||||
// Create a server for each port.
|
// Create a server for each port.
|
||||||
for (const port of listeningPorts) {
|
for (const port of listeningPorts) {
|
||||||
const server = plugins.net
|
const server = plugins.net.createServer(connectionHandler).on('error', (err: Error) => {
|
||||||
.createServer(connectionHandler)
|
console.log(`Server Error on port ${port}: ${err.message}`);
|
||||||
.on('error', (err: Error) => {
|
});
|
||||||
console.log(`Server Error on port ${port}: ${err.message}`);
|
|
||||||
});
|
|
||||||
server.listen(port, () => {
|
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);
|
this.netServers.push(server);
|
||||||
}
|
}
|
||||||
@ -1221,19 +1402,33 @@ export class PortProxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Parity check: if outgoing socket closed and incoming remains active
|
// Parity check: if outgoing socket closed and incoming remains active
|
||||||
if (record.outgoingClosedTime &&
|
if (
|
||||||
!record.incoming.destroyed &&
|
record.outgoingClosedTime &&
|
||||||
!record.connectionClosed &&
|
!record.incoming.destroyed &&
|
||||||
(now - record.outgoingClosedTime > 120000)) {
|
!record.connectionClosed &&
|
||||||
|
now - record.outgoingClosedTime > 120000
|
||||||
|
) {
|
||||||
const remoteIP = record.remoteIP;
|
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');
|
this.cleanupConnection(record, 'parity_check');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for stalled connections waiting for initial data
|
// Check for stalled connections waiting for initial data
|
||||||
if (!record.hasReceivedInitialData &&
|
if (
|
||||||
(now - record.incomingStartTime > this.settings.initialDataTimeout! / 2)) {
|
!record.hasReceivedInitialData &&
|
||||||
console.log(`[${id}] Warning: Connection from ${record.remoteIP} has not received initial data after ${plugins.prettyMs(now - record.incomingStartTime)}`);
|
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
|
// Skip inactivity check if disabled
|
||||||
@ -1243,7 +1438,11 @@ export class PortProxy {
|
|||||||
|
|
||||||
const inactivityTime = now - record.lastActivity;
|
const inactivityTime = now - record.lastActivity;
|
||||||
if (inactivityTime > inactivityThreshold && !record.connectionClosed) {
|
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');
|
this.cleanupConnection(record, 'inactivity');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1252,9 +1451,14 @@ export class PortProxy {
|
|||||||
// Log detailed stats periodically
|
// Log detailed stats periodically
|
||||||
console.log(
|
console.log(
|
||||||
`Active connections: ${this.connectionRecords.size}. ` +
|
`Active connections: ${this.connectionRecords.size}. ` +
|
||||||
`Types: TLS=${tlsConnections} (Completed=${completedTlsHandshakes}, Pending=${pendingTlsHandshakes}), Non-TLS=${nonTlsConnections}. ` +
|
`Types: TLS=${tlsConnections} (Completed=${completedTlsHandshakes}, Pending=${pendingTlsHandshakes}), Non-TLS=${nonTlsConnections}. ` +
|
||||||
`Longest running: IN=${plugins.prettyMs(maxIncoming)}, OUT=${plugins.prettyMs(maxOutgoing)}. ` +
|
`Longest running: IN=${plugins.prettyMs(maxIncoming)}, OUT=${plugins.prettyMs(
|
||||||
`Termination stats: ${JSON.stringify({IN: this.terminationStats.incoming, OUT: this.terminationStats.outgoing})}`
|
maxOutgoing
|
||||||
|
)}. ` +
|
||||||
|
`Termination stats: ${JSON.stringify({
|
||||||
|
IN: this.terminationStats.incoming,
|
||||||
|
OUT: this.terminationStats.outgoing,
|
||||||
|
})}`
|
||||||
);
|
);
|
||||||
}, this.settings.inactivityCheckInterval || 60000);
|
}, this.settings.inactivityCheckInterval || 60000);
|
||||||
|
|
||||||
@ -1268,12 +1472,12 @@ export class PortProxy {
|
|||||||
* Gracefully shut down the proxy
|
* Gracefully shut down the proxy
|
||||||
*/
|
*/
|
||||||
public async stop() {
|
public async stop() {
|
||||||
console.log("PortProxy shutting down...");
|
console.log('PortProxy shutting down...');
|
||||||
this.isShuttingDown = true;
|
this.isShuttingDown = true;
|
||||||
|
|
||||||
// Stop accepting new connections
|
// Stop accepting new connections
|
||||||
const closeServerPromises: Promise<void>[] = this.netServers.map(
|
const closeServerPromises: Promise<void>[] = this.netServers.map(
|
||||||
server =>
|
(server) =>
|
||||||
new Promise<void>((resolve) => {
|
new Promise<void>((resolve) => {
|
||||||
if (!server.listening) {
|
if (!server.listening) {
|
||||||
resolve();
|
resolve();
|
||||||
@ -1296,7 +1500,7 @@ export class PortProxy {
|
|||||||
|
|
||||||
// Wait for servers to close
|
// Wait for servers to close
|
||||||
await Promise.all(closeServerPromises);
|
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
|
// Force destroy all active connections immediately
|
||||||
const connectionIds = [...this.connectionRecords.keys()];
|
const connectionIds = [...this.connectionRecords.keys()];
|
||||||
@ -1328,7 +1532,7 @@ export class PortProxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Short delay to allow graceful ends to process
|
// 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
|
// Second pass: Force destroy everything
|
||||||
for (const id of connectionIds) {
|
for (const id of connectionIds) {
|
||||||
@ -1365,9 +1569,9 @@ export class PortProxy {
|
|||||||
// Reset termination stats
|
// Reset termination stats
|
||||||
this.terminationStats = {
|
this.terminationStats = {
|
||||||
incoming: {},
|
incoming: {},
|
||||||
outgoing: {}
|
outgoing: {},
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log("PortProxy shutdown complete.");
|
console.log('PortProxy shutdown complete.');
|
||||||
}
|
}
|
||||||
}
|
}
|
Loading…
x
Reference in New Issue
Block a user