This commit is contained in:
2025-05-09 21:21:28 +00:00
parent d57d343050
commit b214e58a26
41 changed files with 502 additions and 2224 deletions

View File

@ -0,0 +1,413 @@
import * as plugins from '../../plugins.js';
import * as fs from 'fs';
import * as path from 'path';
import { fileURLToPath } from 'url';
import { type NetworkProxyOptions, type CertificateEntry, type Logger, createLogger } from './models/types.js';
import { Port80Handler } from '../../http/port80/port80-handler.js';
import { CertificateEvents } from '../../certificate/events/certificate-events.js';
import { buildPort80Handler } from '../../certificate/acme/acme-factory.js';
import { subscribeToPort80Handler } from '../../core/utils/event-utils.js';
import type { DomainOptions } from '../../certificate/models/certificate-types.js';
/**
* Manages SSL certificates for NetworkProxy including ACME integration
*/
export class CertificateManager {
private defaultCertificates: { key: string; cert: string };
private certificateCache: Map<string, CertificateEntry> = new Map();
private port80Handler: Port80Handler | null = null;
private externalPort80Handler: boolean = false;
private certificateStoreDir: string;
private logger: Logger;
private httpsServer: plugins.https.Server | null = null;
constructor(private options: NetworkProxyOptions) {
this.certificateStoreDir = path.resolve(options.acme?.certificateStore || './certs');
this.logger = createLogger(options.logLevel || 'info');
// Ensure certificate store directory exists
try {
if (!fs.existsSync(this.certificateStoreDir)) {
fs.mkdirSync(this.certificateStoreDir, { recursive: true });
this.logger.info(`Created certificate store directory: ${this.certificateStoreDir}`);
}
} catch (error) {
this.logger.warn(`Failed to create certificate store directory: ${error}`);
}
this.loadDefaultCertificates();
}
/**
* Loads default certificates from the filesystem
*/
public loadDefaultCertificates(): void {
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const certPath = path.join(__dirname, '..', '..', 'assets', 'certs');
try {
this.defaultCertificates = {
key: fs.readFileSync(path.join(certPath, 'key.pem'), 'utf8'),
cert: fs.readFileSync(path.join(certPath, 'cert.pem'), 'utf8')
};
this.logger.info('Default certificates loaded successfully');
} catch (error) {
this.logger.error('Error loading default certificates', error);
// Generate self-signed fallback certificates
try {
// This is a placeholder for actual certificate generation code
// In a real implementation, you would use a library like selfsigned to generate certs
this.defaultCertificates = {
key: "FALLBACK_KEY_CONTENT",
cert: "FALLBACK_CERT_CONTENT"
};
this.logger.warn('Using fallback self-signed certificates');
} catch (fallbackError) {
this.logger.error('Failed to generate fallback certificates', fallbackError);
throw new Error('Could not load or generate SSL certificates');
}
}
}
/**
* Set the HTTPS server reference for context updates
*/
public setHttpsServer(server: plugins.https.Server): void {
this.httpsServer = server;
}
/**
* Get default certificates
*/
public getDefaultCertificates(): { key: string; cert: string } {
return { ...this.defaultCertificates };
}
/**
* Sets an external Port80Handler for certificate management
*/
public setExternalPort80Handler(handler: Port80Handler): void {
if (this.port80Handler && !this.externalPort80Handler) {
this.logger.warn('Replacing existing internal Port80Handler with external handler');
// Clean up existing handler if needed
if (this.port80Handler !== handler) {
// Unregister event handlers to avoid memory leaks
this.port80Handler.removeAllListeners(CertificateEvents.CERTIFICATE_ISSUED);
this.port80Handler.removeAllListeners(CertificateEvents.CERTIFICATE_RENEWED);
this.port80Handler.removeAllListeners(CertificateEvents.CERTIFICATE_FAILED);
this.port80Handler.removeAllListeners(CertificateEvents.CERTIFICATE_EXPIRING);
}
}
// Set the external handler
this.port80Handler = handler;
this.externalPort80Handler = true;
// Subscribe to Port80Handler events
subscribeToPort80Handler(this.port80Handler, {
onCertificateIssued: this.handleCertificateIssued.bind(this),
onCertificateRenewed: this.handleCertificateIssued.bind(this),
onCertificateFailed: this.handleCertificateFailed.bind(this),
onCertificateExpiring: (data) => {
this.logger.info(`Certificate for ${data.domain} expires in ${data.daysRemaining} days`);
}
});
this.logger.info('External Port80Handler connected to CertificateManager');
// Register domains with Port80Handler if we have any certificates cached
if (this.certificateCache.size > 0) {
const domains = Array.from(this.certificateCache.keys())
.filter(domain => !domain.includes('*')); // Skip wildcard domains
this.registerDomainsWithPort80Handler(domains);
}
}
/**
* Handle newly issued or renewed certificates from Port80Handler
*/
private handleCertificateIssued(data: { domain: string; certificate: string; privateKey: string; expiryDate: Date }): void {
const { domain, certificate, privateKey, expiryDate } = data;
this.logger.info(`Certificate ${this.certificateCache.has(domain) ? 'renewed' : 'issued'} for ${domain}, valid until ${expiryDate.toISOString()}`);
// Update certificate in HTTPS server
this.updateCertificateCache(domain, certificate, privateKey, expiryDate);
// Save the certificate to the filesystem if not using external handler
if (!this.externalPort80Handler && this.options.acme?.certificateStore) {
this.saveCertificateToStore(domain, certificate, privateKey);
}
}
/**
* Handle certificate issuance failures
*/
private handleCertificateFailed(data: { domain: string; error: string }): void {
this.logger.error(`Certificate issuance failed for ${data.domain}: ${data.error}`);
}
/**
* Saves certificate and private key to the filesystem
*/
private saveCertificateToStore(domain: string, certificate: string, privateKey: string): void {
try {
const certPath = path.join(this.certificateStoreDir, `${domain}.cert.pem`);
const keyPath = path.join(this.certificateStoreDir, `${domain}.key.pem`);
fs.writeFileSync(certPath, certificate);
fs.writeFileSync(keyPath, privateKey);
// Ensure private key has restricted permissions
try {
fs.chmodSync(keyPath, 0o600);
} catch (error) {
this.logger.warn(`Failed to set permissions on private key for ${domain}: ${error}`);
}
this.logger.info(`Saved certificate for ${domain} to ${certPath}`);
} catch (error) {
this.logger.error(`Failed to save certificate for ${domain}: ${error}`);
}
}
/**
* Handles SNI (Server Name Indication) for TLS connections
* Used by the HTTPS server to select the correct certificate for each domain
*/
public handleSNI(domain: string, cb: (err: Error | null, ctx: plugins.tls.SecureContext) => void): void {
this.logger.debug(`SNI request for domain: ${domain}`);
// Check if we have a certificate for this domain
const certs = this.certificateCache.get(domain);
if (certs) {
try {
// Create TLS context with the cached certificate
const context = plugins.tls.createSecureContext({
key: certs.key,
cert: certs.cert
});
this.logger.debug(`Using cached certificate for ${domain}`);
cb(null, context);
return;
} catch (err) {
this.logger.error(`Error creating secure context for ${domain}:`, err);
}
}
// No existing certificate: trigger dynamic provisioning via Port80Handler
if (this.port80Handler) {
try {
this.logger.info(`Triggering on-demand certificate retrieval for ${domain}`);
this.port80Handler.addDomain({
domainName: domain,
sslRedirect: false,
acmeMaintenance: true
});
} catch (err) {
this.logger.error(`Error registering domain for on-demand certificate: ${domain}`, err);
}
}
// Check if we should trigger certificate issuance
if (this.options.acme?.enabled && this.port80Handler && !domain.includes('*')) {
// Check if this domain is already registered
const certData = this.port80Handler.getCertificate(domain);
if (!certData) {
this.logger.info(`No certificate found for ${domain}, registering for issuance`);
// Register with new domain options format
const domainOptions: DomainOptions = {
domainName: domain,
sslRedirect: true,
acmeMaintenance: true
};
this.port80Handler.addDomain(domainOptions);
}
}
// Fall back to default certificate
try {
const context = plugins.tls.createSecureContext({
key: this.defaultCertificates.key,
cert: this.defaultCertificates.cert
});
this.logger.debug(`Using default certificate for ${domain}`);
cb(null, context);
} catch (err) {
this.logger.error(`Error creating default secure context:`, err);
cb(new Error('Cannot create secure context'), null);
}
}
/**
* Updates certificate in cache
*/
public updateCertificateCache(domain: string, certificate: string, privateKey: string, expiryDate?: Date): void {
// Update certificate context in HTTPS server if it's running
if (this.httpsServer) {
try {
this.httpsServer.addContext(domain, {
key: privateKey,
cert: certificate
});
this.logger.debug(`Updated SSL context for domain: ${domain}`);
} catch (error) {
this.logger.error(`Error updating SSL context for domain ${domain}:`, error);
}
}
// Update certificate in cache
this.certificateCache.set(domain, {
key: privateKey,
cert: certificate,
expires: expiryDate
});
}
/**
* Gets a certificate for a domain
*/
public getCertificate(domain: string): CertificateEntry | undefined {
return this.certificateCache.get(domain);
}
/**
* Requests a new certificate for a domain
*/
public async requestCertificate(domain: string): Promise<boolean> {
if (!this.options.acme?.enabled && !this.externalPort80Handler) {
this.logger.warn('ACME certificate management is not enabled');
return false;
}
if (!this.port80Handler) {
this.logger.error('Port80Handler is not initialized');
return false;
}
// Skip wildcard domains - can't get certs for these with HTTP-01 validation
if (domain.includes('*')) {
this.logger.error(`Cannot request certificate for wildcard domain: ${domain}`);
return false;
}
try {
// Use the new domain options format
const domainOptions: DomainOptions = {
domainName: domain,
sslRedirect: true,
acmeMaintenance: true
};
this.port80Handler.addDomain(domainOptions);
this.logger.info(`Certificate request submitted for domain: ${domain}`);
return true;
} catch (error) {
this.logger.error(`Error requesting certificate for domain ${domain}:`, error);
return false;
}
}
/**
* Registers domains with Port80Handler for ACME certificate management
*/
public registerDomainsWithPort80Handler(domains: string[]): void {
if (!this.port80Handler) {
this.logger.warn('Port80Handler is not initialized');
return;
}
for (const domain of domains) {
// Skip wildcard domains - can't get certs for these with HTTP-01 validation
if (domain.includes('*')) {
this.logger.info(`Skipping wildcard domain for ACME: ${domain}`);
continue;
}
// Skip domains already with certificates if configured to do so
if (this.options.acme?.skipConfiguredCerts) {
const cachedCert = this.certificateCache.get(domain);
if (cachedCert) {
this.logger.info(`Skipping domain with existing certificate: ${domain}`);
continue;
}
}
// Register the domain for certificate issuance with new domain options format
const domainOptions: DomainOptions = {
domainName: domain,
sslRedirect: true,
acmeMaintenance: true
};
this.port80Handler.addDomain(domainOptions);
this.logger.info(`Registered domain for ACME certificate issuance: ${domain}`);
}
}
/**
* Initialize internal Port80Handler
*/
public async initializePort80Handler(): Promise<Port80Handler | null> {
// Skip if using external handler
if (this.externalPort80Handler) {
this.logger.info('Using external Port80Handler, skipping initialization');
return this.port80Handler;
}
if (!this.options.acme?.enabled) {
return null;
}
// Build and configure Port80Handler
this.port80Handler = buildPort80Handler({
port: this.options.acme.port,
accountEmail: this.options.acme.accountEmail,
useProduction: this.options.acme.useProduction,
httpsRedirectPort: this.options.port, // Redirect to our HTTPS port
enabled: this.options.acme.enabled,
certificateStore: this.options.acme.certificateStore,
skipConfiguredCerts: this.options.acme.skipConfiguredCerts
});
// Subscribe to Port80Handler events
subscribeToPort80Handler(this.port80Handler, {
onCertificateIssued: this.handleCertificateIssued.bind(this),
onCertificateRenewed: this.handleCertificateIssued.bind(this),
onCertificateFailed: this.handleCertificateFailed.bind(this),
onCertificateExpiring: (data) => {
this.logger.info(`Certificate for ${data.domain} expires in ${data.daysRemaining} days`);
}
});
// Start the handler
try {
await this.port80Handler.start();
this.logger.info(`Port80Handler started on port ${this.options.acme.port}`);
return this.port80Handler;
} catch (error) {
this.logger.error(`Failed to start Port80Handler: ${error}`);
this.port80Handler = null;
return null;
}
}
/**
* Stop the Port80Handler if it was internally created
*/
public async stopPort80Handler(): Promise<void> {
if (this.port80Handler && !this.externalPort80Handler) {
try {
await this.port80Handler.stop();
this.logger.info('Port80Handler stopped');
} catch (error) {
this.logger.error('Error stopping Port80Handler', error);
}
}
}
}

View File

@ -0,0 +1,241 @@
import * as plugins from '../../plugins.js';
import { type NetworkProxyOptions, type ConnectionEntry, type Logger, createLogger } from './models/types.js';
/**
* Manages a pool of backend connections for efficient reuse
*/
export class ConnectionPool {
private connectionPool: Map<string, Array<ConnectionEntry>> = new Map();
private roundRobinPositions: Map<string, number> = new Map();
private logger: Logger;
constructor(private options: NetworkProxyOptions) {
this.logger = createLogger(options.logLevel || 'info');
}
/**
* Get a connection from the pool or create a new one
*/
public getConnection(host: string, port: number): Promise<plugins.net.Socket> {
return new Promise((resolve, reject) => {
const poolKey = `${host}:${port}`;
const connectionList = this.connectionPool.get(poolKey) || [];
// Look for an idle connection
const idleConnectionIndex = connectionList.findIndex(c => c.isIdle);
if (idleConnectionIndex >= 0) {
// Get existing connection from pool
const connection = connectionList[idleConnectionIndex];
connection.isIdle = false;
connection.lastUsed = Date.now();
this.logger.debug(`Reusing connection from pool for ${poolKey}`);
// Update the pool
this.connectionPool.set(poolKey, connectionList);
resolve(connection.socket);
return;
}
// No idle connection available, create a new one if pool isn't full
const poolSize = this.options.connectionPoolSize || 50;
if (connectionList.length < poolSize) {
this.logger.debug(`Creating new connection to ${host}:${port}`);
try {
const socket = plugins.net.connect({
host,
port,
keepAlive: true,
keepAliveInitialDelay: 30000 // 30 seconds
});
socket.once('connect', () => {
// Add to connection pool
const connection = {
socket,
lastUsed: Date.now(),
isIdle: false
};
connectionList.push(connection);
this.connectionPool.set(poolKey, connectionList);
// Setup cleanup when the connection is closed
socket.once('close', () => {
const idx = connectionList.findIndex(c => c.socket === socket);
if (idx >= 0) {
connectionList.splice(idx, 1);
this.connectionPool.set(poolKey, connectionList);
this.logger.debug(`Removed closed connection from pool for ${poolKey}`);
}
});
resolve(socket);
});
socket.once('error', (err) => {
this.logger.error(`Error creating connection to ${host}:${port}`, err);
reject(err);
});
} catch (err) {
this.logger.error(`Failed to create connection to ${host}:${port}`, err);
reject(err);
}
} else {
// Pool is full, wait for an idle connection or reject
this.logger.warn(`Connection pool for ${poolKey} is full (${connectionList.length})`);
reject(new Error(`Connection pool for ${poolKey} is full`));
}
});
}
/**
* Return a connection to the pool for reuse
*/
public returnConnection(socket: plugins.net.Socket, host: string, port: number): void {
const poolKey = `${host}:${port}`;
const connectionList = this.connectionPool.get(poolKey) || [];
// Find this connection in the pool
const connectionIndex = connectionList.findIndex(c => c.socket === socket);
if (connectionIndex >= 0) {
// Mark as idle and update last used time
connectionList[connectionIndex].isIdle = true;
connectionList[connectionIndex].lastUsed = Date.now();
this.logger.debug(`Returned connection to pool for ${poolKey}`);
} else {
this.logger.warn(`Attempted to return unknown connection to pool for ${poolKey}`);
}
}
/**
* Cleanup the connection pool by removing idle connections
* or reducing pool size if it exceeds the configured maximum
*/
public cleanupConnectionPool(): void {
const now = Date.now();
const idleTimeout = this.options.keepAliveTimeout || 120000; // 2 minutes default
for (const [host, connections] of this.connectionPool.entries()) {
// Sort by last used time (oldest first)
connections.sort((a, b) => a.lastUsed - b.lastUsed);
// Remove idle connections older than the idle timeout
let removed = 0;
while (connections.length > 0) {
const connection = connections[0];
// Remove if idle and exceeds timeout, or if pool is too large
if ((connection.isIdle && now - connection.lastUsed > idleTimeout) ||
connections.length > (this.options.connectionPoolSize || 50)) {
try {
if (!connection.socket.destroyed) {
connection.socket.end();
connection.socket.destroy();
}
} catch (err) {
this.logger.error(`Error destroying pooled connection to ${host}`, err);
}
connections.shift(); // Remove from pool
removed++;
} else {
break; // Stop removing if we've reached active or recent connections
}
}
if (removed > 0) {
this.logger.debug(`Removed ${removed} idle connections from pool for ${host}, ${connections.length} remaining`);
}
// Update the pool with the remaining connections
if (connections.length === 0) {
this.connectionPool.delete(host);
} else {
this.connectionPool.set(host, connections);
}
}
}
/**
* Close all connections in the pool
*/
public closeAllConnections(): void {
for (const [host, connections] of this.connectionPool.entries()) {
this.logger.debug(`Closing ${connections.length} connections to ${host}`);
for (const connection of connections) {
try {
if (!connection.socket.destroyed) {
connection.socket.end();
connection.socket.destroy();
}
} catch (error) {
this.logger.error(`Error closing connection to ${host}:`, error);
}
}
}
this.connectionPool.clear();
this.roundRobinPositions.clear();
}
/**
* Get load balancing target using round-robin
*/
public getNextTarget(targets: string[], port: number): { host: string, port: number } {
const targetKey = targets.join(',');
// Initialize position if not exists
if (!this.roundRobinPositions.has(targetKey)) {
this.roundRobinPositions.set(targetKey, 0);
}
// Get current position and increment for next time
const currentPosition = this.roundRobinPositions.get(targetKey)!;
const nextPosition = (currentPosition + 1) % targets.length;
this.roundRobinPositions.set(targetKey, nextPosition);
// Return the selected target
return {
host: targets[currentPosition],
port
};
}
/**
* Gets the connection pool status
*/
public getPoolStatus(): Record<string, { total: number, idle: number }> {
return Object.fromEntries(
Array.from(this.connectionPool.entries()).map(([host, connections]) => [
host,
{
total: connections.length,
idle: connections.filter(c => c.isIdle).length
}
])
);
}
/**
* Setup a periodic cleanup task
*/
public setupPeriodicCleanup(interval: number = 60000): NodeJS.Timeout {
const timer = setInterval(() => {
this.cleanupConnectionPool();
}, interval);
// Don't prevent process exit
if (timer.unref) {
timer.unref();
}
return timer;
}
}

View File

@ -4,5 +4,10 @@
// Re-export models
export * from './models/index.js';
// Core NetworkProxy will be added later:
// export { NetworkProxy } from './network-proxy.js';
// Export NetworkProxy and supporting classes
export { NetworkProxy } from './network-proxy.js';
export { CertificateManager } from './certificate-manager.js';
export { ConnectionPool } from './connection-pool.js';
export { RequestHandler } from './request-handler.js';
export type { IMetricsTracker, MetricsTracker } from './request-handler.js';
export { WebSocketHandler } from './websocket-handler.js';

View File

@ -0,0 +1,484 @@
import * as plugins from '../../plugins.js';
import {
createLogger
} from './models/types.js';
import type {
NetworkProxyOptions,
Logger,
ReverseProxyConfig
} from './models/types.js';
import { CertificateManager } from './certificate-manager.js';
import { ConnectionPool } from './connection-pool.js';
import { RequestHandler, type IMetricsTracker } from './request-handler.js';
import { WebSocketHandler } from './websocket-handler.js';
import { ProxyRouter } from '../../http/router/index.js';
import { Port80Handler } from '../../http/port80/port80-handler.js';
/**
* NetworkProxy provides a reverse proxy with TLS termination, WebSocket support,
* automatic certificate management, and high-performance connection pooling.
*/
export class NetworkProxy implements IMetricsTracker {
// Provide a minimal JSON representation to avoid circular references during deep equality checks
public toJSON(): any {
return {};
}
// Configuration
public options: NetworkProxyOptions;
public proxyConfigs: ReverseProxyConfig[] = [];
// Server instances (HTTP/2 with HTTP/1 fallback)
public httpsServer: any;
// Core components
private certificateManager: CertificateManager;
private connectionPool: ConnectionPool;
private requestHandler: RequestHandler;
private webSocketHandler: WebSocketHandler;
private router = new ProxyRouter();
// State tracking
public socketMap = new plugins.lik.ObjectMap<plugins.net.Socket>();
public activeContexts: Set<string> = new Set();
public connectedClients: number = 0;
public startTime: number = 0;
public requestsServed: number = 0;
public failedRequests: number = 0;
// Tracking for SmartProxy integration
private portProxyConnections: number = 0;
private tlsTerminatedConnections: number = 0;
// Timers
private metricsInterval: NodeJS.Timeout;
private connectionPoolCleanupInterval: NodeJS.Timeout;
// Logger
private logger: Logger;
/**
* Creates a new NetworkProxy instance
*/
constructor(optionsArg: NetworkProxyOptions) {
// Set default options
this.options = {
port: optionsArg.port,
maxConnections: optionsArg.maxConnections || 10000,
keepAliveTimeout: optionsArg.keepAliveTimeout || 120000, // 2 minutes
headersTimeout: optionsArg.headersTimeout || 60000, // 1 minute
logLevel: optionsArg.logLevel || 'info',
cors: optionsArg.cors || {
allowOrigin: '*',
allowMethods: 'GET, POST, PUT, DELETE, OPTIONS',
allowHeaders: 'Content-Type, Authorization',
maxAge: 86400
},
// Defaults for SmartProxy integration
connectionPoolSize: optionsArg.connectionPoolSize || 50,
portProxyIntegration: optionsArg.portProxyIntegration || false,
useExternalPort80Handler: optionsArg.useExternalPort80Handler || false,
// Backend protocol (http1 or http2)
backendProtocol: optionsArg.backendProtocol || 'http1',
// Default ACME options
acme: {
enabled: optionsArg.acme?.enabled || false,
port: optionsArg.acme?.port || 80,
accountEmail: optionsArg.acme?.accountEmail || 'admin@example.com',
useProduction: optionsArg.acme?.useProduction || false, // Default to staging for safety
renewThresholdDays: optionsArg.acme?.renewThresholdDays || 30,
autoRenew: optionsArg.acme?.autoRenew !== false, // Default to true
certificateStore: optionsArg.acme?.certificateStore || './certs',
skipConfiguredCerts: optionsArg.acme?.skipConfiguredCerts || false
}
};
// Initialize logger
this.logger = createLogger(this.options.logLevel);
// Initialize components
this.certificateManager = new CertificateManager(this.options);
this.connectionPool = new ConnectionPool(this.options);
this.requestHandler = new RequestHandler(this.options, this.connectionPool, this.router);
this.webSocketHandler = new WebSocketHandler(this.options, this.connectionPool, this.router);
// Connect request handler to this metrics tracker
this.requestHandler.setMetricsTracker(this);
}
/**
* Implements IMetricsTracker interface to increment request counters
*/
public incrementRequestsServed(): void {
this.requestsServed++;
}
/**
* Implements IMetricsTracker interface to increment failed request counters
*/
public incrementFailedRequests(): void {
this.failedRequests++;
}
/**
* Returns the port number this NetworkProxy is listening on
* Useful for SmartProxy to determine where to forward connections
*/
public getListeningPort(): number {
return this.options.port;
}
/**
* Updates the server capacity settings
* @param maxConnections Maximum number of simultaneous connections
* @param keepAliveTimeout Keep-alive timeout in milliseconds
* @param connectionPoolSize Size of the connection pool per backend
*/
public updateCapacity(maxConnections?: number, keepAliveTimeout?: number, connectionPoolSize?: number): void {
if (maxConnections !== undefined) {
this.options.maxConnections = maxConnections;
this.logger.info(`Updated max connections to ${maxConnections}`);
}
if (keepAliveTimeout !== undefined) {
this.options.keepAliveTimeout = keepAliveTimeout;
if (this.httpsServer) {
this.httpsServer.keepAliveTimeout = keepAliveTimeout;
this.logger.info(`Updated keep-alive timeout to ${keepAliveTimeout}ms`);
}
}
if (connectionPoolSize !== undefined) {
this.options.connectionPoolSize = connectionPoolSize;
this.logger.info(`Updated connection pool size to ${connectionPoolSize}`);
// Clean up excess connections in the pool
this.connectionPool.cleanupConnectionPool();
}
}
/**
* Returns current server metrics
* Useful for SmartProxy to determine which NetworkProxy to use for load balancing
*/
public getMetrics(): any {
return {
activeConnections: this.connectedClients,
totalRequests: this.requestsServed,
failedRequests: this.failedRequests,
portProxyConnections: this.portProxyConnections,
tlsTerminatedConnections: this.tlsTerminatedConnections,
connectionPoolSize: this.connectionPool.getPoolStatus(),
uptime: Math.floor((Date.now() - this.startTime) / 1000),
memoryUsage: process.memoryUsage(),
activeWebSockets: this.webSocketHandler.getConnectionInfo().activeConnections
};
}
/**
* Sets an external Port80Handler for certificate management
* This allows the NetworkProxy to use a centrally managed Port80Handler
* instead of creating its own
*
* @param handler The Port80Handler instance to use
*/
public setExternalPort80Handler(handler: Port80Handler): void {
// Connect it to the certificate manager
this.certificateManager.setExternalPort80Handler(handler);
}
/**
* Starts the proxy server
*/
public async start(): Promise<void> {
this.startTime = Date.now();
// Initialize Port80Handler if enabled and not using external handler
if (this.options.acme?.enabled && !this.options.useExternalPort80Handler) {
await this.certificateManager.initializePort80Handler();
}
// Create HTTP/2 server with HTTP/1 fallback
this.httpsServer = plugins.http2.createSecureServer(
{
key: this.certificateManager.getDefaultCertificates().key,
cert: this.certificateManager.getDefaultCertificates().cert,
allowHTTP1: true,
ALPNProtocols: ['h2', 'http/1.1']
}
);
// Track raw TCP connections for metrics and limits
this.setupConnectionTracking();
// Handle incoming HTTP/2 streams
this.httpsServer.on('stream', (stream: any, headers: any) => {
this.requestHandler.handleHttp2(stream, headers);
});
// Handle HTTP/1.x fallback requests
this.httpsServer.on('request', (req: any, res: any) => {
this.requestHandler.handleRequest(req, res);
});
// Share server with certificate manager for dynamic contexts
this.certificateManager.setHttpsServer(this.httpsServer);
// Setup WebSocket support on HTTP/1 fallback
this.webSocketHandler.initialize(this.httpsServer);
// Start metrics logging
this.setupMetricsCollection();
// Start periodic connection pool cleanup
this.connectionPoolCleanupInterval = this.connectionPool.setupPeriodicCleanup();
// Start the server
return new Promise((resolve) => {
this.httpsServer.listen(this.options.port, () => {
this.logger.info(`NetworkProxy started on port ${this.options.port}`);
resolve();
});
});
}
/**
* Sets up tracking of TCP connections
*/
private setupConnectionTracking(): void {
this.httpsServer.on('connection', (connection: plugins.net.Socket) => {
// Check if max connections reached
if (this.socketMap.getArray().length >= this.options.maxConnections) {
this.logger.warn(`Max connections (${this.options.maxConnections}) reached, rejecting new connection`);
connection.destroy();
return;
}
// Add connection to tracking
this.socketMap.add(connection);
this.connectedClients = this.socketMap.getArray().length;
// Check for connection from SmartProxy by inspecting the source port
const localPort = connection.localPort || 0;
const remotePort = connection.remotePort || 0;
// If this connection is from a SmartProxy (usually indicated by it coming from localhost)
if (this.options.portProxyIntegration && connection.remoteAddress?.includes('127.0.0.1')) {
this.portProxyConnections++;
this.logger.debug(`New connection from SmartProxy (local: ${localPort}, remote: ${remotePort})`);
} else {
this.logger.debug(`New direct connection (local: ${localPort}, remote: ${remotePort})`);
}
// Setup connection cleanup handlers
const cleanupConnection = () => {
if (this.socketMap.checkForObject(connection)) {
this.socketMap.remove(connection);
this.connectedClients = this.socketMap.getArray().length;
// If this was a SmartProxy connection, decrement the counter
if (this.options.portProxyIntegration && connection.remoteAddress?.includes('127.0.0.1')) {
this.portProxyConnections--;
}
this.logger.debug(`Connection closed. ${this.connectedClients} connections remaining`);
}
};
connection.on('close', cleanupConnection);
connection.on('error', (err) => {
this.logger.debug('Connection error', err);
cleanupConnection();
});
connection.on('end', cleanupConnection);
});
// Track TLS handshake completions
this.httpsServer.on('secureConnection', (tlsSocket) => {
this.tlsTerminatedConnections++;
this.logger.debug('TLS handshake completed, connection secured');
});
}
/**
* Sets up metrics collection
*/
private setupMetricsCollection(): void {
this.metricsInterval = setInterval(() => {
const uptime = Math.floor((Date.now() - this.startTime) / 1000);
const metrics = {
uptime,
activeConnections: this.connectedClients,
totalRequests: this.requestsServed,
failedRequests: this.failedRequests,
portProxyConnections: this.portProxyConnections,
tlsTerminatedConnections: this.tlsTerminatedConnections,
activeWebSockets: this.webSocketHandler.getConnectionInfo().activeConnections,
memoryUsage: process.memoryUsage(),
activeContexts: Array.from(this.activeContexts),
connectionPool: this.connectionPool.getPoolStatus()
};
this.logger.debug('Proxy metrics', metrics);
}, 60000); // Log metrics every minute
// Don't keep process alive just for metrics
if (this.metricsInterval.unref) {
this.metricsInterval.unref();
}
}
/**
* Updates proxy configurations
*/
public async updateProxyConfigs(
proxyConfigsArg: ReverseProxyConfig[]
): Promise<void> {
this.logger.info(`Updating proxy configurations (${proxyConfigsArg.length} configs)`);
// Update internal configs
this.proxyConfigs = proxyConfigsArg;
this.router.setNewProxyConfigs(proxyConfigsArg);
// Collect all hostnames for cleanup later
const currentHostNames = new Set<string>();
// Add/update SSL contexts for each host
for (const config of proxyConfigsArg) {
currentHostNames.add(config.hostName);
try {
// Update certificate in cache
this.certificateManager.updateCertificateCache(
config.hostName,
config.publicKey,
config.privateKey
);
this.activeContexts.add(config.hostName);
} catch (error) {
this.logger.error(`Failed to add SSL context for ${config.hostName}`, error);
}
}
// Clean up removed contexts
for (const hostname of this.activeContexts) {
if (!currentHostNames.has(hostname)) {
this.logger.info(`Hostname ${hostname} removed from configuration`);
this.activeContexts.delete(hostname);
}
}
// Register domains with Port80Handler if available
const domainsForACME = Array.from(currentHostNames)
.filter(domain => !domain.includes('*')); // Skip wildcard domains
this.certificateManager.registerDomainsWithPort80Handler(domainsForACME);
}
/**
* Converts SmartProxy domain configurations to NetworkProxy configs
* @param domainConfigs SmartProxy domain configs
* @param sslKeyPair Default SSL key pair to use if not specified
* @returns Array of NetworkProxy configs
*/
public convertSmartProxyConfigs(
domainConfigs: Array<{
domains: string[];
targetIPs?: string[];
allowedIPs?: string[];
}>,
sslKeyPair?: { key: string; cert: string }
): ReverseProxyConfig[] {
const proxyConfigs: ReverseProxyConfig[] = [];
// Use default certificates if not provided
const defaultCerts = this.certificateManager.getDefaultCertificates();
const sslKey = sslKeyPair?.key || defaultCerts.key;
const sslCert = sslKeyPair?.cert || defaultCerts.cert;
for (const domainConfig of domainConfigs) {
// Each domain in the domains array gets its own config
for (const domain of domainConfig.domains) {
// Skip non-hostname patterns (like IP addresses)
if (domain.match(/^\d+\.\d+\.\d+\.\d+$/) || domain === '*' || domain === 'localhost') {
continue;
}
proxyConfigs.push({
hostName: domain,
destinationIps: domainConfig.targetIPs || ['localhost'],
destinationPorts: [this.options.port], // Use the NetworkProxy port
privateKey: sslKey,
publicKey: sslCert
});
}
}
this.logger.info(`Converted ${domainConfigs.length} SmartProxy configs to ${proxyConfigs.length} NetworkProxy configs`);
return proxyConfigs;
}
/**
* Adds default headers to be included in all responses
*/
public async addDefaultHeaders(headersArg: { [key: string]: string }): Promise<void> {
this.logger.info('Adding default headers', headersArg);
this.requestHandler.setDefaultHeaders(headersArg);
}
/**
* Stops the proxy server
*/
public async stop(): Promise<void> {
this.logger.info('Stopping NetworkProxy server');
// Clear intervals
if (this.metricsInterval) {
clearInterval(this.metricsInterval);
}
if (this.connectionPoolCleanupInterval) {
clearInterval(this.connectionPoolCleanupInterval);
}
// Stop WebSocket handler
this.webSocketHandler.shutdown();
// Close all tracked sockets
for (const socket of this.socketMap.getArray()) {
try {
socket.destroy();
} catch (error) {
this.logger.error('Error destroying socket', error);
}
}
// Close all connection pool connections
this.connectionPool.closeAllConnections();
// Stop Port80Handler if internally managed
await this.certificateManager.stopPort80Handler();
// Close the HTTPS server
return new Promise((resolve) => {
this.httpsServer.close(() => {
this.logger.info('NetworkProxy server stopped successfully');
resolve();
});
});
}
/**
* Requests a new certificate for a domain
* This can be used to manually trigger certificate issuance
* @param domain The domain to request a certificate for
* @returns A promise that resolves when the request is submitted (not when the certificate is issued)
*/
public async requestCertificate(domain: string): Promise<boolean> {
return this.certificateManager.requestCertificate(domain);
}
/**
* Gets all proxy configurations currently in use
*/
public getProxyConfigs(): ReverseProxyConfig[] {
return [...this.proxyConfigs];
}
}

View File

@ -0,0 +1,463 @@
import * as plugins from '../../plugins.js';
import { type NetworkProxyOptions, type Logger, createLogger, type ReverseProxyConfig } from './models/types.js';
import { ConnectionPool } from './connection-pool.js';
import { ProxyRouter } from '../../http/router/index.js';
/**
* Interface for tracking metrics
*/
export interface IMetricsTracker {
incrementRequestsServed(): void;
incrementFailedRequests(): void;
}
// Backward compatibility
export type MetricsTracker = IMetricsTracker;
/**
* Handles HTTP request processing and proxying
*/
export class RequestHandler {
private defaultHeaders: { [key: string]: string } = {};
private logger: Logger;
private metricsTracker: IMetricsTracker | null = null;
// HTTP/2 client sessions for backend proxying
private h2Sessions: Map<string, plugins.http2.ClientHttp2Session> = new Map();
constructor(
private options: NetworkProxyOptions,
private connectionPool: ConnectionPool,
private router: ProxyRouter
) {
this.logger = createLogger(options.logLevel || 'info');
}
/**
* Set the metrics tracker instance
*/
public setMetricsTracker(tracker: IMetricsTracker): void {
this.metricsTracker = tracker;
}
/**
* Set default headers to be included in all responses
*/
public setDefaultHeaders(headers: { [key: string]: string }): void {
this.defaultHeaders = {
...this.defaultHeaders,
...headers
};
this.logger.info('Updated default response headers');
}
/**
* Get all default headers
*/
public getDefaultHeaders(): { [key: string]: string } {
return { ...this.defaultHeaders };
}
/**
* Apply CORS headers to response if configured
*/
private applyCorsHeaders(
res: plugins.http.ServerResponse,
req: plugins.http.IncomingMessage
): void {
if (!this.options.cors) {
return;
}
// Apply CORS headers
if (this.options.cors.allowOrigin) {
res.setHeader('Access-Control-Allow-Origin', this.options.cors.allowOrigin);
}
if (this.options.cors.allowMethods) {
res.setHeader('Access-Control-Allow-Methods', this.options.cors.allowMethods);
}
if (this.options.cors.allowHeaders) {
res.setHeader('Access-Control-Allow-Headers', this.options.cors.allowHeaders);
}
if (this.options.cors.maxAge) {
res.setHeader('Access-Control-Max-Age', this.options.cors.maxAge.toString());
}
// Handle CORS preflight requests
if (req.method === 'OPTIONS') {
res.statusCode = 204; // No content
res.end();
return;
}
}
/**
* Apply default headers to response
*/
private applyDefaultHeaders(res: plugins.http.ServerResponse): void {
// Apply default headers
for (const [key, value] of Object.entries(this.defaultHeaders)) {
if (!res.hasHeader(key)) {
res.setHeader(key, value);
}
}
// Add server identifier if not already set
if (!res.hasHeader('Server')) {
res.setHeader('Server', 'NetworkProxy');
}
}
/**
* Handle an HTTP request
*/
public async handleRequest(
req: plugins.http.IncomingMessage,
res: plugins.http.ServerResponse
): Promise<void> {
// Record start time for logging
const startTime = Date.now();
// Apply CORS headers if configured
this.applyCorsHeaders(res, req);
// If this is an OPTIONS request, the response has already been ended in applyCorsHeaders
// so we should return early to avoid trying to set more headers
if (req.method === 'OPTIONS') {
// Increment metrics for OPTIONS requests too
if (this.metricsTracker) {
this.metricsTracker.incrementRequestsServed();
}
return;
}
// Apply default headers
this.applyDefaultHeaders(res);
// Determine routing configuration
let proxyConfig: ReverseProxyConfig | undefined;
try {
proxyConfig = this.router.routeReq(req);
} catch (err) {
this.logger.error('Error routing request', err);
res.statusCode = 500;
res.end('Internal Server Error');
if (this.metricsTracker) this.metricsTracker.incrementFailedRequests();
return;
}
if (!proxyConfig) {
this.logger.warn(`No proxy configuration for host: ${req.headers.host}`);
res.statusCode = 404;
res.end('Not Found: No proxy configuration for this host');
if (this.metricsTracker) this.metricsTracker.incrementFailedRequests();
return;
}
// Determine protocol to backend (per-domain override or global)
const backendProto = proxyConfig.backendProtocol || this.options.backendProtocol;
if (backendProto === 'http2') {
const destination = this.connectionPool.getNextTarget(
proxyConfig.destinationIps,
proxyConfig.destinationPorts[0]
);
const key = `${destination.host}:${destination.port}`;
let session = this.h2Sessions.get(key);
if (!session || session.closed || (session as any).destroyed) {
session = plugins.http2.connect(`http://${destination.host}:${destination.port}`);
this.h2Sessions.set(key, session);
session.on('error', () => this.h2Sessions.delete(key));
session.on('close', () => this.h2Sessions.delete(key));
}
// Build headers for HTTP/2 request
const hdrs: Record<string, any> = {
':method': req.method,
':path': req.url,
':authority': `${destination.host}:${destination.port}`
};
for (const [hk, hv] of Object.entries(req.headers)) {
if (typeof hv === 'string') hdrs[hk] = hv;
}
const h2Stream = session.request(hdrs);
req.pipe(h2Stream);
h2Stream.on('response', (hdrs2: any) => {
const status = (hdrs2[':status'] as number) || 502;
res.statusCode = status;
// Copy headers from HTTP/2 response to HTTP/1 response
for (const [hk, hv] of Object.entries(hdrs2)) {
if (!hk.startsWith(':') && hv != null) {
res.setHeader(hk, hv as string | string[]);
}
}
h2Stream.pipe(res);
});
h2Stream.on('error', (err) => {
res.statusCode = 502;
res.end(`Bad Gateway: ${err.message}`);
if (this.metricsTracker) this.metricsTracker.incrementFailedRequests();
});
return;
}
try {
// Find target based on hostname
const proxyConfig = this.router.routeReq(req);
if (!proxyConfig) {
// No matching proxy configuration
this.logger.warn(`No proxy configuration for host: ${req.headers.host}`);
res.statusCode = 404;
res.end('Not Found: No proxy configuration for this host');
// Increment failed requests counter
if (this.metricsTracker) {
this.metricsTracker.incrementFailedRequests();
}
return;
}
// Get destination IP using round-robin if multiple IPs configured
const destination = this.connectionPool.getNextTarget(
proxyConfig.destinationIps,
proxyConfig.destinationPorts[0]
);
// Create options for the proxy request
const options: plugins.http.RequestOptions = {
hostname: destination.host,
port: destination.port,
path: req.url,
method: req.method,
headers: { ...req.headers }
};
// Remove host header to avoid issues with virtual hosts on target server
// The host header should match the target server's expected hostname
if (options.headers && options.headers.host) {
if ((proxyConfig as ReverseProxyConfig).rewriteHostHeader) {
options.headers.host = `${destination.host}:${destination.port}`;
}
}
this.logger.debug(
`Proxying request to ${destination.host}:${destination.port}${req.url}`,
{ method: req.method }
);
// Create proxy request
const proxyReq = plugins.http.request(options, (proxyRes) => {
// Copy status code
res.statusCode = proxyRes.statusCode || 500;
// Copy headers from proxy response to client response
for (const [key, value] of Object.entries(proxyRes.headers)) {
if (value !== undefined) {
res.setHeader(key, value);
}
}
// Pipe proxy response to client response
proxyRes.pipe(res);
// Increment served requests counter when the response finishes
res.on('finish', () => {
if (this.metricsTracker) {
this.metricsTracker.incrementRequestsServed();
}
// Log the completed request
const duration = Date.now() - startTime;
this.logger.debug(
`Request completed in ${duration}ms: ${req.method} ${req.url} ${res.statusCode}`,
{ duration, statusCode: res.statusCode }
);
});
});
// Handle proxy request errors
proxyReq.on('error', (error) => {
const duration = Date.now() - startTime;
this.logger.error(
`Proxy error for ${req.method} ${req.url}: ${error.message}`,
{ duration, error: error.message }
);
// Increment failed requests counter
if (this.metricsTracker) {
this.metricsTracker.incrementFailedRequests();
}
// Check if headers have already been sent
if (!res.headersSent) {
res.statusCode = 502;
res.end(`Bad Gateway: ${error.message}`);
} else {
// If headers already sent, just close the connection
res.end();
}
});
// Pipe request body to proxy request and handle client-side errors
req.pipe(proxyReq);
// Handle client disconnection
req.on('error', (error) => {
this.logger.debug(`Client connection error: ${error.message}`);
proxyReq.destroy();
// Increment failed requests counter on client errors
if (this.metricsTracker) {
this.metricsTracker.incrementFailedRequests();
}
});
// Handle response errors
res.on('error', (error) => {
this.logger.debug(`Response error: ${error.message}`);
proxyReq.destroy();
// Increment failed requests counter on response errors
if (this.metricsTracker) {
this.metricsTracker.incrementFailedRequests();
}
});
} catch (error) {
// Handle any unexpected errors
this.logger.error(
`Unexpected error handling request: ${error.message}`,
{ error: error.stack }
);
// Increment failed requests counter
if (this.metricsTracker) {
this.metricsTracker.incrementFailedRequests();
}
if (!res.headersSent) {
res.statusCode = 500;
res.end('Internal Server Error');
} else {
res.end();
}
}
}
/**
* Handle HTTP/2 stream requests by proxying to HTTP/1 backends
*/
public async handleHttp2(stream: any, headers: any): Promise<void> {
const startTime = Date.now();
const method = headers[':method'] || 'GET';
const path = headers[':path'] || '/';
// If configured to proxy to backends over HTTP/2, use HTTP/2 client sessions
if (this.options.backendProtocol === 'http2') {
const authority = headers[':authority'] as string || '';
const host = authority.split(':')[0];
const fakeReq: any = { headers: { host }, method: headers[':method'], url: headers[':path'], socket: (stream.session as any).socket };
const proxyConfig = this.router.routeReq(fakeReq);
if (!proxyConfig) {
stream.respond({ ':status': 404 });
stream.end('Not Found');
if (this.metricsTracker) this.metricsTracker.incrementFailedRequests();
return;
}
const destination = this.connectionPool.getNextTarget(proxyConfig.destinationIps, proxyConfig.destinationPorts[0]);
const key = `${destination.host}:${destination.port}`;
let session = this.h2Sessions.get(key);
if (!session || session.closed || (session as any).destroyed) {
session = plugins.http2.connect(`http://${destination.host}:${destination.port}`);
this.h2Sessions.set(key, session);
session.on('error', () => this.h2Sessions.delete(key));
session.on('close', () => this.h2Sessions.delete(key));
}
// Build headers for backend HTTP/2 request
const h2Headers: Record<string, any> = {
':method': headers[':method'],
':path': headers[':path'],
':authority': `${destination.host}:${destination.port}`
};
for (const [k, v] of Object.entries(headers)) {
if (!k.startsWith(':') && typeof v === 'string') {
h2Headers[k] = v;
}
}
const h2Stream2 = session.request(h2Headers);
stream.pipe(h2Stream2);
h2Stream2.on('response', (hdrs: any) => {
// Map status and headers to client
const resp: Record<string, any> = { ':status': hdrs[':status'] as number };
for (const [hk, hv] of Object.entries(hdrs)) {
if (!hk.startsWith(':') && hv) resp[hk] = hv;
}
stream.respond(resp);
h2Stream2.pipe(stream);
});
h2Stream2.on('error', (err) => {
stream.respond({ ':status': 502 });
stream.end(`Bad Gateway: ${err.message}`);
if (this.metricsTracker) this.metricsTracker.incrementFailedRequests();
});
return;
}
try {
// Determine host for routing
const authority = headers[':authority'] as string || '';
const host = authority.split(':')[0];
// Fake request object for routing
const fakeReq: any = { headers: { host }, method, url: path, socket: (stream.session as any).socket };
const proxyConfig = this.router.routeReq(fakeReq as any);
if (!proxyConfig) {
stream.respond({ ':status': 404 });
stream.end('Not Found');
if (this.metricsTracker) this.metricsTracker.incrementFailedRequests();
return;
}
// Select backend target
const destination = this.connectionPool.getNextTarget(
proxyConfig.destinationIps,
proxyConfig.destinationPorts[0]
);
// Build headers for HTTP/1 proxy
const outboundHeaders: Record<string,string> = {};
for (const [key, value] of Object.entries(headers)) {
if (typeof key === 'string' && typeof value === 'string' && !key.startsWith(':')) {
outboundHeaders[key] = value;
}
}
if (outboundHeaders.host && (proxyConfig as any).rewriteHostHeader) {
outboundHeaders.host = `${destination.host}:${destination.port}`;
}
// Create HTTP/1 proxy request
const proxyReq = plugins.http.request(
{ hostname: destination.host, port: destination.port, path, method, headers: outboundHeaders },
(proxyRes) => {
// Map status and headers back to HTTP/2
const responseHeaders: Record<string, number|string|string[]> = {};
for (const [k, v] of Object.entries(proxyRes.headers)) {
if (v !== undefined) {
responseHeaders[k] = v as string | string[];
}
}
stream.respond({ ':status': proxyRes.statusCode || 500, ...responseHeaders });
proxyRes.pipe(stream);
stream.on('close', () => proxyReq.destroy());
stream.on('error', () => proxyReq.destroy());
if (this.metricsTracker) stream.on('end', () => this.metricsTracker.incrementRequestsServed());
}
);
proxyReq.on('error', (err) => {
stream.respond({ ':status': 502 });
stream.end(`Bad Gateway: ${err.message}`);
if (this.metricsTracker) this.metricsTracker.incrementFailedRequests();
});
// Pipe client stream to backend
stream.pipe(proxyReq);
} catch (err: any) {
stream.respond({ ':status': 500 });
stream.end('Internal Server Error');
if (this.metricsTracker) this.metricsTracker.incrementFailedRequests();
}
}
}

View File

@ -0,0 +1,226 @@
import * as plugins from '../../plugins.js';
import { type NetworkProxyOptions, type WebSocketWithHeartbeat, type Logger, createLogger, type ReverseProxyConfig } from './models/types.js';
import { ConnectionPool } from './connection-pool.js';
import { ProxyRouter } from '../../http/router/index.js';
/**
* Handles WebSocket connections and proxying
*/
export class WebSocketHandler {
private heartbeatInterval: NodeJS.Timeout | null = null;
private wsServer: plugins.ws.WebSocketServer | null = null;
private logger: Logger;
constructor(
private options: NetworkProxyOptions,
private connectionPool: ConnectionPool,
private router: ProxyRouter
) {
this.logger = createLogger(options.logLevel || 'info');
}
/**
* Initialize WebSocket server on an existing HTTPS server
*/
public initialize(server: plugins.https.Server): void {
// Create WebSocket server
this.wsServer = new plugins.ws.WebSocketServer({
server: server,
clientTracking: true
});
// Handle WebSocket connections
this.wsServer.on('connection', (wsIncoming: WebSocketWithHeartbeat, req: plugins.http.IncomingMessage) => {
this.handleWebSocketConnection(wsIncoming, req);
});
// Start the heartbeat interval
this.startHeartbeat();
this.logger.info('WebSocket handler initialized');
}
/**
* Start the heartbeat interval to check for inactive WebSocket connections
*/
private startHeartbeat(): void {
// Clean up existing interval if any
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
}
// Set up the heartbeat interval (check every 30 seconds)
this.heartbeatInterval = setInterval(() => {
if (!this.wsServer || this.wsServer.clients.size === 0) {
return; // Skip if no active connections
}
this.logger.debug(`WebSocket heartbeat check for ${this.wsServer.clients.size} clients`);
this.wsServer.clients.forEach((ws: plugins.wsDefault) => {
const wsWithHeartbeat = ws as WebSocketWithHeartbeat;
if (wsWithHeartbeat.isAlive === false) {
this.logger.debug('Terminating inactive WebSocket connection');
return wsWithHeartbeat.terminate();
}
wsWithHeartbeat.isAlive = false;
wsWithHeartbeat.ping();
});
}, 30000);
// Make sure the interval doesn't keep the process alive
if (this.heartbeatInterval.unref) {
this.heartbeatInterval.unref();
}
}
/**
* Handle a new WebSocket connection
*/
private handleWebSocketConnection(wsIncoming: WebSocketWithHeartbeat, req: plugins.http.IncomingMessage): void {
try {
// Initialize heartbeat tracking
wsIncoming.isAlive = true;
wsIncoming.lastPong = Date.now();
// Handle pong messages to track liveness
wsIncoming.on('pong', () => {
wsIncoming.isAlive = true;
wsIncoming.lastPong = Date.now();
});
// Find target configuration based on request
const proxyConfig = this.router.routeReq(req);
if (!proxyConfig) {
this.logger.warn(`No proxy configuration for WebSocket host: ${req.headers.host}`);
wsIncoming.close(1008, 'No proxy configuration for this host');
return;
}
// Get destination target using round-robin if multiple targets
const destination = this.connectionPool.getNextTarget(
proxyConfig.destinationIps,
proxyConfig.destinationPorts[0]
);
// Build target URL
const protocol = (req.socket as any).encrypted ? 'wss' : 'ws';
const targetUrl = `${protocol}://${destination.host}:${destination.port}${req.url}`;
this.logger.debug(`WebSocket connection from ${req.socket.remoteAddress} to ${targetUrl}`);
// Create headers for outgoing WebSocket connection
const headers: { [key: string]: string } = {};
// Copy relevant headers from incoming request
for (const [key, value] of Object.entries(req.headers)) {
if (value && typeof value === 'string' &&
key.toLowerCase() !== 'connection' &&
key.toLowerCase() !== 'upgrade' &&
key.toLowerCase() !== 'sec-websocket-key' &&
key.toLowerCase() !== 'sec-websocket-version') {
headers[key] = value;
}
}
// Override host header if needed
if ((proxyConfig as ReverseProxyConfig).rewriteHostHeader) {
headers['host'] = `${destination.host}:${destination.port}`;
}
// Create outgoing WebSocket connection
const wsOutgoing = new plugins.wsDefault(targetUrl, {
headers: headers,
followRedirects: true
});
// Handle connection errors
wsOutgoing.on('error', (err) => {
this.logger.error(`WebSocket target connection error: ${err.message}`);
if (wsIncoming.readyState === wsIncoming.OPEN) {
wsIncoming.close(1011, 'Internal server error');
}
});
// Handle outgoing connection open
wsOutgoing.on('open', () => {
// Forward incoming messages to outgoing connection
wsIncoming.on('message', (data, isBinary) => {
if (wsOutgoing.readyState === wsOutgoing.OPEN) {
wsOutgoing.send(data, { binary: isBinary });
}
});
// Forward outgoing messages to incoming connection
wsOutgoing.on('message', (data, isBinary) => {
if (wsIncoming.readyState === wsIncoming.OPEN) {
wsIncoming.send(data, { binary: isBinary });
}
});
// Handle closing of connections
wsIncoming.on('close', (code, reason) => {
this.logger.debug(`WebSocket client connection closed: ${code} ${reason}`);
if (wsOutgoing.readyState === wsOutgoing.OPEN) {
wsOutgoing.close(code, reason);
}
});
wsOutgoing.on('close', (code, reason) => {
this.logger.debug(`WebSocket target connection closed: ${code} ${reason}`);
if (wsIncoming.readyState === wsIncoming.OPEN) {
wsIncoming.close(code, reason);
}
});
this.logger.debug(`WebSocket connection established: ${req.headers.host} -> ${destination.host}:${destination.port}`);
});
} catch (error) {
this.logger.error(`Error handling WebSocket connection: ${error.message}`);
if (wsIncoming.readyState === wsIncoming.OPEN) {
wsIncoming.close(1011, 'Internal server error');
}
}
}
/**
* Get information about active WebSocket connections
*/
public getConnectionInfo(): { activeConnections: number } {
return {
activeConnections: this.wsServer ? this.wsServer.clients.size : 0
};
}
/**
* Shutdown the WebSocket handler
*/
public shutdown(): void {
// Stop heartbeat interval
if (this.heartbeatInterval) {
clearInterval(this.heartbeatInterval);
this.heartbeatInterval = null;
}
// Close all WebSocket connections
if (this.wsServer) {
this.logger.info(`Closing ${this.wsServer.clients.size} WebSocket connections`);
for (const client of this.wsServer.clients) {
try {
client.terminate();
} catch (error) {
this.logger.error('Error terminating WebSocket client', error);
}
}
// Close the server
this.wsServer.close();
this.wsServer = null;
}
}
}

View File

@ -1,5 +1,5 @@
/**
* NfTablesProxy implementation
*/
// Core NfTablesProxy will be added later:
// export { NfTablesProxy } from './nftables-proxy.js';
export * from './nftables-proxy.js';
export * from './models/index.js';

View File

@ -0,0 +1,30 @@
/**
* Custom error classes for better error handling
*/
export class NftBaseError extends Error {
constructor(message: string) {
super(message);
this.name = 'NftBaseError';
}
}
export class NftValidationError extends NftBaseError {
constructor(message: string) {
super(message);
this.name = 'NftValidationError';
}
}
export class NftExecutionError extends NftBaseError {
constructor(message: string) {
super(message);
this.name = 'NftExecutionError';
}
}
export class NftResourceError extends NftBaseError {
constructor(message: string) {
super(message);
this.name = 'NftResourceError';
}
}

View File

@ -0,0 +1,5 @@
/**
* Export all models
*/
export * from './interfaces.js';
export * from './errors.js';

View File

@ -0,0 +1,94 @@
/**
* Interfaces for NfTablesProxy
*/
/**
* Represents a port range for forwarding
*/
export interface PortRange {
from: number;
to: number;
}
// Legacy interface name for backward compatibility
export type IPortRange = PortRange;
/**
* Settings for NfTablesProxy.
*/
export interface NfTableProxyOptions {
// Basic settings
fromPort: number | PortRange | Array<number | PortRange>; // Support single port, port range, or multiple ports/ranges
toPort: number | PortRange | Array<number | PortRange>;
toHost?: string; // Target host for proxying; defaults to 'localhost'
// Advanced settings
preserveSourceIP?: boolean; // If true, the original source IP is preserved
deleteOnExit?: boolean; // If true, clean up rules before process exit
protocol?: 'tcp' | 'udp' | 'all'; // Protocol to forward, defaults to 'tcp'
enableLogging?: boolean; // Enable detailed logging
ipv6Support?: boolean; // Enable IPv6 support
logFormat?: 'plain' | 'json'; // Format for logs
// Source filtering
allowedSourceIPs?: string[]; // If provided, only these IPs are allowed
bannedSourceIPs?: string[]; // If provided, these IPs are blocked
useIPSets?: boolean; // Use nftables sets for efficient IP management
// Rule management
forceCleanSlate?: boolean; // Clear all NfTablesProxy rules before starting
tableName?: string; // Custom table name (defaults to 'portproxy')
// Connection management
maxRetries?: number; // Maximum number of retries for failed commands
retryDelayMs?: number; // Delay between retries in milliseconds
useAdvancedNAT?: boolean; // Use connection tracking for stateful NAT
// Quality of Service
qos?: {
enabled: boolean;
maxRate?: string; // e.g. "10mbps"
priority?: number; // 1 (highest) to 10 (lowest)
markConnections?: boolean; // Mark connections for easier management
};
// Integration with PortProxy/NetworkProxy
netProxyIntegration?: {
enabled: boolean;
redirectLocalhost?: boolean; // Redirect localhost traffic to NetworkProxy
sslTerminationPort?: number; // Port where NetworkProxy handles SSL termination
};
}
// Legacy interface name for backward compatibility
export type INfTableProxySettings = NfTableProxyOptions;
/**
* Interface for status reporting
*/
export interface NfTablesStatus {
active: boolean;
ruleCount: {
total: number;
added: number;
verified: number;
};
tablesConfigured: { family: string; tableName: string }[];
metrics: {
forwardedConnections?: number;
activeConnections?: number;
bytesForwarded?: {
sent: number;
received: number;
};
};
qosEnabled?: boolean;
ipSetsConfigured?: {
name: string;
elementCount: number;
type: string;
}[];
}
// Legacy interface name for backward compatibility
export type INfTablesStatus = NfTablesStatus;

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,446 @@
import * as plugins from '../../plugins.js';
import type { ConnectionRecord, SmartProxyOptions } from './models/interfaces.js';
import { SecurityManager } from './security-manager.js';
import { TimeoutManager } from './timeout-manager.js';
/**
* Manages connection lifecycle, tracking, and cleanup
*/
export class ConnectionManager {
private connectionRecords: Map<string, ConnectionRecord> = new Map();
private terminationStats: {
incoming: Record<string, number>;
outgoing: Record<string, number>;
} = { incoming: {}, outgoing: {} };
constructor(
private settings: SmartProxyOptions,
private securityManager: SecurityManager,
private timeoutManager: TimeoutManager
) {}
/**
* Generate a unique connection ID
*/
public generateConnectionId(): string {
return Math.random().toString(36).substring(2, 15) +
Math.random().toString(36).substring(2, 15);
}
/**
* Create and track a new connection
*/
public createConnection(socket: plugins.net.Socket): ConnectionRecord {
const connectionId = this.generateConnectionId();
const remoteIP = socket.remoteAddress || '';
const localPort = socket.localPort || 0;
const record: ConnectionRecord = {
id: connectionId,
incoming: socket,
outgoing: null,
incomingStartTime: Date.now(),
lastActivity: Date.now(),
connectionClosed: false,
pendingData: [],
pendingDataSize: 0,
bytesReceived: 0,
bytesSent: 0,
remoteIP,
localPort,
isTLS: false,
tlsHandshakeComplete: false,
hasReceivedInitialData: false,
hasKeepAlive: false,
incomingTerminationReason: null,
outgoingTerminationReason: null,
usingNetworkProxy: false,
isBrowserConnection: false,
domainSwitches: 0
};
this.trackConnection(connectionId, record);
return record;
}
/**
* Track an existing connection
*/
public trackConnection(connectionId: string, record: ConnectionRecord): void {
this.connectionRecords.set(connectionId, record);
this.securityManager.trackConnectionByIP(record.remoteIP, connectionId);
}
/**
* Get a connection by ID
*/
public getConnection(connectionId: string): ConnectionRecord | undefined {
return this.connectionRecords.get(connectionId);
}
/**
* Get all active connections
*/
public getConnections(): Map<string, ConnectionRecord> {
return this.connectionRecords;
}
/**
* Get count of active connections
*/
public getConnectionCount(): number {
return this.connectionRecords.size;
}
/**
* Initiates cleanup once for a connection
*/
public initiateCleanupOnce(record: ConnectionRecord, reason: string = 'normal'): void {
if (this.settings.enableDetailedLogging) {
console.log(`[${record.id}] Connection cleanup initiated for ${record.remoteIP} (${reason})`);
}
if (
record.incomingTerminationReason === null ||
record.incomingTerminationReason === undefined
) {
record.incomingTerminationReason = reason;
this.incrementTerminationStat('incoming', reason);
}
this.cleanupConnection(record, reason);
}
/**
* Clean up a connection record
*/
public cleanupConnection(record: ConnectionRecord, reason: string = 'normal'): void {
if (!record.connectionClosed) {
record.connectionClosed = true;
// Track connection termination
this.securityManager.removeConnectionByIP(record.remoteIP, record.id);
if (record.cleanupTimer) {
clearTimeout(record.cleanupTimer);
record.cleanupTimer = undefined;
}
// Detailed logging data
const duration = Date.now() - record.incomingStartTime;
const bytesReceived = record.bytesReceived;
const bytesSent = record.bytesSent;
// Remove all data handlers to make sure we clean up properly
if (record.incoming) {
try {
// Remove our safe data handler
record.incoming.removeAllListeners('data');
// Reset the handler references
record.renegotiationHandler = undefined;
} catch (err) {
console.log(`[${record.id}] Error removing data handlers: ${err}`);
}
}
// Handle incoming socket
this.cleanupSocket(record, 'incoming', record.incoming);
// Handle outgoing socket
if (record.outgoing) {
this.cleanupSocket(record, 'outgoing', record.outgoing);
}
// Clear pendingData to avoid memory leaks
record.pendingData = [];
record.pendingDataSize = 0;
// Remove the record from the tracking map
this.connectionRecords.delete(record.id);
// 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'}, Keep-Alive: ${record.hasKeepAlive ? 'Yes' : 'No'}` +
`${record.usingNetworkProxy ? ', Using NetworkProxy' : ''}` +
`${record.domainSwitches ? `, Domain switches: ${record.domainSwitches}` : ''}`
);
} else {
console.log(
`[${record.id}] Connection from ${record.remoteIP} terminated (${reason}). Active connections: ${this.connectionRecords.size}`
);
}
}
}
/**
* Helper method to clean up a socket
*/
private cleanupSocket(record: ConnectionRecord, side: 'incoming' | 'outgoing', socket: plugins.net.Socket): void {
try {
if (!socket.destroyed) {
// Try graceful shutdown first, then force destroy after a short timeout
socket.end();
const socketTimeout = setTimeout(() => {
try {
if (!socket.destroyed) {
socket.destroy();
}
} catch (err) {
console.log(`[${record.id}] Error destroying ${side} socket: ${err}`);
}
}, 1000);
// Ensure the timeout doesn't block Node from exiting
if (socketTimeout.unref) {
socketTimeout.unref();
}
}
} catch (err) {
console.log(`[${record.id}] Error closing ${side} socket: ${err}`);
try {
if (!socket.destroyed) {
socket.destroy();
}
} catch (destroyErr) {
console.log(`[${record.id}] Error destroying ${side} socket: ${destroyErr}`);
}
}
}
/**
* Creates a generic error handler for incoming or outgoing sockets
*/
public handleError(side: 'incoming' | 'outgoing', record: ConnectionRecord) {
return (err: Error) => {
const code = (err as any).code;
let reason = 'error';
const now = Date.now();
const connectionDuration = now - record.incomingStartTime;
const lastActivityAge = now - record.lastActivity;
if (code === 'ECONNRESET') {
reason = 'econnreset';
console.log(
`[${record.id}] ECONNRESET on ${side} side from ${record.remoteIP}: ${err.message}. ` +
`Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(lastActivityAge)} ago`
);
} else if (code === 'ETIMEDOUT') {
reason = 'etimedout';
console.log(
`[${record.id}] ETIMEDOUT on ${side} side from ${record.remoteIP}: ${err.message}. ` +
`Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(lastActivityAge)} ago`
);
} else {
console.log(
`[${record.id}] Error on ${side} side from ${record.remoteIP}: ${err.message}. ` +
`Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(lastActivityAge)} ago`
);
}
if (side === 'incoming' && record.incomingTerminationReason === null) {
record.incomingTerminationReason = reason;
this.incrementTerminationStat('incoming', reason);
} else if (side === 'outgoing' && record.outgoingTerminationReason === null) {
record.outgoingTerminationReason = reason;
this.incrementTerminationStat('outgoing', reason);
}
this.initiateCleanupOnce(record, reason);
};
}
/**
* Creates a generic close handler for incoming or outgoing sockets
*/
public handleClose(side: 'incoming' | 'outgoing', record: ConnectionRecord) {
return () => {
if (this.settings.enableDetailedLogging) {
console.log(`[${record.id}] Connection closed on ${side} side from ${record.remoteIP}`);
}
if (side === 'incoming' && record.incomingTerminationReason === null) {
record.incomingTerminationReason = 'normal';
this.incrementTerminationStat('incoming', 'normal');
} else if (side === 'outgoing' && record.outgoingTerminationReason === null) {
record.outgoingTerminationReason = 'normal';
this.incrementTerminationStat('outgoing', 'normal');
// Record the time when outgoing socket closed.
record.outgoingClosedTime = Date.now();
}
this.initiateCleanupOnce(record, 'closed_' + side);
};
}
/**
* Increment termination statistics
*/
public incrementTerminationStat(side: 'incoming' | 'outgoing', reason: string): void {
this.terminationStats[side][reason] = (this.terminationStats[side][reason] || 0) + 1;
}
/**
* Get termination statistics
*/
public getTerminationStats(): { incoming: Record<string, number>; outgoing: Record<string, number> } {
return this.terminationStats;
}
/**
* Check for stalled/inactive connections
*/
public performInactivityCheck(): void {
const now = Date.now();
const connectionIds = [...this.connectionRecords.keys()];
for (const id of connectionIds) {
const record = this.connectionRecords.get(id);
if (!record) continue;
// Skip inactivity check if disabled or for immortal keep-alive connections
if (
this.settings.disableInactivityCheck ||
(record.hasKeepAlive && this.settings.keepAliveTreatment === 'immortal')
) {
continue;
}
const inactivityTime = now - record.lastActivity;
// Use extended timeout for extended-treatment keep-alive connections
let effectiveTimeout = this.settings.inactivityTimeout!;
if (record.hasKeepAlive && this.settings.keepAliveTreatment === 'extended') {
const multiplier = this.settings.keepAliveInactivityMultiplier || 6;
effectiveTimeout = effectiveTimeout * multiplier;
}
if (inactivityTime > effectiveTimeout && !record.connectionClosed) {
// For keep-alive connections, issue a warning first
if (record.hasKeepAlive && !record.inactivityWarningIssued) {
console.log(
`[${id}] Warning: Keep-alive connection from ${record.remoteIP} inactive for ${
plugins.prettyMs(inactivityTime)
}. Will close in 10 minutes if no activity.`
);
// Set warning flag and add grace period
record.inactivityWarningIssued = true;
record.lastActivity = now - (effectiveTimeout - 600000);
// Try to stimulate activity with a probe packet
if (record.outgoing && !record.outgoing.destroyed) {
try {
record.outgoing.write(Buffer.alloc(0));
if (this.settings.enableDetailedLogging) {
console.log(`[${id}] Sent probe packet to test keep-alive connection`);
}
} catch (err) {
console.log(`[${id}] Error sending probe packet: ${err}`);
}
}
} else {
// For non-keep-alive or after warning, close the connection
console.log(
`[${id}] Inactivity check: No activity on connection from ${record.remoteIP} ` +
`for ${plugins.prettyMs(inactivityTime)}.` +
(record.hasKeepAlive ? ' Despite keep-alive being enabled.' : '')
);
this.cleanupConnection(record, 'inactivity');
}
} else if (inactivityTime <= effectiveTimeout && record.inactivityWarningIssued) {
// If activity detected after warning, clear the warning
if (this.settings.enableDetailedLogging) {
console.log(
`[${id}] Connection activity detected after inactivity warning, resetting warning`
);
}
record.inactivityWarningIssued = false;
}
// Parity check: if outgoing socket closed and incoming remains active
if (
record.outgoingClosedTime &&
!record.incoming.destroyed &&
!record.connectionClosed &&
now - record.outgoingClosedTime > 120000
) {
console.log(
`[${id}] Parity check: Incoming socket for ${record.remoteIP} still active ${
plugins.prettyMs(now - record.outgoingClosedTime)
} after outgoing closed.`
);
this.cleanupConnection(record, 'parity_check');
}
}
}
/**
* Clear all connections (for shutdown)
*/
public clearConnections(): void {
// Create a copy of the keys to avoid modification during iteration
const connectionIds = [...this.connectionRecords.keys()];
// First pass: End all connections gracefully
for (const id of connectionIds) {
const record = this.connectionRecords.get(id);
if (record) {
try {
// Clear any timers
if (record.cleanupTimer) {
clearTimeout(record.cleanupTimer);
record.cleanupTimer = undefined;
}
// End sockets gracefully
if (record.incoming && !record.incoming.destroyed) {
record.incoming.end();
}
if (record.outgoing && !record.outgoing.destroyed) {
record.outgoing.end();
}
} catch (err) {
console.log(`Error during graceful connection end for ${id}: ${err}`);
}
}
}
// Short delay to allow graceful ends to process
setTimeout(() => {
// Second pass: Force destroy everything
for (const id of connectionIds) {
const record = this.connectionRecords.get(id);
if (record) {
try {
// Remove all listeners to prevent memory leaks
if (record.incoming) {
record.incoming.removeAllListeners();
if (!record.incoming.destroyed) {
record.incoming.destroy();
}
}
if (record.outgoing) {
record.outgoing.removeAllListeners();
if (!record.outgoing.destroyed) {
record.outgoing.destroy();
}
}
} catch (err) {
console.log(`Error during forced connection destruction for ${id}: ${err}`);
}
}
}
// Clear all maps
this.connectionRecords.clear();
this.terminationStats = { incoming: {}, outgoing: {} };
}, 100);
}
}

View File

@ -0,0 +1,298 @@
import * as plugins from '../../plugins.js';
import type { DomainConfig, SmartProxyOptions } from './models/interfaces.js';
import type { ForwardingType, ForwardConfig } from '../../forwarding/config/forwarding-types.js';
import type { ForwardingHandler } from '../../forwarding/handlers/base-handler.js';
import { ForwardingHandlerFactory } from '../../forwarding/factory/forwarding-factory.js';
/**
* Manages domain configurations and target selection
*/
export class DomainConfigManager {
// Track round-robin indices for domain configs
private domainTargetIndices: Map<DomainConfig, number> = new Map();
// Cache forwarding handlers for each domain config
private forwardingHandlers: Map<DomainConfig, ForwardingHandler> = new Map();
constructor(private settings: SmartProxyOptions) {}
/**
* Updates the domain configurations
*/
public updateDomainConfigs(newDomainConfigs: DomainConfig[]): void {
this.settings.domainConfigs = newDomainConfigs;
// Reset target indices for removed configs
const currentConfigSet = new Set(newDomainConfigs);
for (const [config] of this.domainTargetIndices) {
if (!currentConfigSet.has(config)) {
this.domainTargetIndices.delete(config);
}
}
// Clear handlers for removed configs and create handlers for new configs
const handlersToRemove: DomainConfig[] = [];
for (const [config] of this.forwardingHandlers) {
if (!currentConfigSet.has(config)) {
handlersToRemove.push(config);
}
}
// Remove handlers that are no longer needed
for (const config of handlersToRemove) {
this.forwardingHandlers.delete(config);
}
// Create handlers for new configs
for (const config of newDomainConfigs) {
if (!this.forwardingHandlers.has(config)) {
try {
const handler = this.createForwardingHandler(config);
this.forwardingHandlers.set(config, handler);
} catch (err) {
console.log(`Error creating forwarding handler for domain ${config.domains.join(', ')}: ${err}`);
}
}
}
}
/**
* Get all domain configurations
*/
public getDomainConfigs(): DomainConfig[] {
return this.settings.domainConfigs;
}
/**
* Find domain config matching a server name
*/
public findDomainConfig(serverName: string): DomainConfig | undefined {
if (!serverName) return undefined;
return this.settings.domainConfigs.find((config) =>
config.domains.some((d) => plugins.minimatch(serverName, d))
);
}
/**
* Find domain config for a specific port
*/
public findDomainConfigForPort(port: number): DomainConfig | undefined {
return this.settings.domainConfigs.find(
(domain) => {
const portRanges = domain.forwarding?.advanced?.portRanges;
return portRanges &&
portRanges.length > 0 &&
this.isPortInRanges(port, portRanges);
}
);
}
/**
* Check if a port is within any of the given ranges
*/
public isPortInRanges(port: number, ranges: Array<{ from: number; to: number }>): boolean {
return ranges.some((range) => port >= range.from && port <= range.to);
}
/**
* Get target IP with round-robin support
*/
public getTargetIP(domainConfig: DomainConfig): string {
const targetHosts = Array.isArray(domainConfig.forwarding.target.host)
? domainConfig.forwarding.target.host
: [domainConfig.forwarding.target.host];
if (targetHosts.length > 0) {
const currentIndex = this.domainTargetIndices.get(domainConfig) || 0;
const ip = targetHosts[currentIndex % targetHosts.length];
this.domainTargetIndices.set(domainConfig, currentIndex + 1);
return ip;
}
return this.settings.targetIP || 'localhost';
}
/**
* Get target host with round-robin support (for tests)
* This is just an alias for getTargetIP for easier test compatibility
*/
public getTargetHost(domainConfig: DomainConfig): string {
return this.getTargetIP(domainConfig);
}
/**
* Get target port from domain config
*/
public getTargetPort(domainConfig: DomainConfig, defaultPort: number): number {
return domainConfig.forwarding.target.port || defaultPort;
}
/**
* Checks if a domain should use NetworkProxy
*/
public shouldUseNetworkProxy(domainConfig: DomainConfig): boolean {
const forwardingType = this.getForwardingType(domainConfig);
return forwardingType === 'https-terminate-to-http' ||
forwardingType === 'https-terminate-to-https';
}
/**
* Gets the NetworkProxy port for a domain
*/
public getNetworkProxyPort(domainConfig: DomainConfig): number | undefined {
// First check if we should use NetworkProxy at all
if (!this.shouldUseNetworkProxy(domainConfig)) {
return undefined;
}
return domainConfig.forwarding.advanced?.networkProxyPort || this.settings.networkProxyPort;
}
/**
* Get effective allowed and blocked IPs for a domain
*
* This method combines domain-specific security rules from the forwarding configuration
* with global security defaults when necessary.
*/
public getEffectiveIPRules(domainConfig: DomainConfig): {
allowedIPs: string[],
blockedIPs: string[]
} {
// Start with empty arrays
const allowedIPs: string[] = [];
const blockedIPs: string[] = [];
// Add IPs from forwarding security settings if available
if (domainConfig.forwarding?.security?.allowedIps) {
allowedIPs.push(...domainConfig.forwarding.security.allowedIps);
} else {
// If no allowed IPs are specified in forwarding config and global defaults exist, use them
if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0) {
allowedIPs.push(...this.settings.defaultAllowedIPs);
} else {
// Default to allow all if no specific rules
allowedIPs.push('*');
}
}
// Add blocked IPs from forwarding security settings if available
if (domainConfig.forwarding?.security?.blockedIps) {
blockedIPs.push(...domainConfig.forwarding.security.blockedIps);
}
// Always add global blocked IPs, even if domain has its own rules
// This ensures that global blocks take precedence
if (this.settings.defaultBlockedIPs && this.settings.defaultBlockedIPs.length > 0) {
// Add only unique IPs that aren't already in the list
for (const ip of this.settings.defaultBlockedIPs) {
if (!blockedIPs.includes(ip)) {
blockedIPs.push(ip);
}
}
}
return {
allowedIPs,
blockedIPs
};
}
/**
* Get connection timeout for a domain
*/
public getConnectionTimeout(domainConfig?: DomainConfig): number {
if (domainConfig?.forwarding.advanced?.timeout) {
return domainConfig.forwarding.advanced.timeout;
}
return this.settings.maxConnectionLifetime || 86400000; // 24 hours default
}
/**
* Creates a forwarding handler for a domain configuration
*/
private createForwardingHandler(domainConfig: DomainConfig): ForwardingHandler {
// Create a new handler using the factory
const handler = ForwardingHandlerFactory.createHandler(domainConfig.forwarding);
// Initialize the handler
handler.initialize().catch(err => {
console.log(`Error initializing forwarding handler for ${domainConfig.domains.join(', ')}: ${err}`);
});
return handler;
}
/**
* Gets a forwarding handler for a domain config
* If no handler exists, creates one
*/
public getForwardingHandler(domainConfig: DomainConfig): ForwardingHandler {
// If we already have a handler, return it
if (this.forwardingHandlers.has(domainConfig)) {
return this.forwardingHandlers.get(domainConfig)!;
}
// Otherwise create a new handler
const handler = this.createForwardingHandler(domainConfig);
this.forwardingHandlers.set(domainConfig, handler);
return handler;
}
/**
* Gets the forwarding type for a domain config
*/
public getForwardingType(domainConfig?: DomainConfig): ForwardingType | undefined {
if (!domainConfig?.forwarding) return undefined;
return domainConfig.forwarding.type;
}
/**
* Checks if the forwarding type requires TLS termination
*/
public requiresTlsTermination(domainConfig?: DomainConfig): boolean {
if (!domainConfig) return false;
const forwardingType = this.getForwardingType(domainConfig);
return forwardingType === 'https-terminate-to-http' ||
forwardingType === 'https-terminate-to-https';
}
/**
* Checks if the forwarding type supports HTTP
*/
public supportsHttp(domainConfig?: DomainConfig): boolean {
if (!domainConfig) return false;
const forwardingType = this.getForwardingType(domainConfig);
// HTTP-only always supports HTTP
if (forwardingType === 'http-only') return true;
// For termination types, check the HTTP settings
if (forwardingType === 'https-terminate-to-http' ||
forwardingType === 'https-terminate-to-https') {
// HTTP is supported by default for termination types
return domainConfig.forwarding?.http?.enabled !== false;
}
// HTTPS-passthrough doesn't support HTTP
return false;
}
/**
* Checks if HTTP requests should be redirected to HTTPS
*/
public shouldRedirectToHttps(domainConfig?: DomainConfig): boolean {
if (!domainConfig?.forwarding) return false;
// Only check for redirect if HTTP is enabled
if (this.supportsHttp(domainConfig)) {
return !!domainConfig.forwarding.http?.redirectToHttps;
}
return false;
}
}

View File

@ -4,5 +4,15 @@
// Re-export models
export * from './models/index.js';
// Core SmartProxy will be added later:
// export { SmartProxy } from './smart-proxy.js';
// Export the main SmartProxy class
export { SmartProxy } from './smart-proxy.js';
// Export supporting classes
export { ConnectionManager } from './connection-manager.js';
export { SecurityManager } from './security-manager.js';
export { DomainConfigManager } from './domain-config-manager.js';
export { TimeoutManager } from './timeout-manager.js';
export { TlsManager } from './tls-manager.js';
export { NetworkProxyBridge } from './network-proxy-bridge.js';
export { PortRangeManager } from './port-range-manager.js';
export { ConnectionHandler } from './connection-handler.js';

View File

@ -0,0 +1,371 @@
import * as plugins from '../../plugins.js';
import { NetworkProxy } from '../network-proxy/index.js';
import { Port80Handler } from '../../http/port80/port80-handler.js';
import { Port80HandlerEvents } from '../../core/models/common-types.js';
import { subscribeToPort80Handler } from '../../core/utils/event-utils.js';
import type { CertificateData } from '../../certificate/models/certificate-types.js';
import type { ConnectionRecord, SmartProxyOptions, DomainConfig } from './models/interfaces.js';
/**
* Manages NetworkProxy integration for TLS termination
*/
export class NetworkProxyBridge {
private networkProxy: NetworkProxy | null = null;
private port80Handler: Port80Handler | null = null;
constructor(private settings: SmartProxyOptions) {}
/**
* Set the Port80Handler to use for certificate management
*/
public setPort80Handler(handler: Port80Handler): void {
this.port80Handler = handler;
// Subscribe to certificate events
subscribeToPort80Handler(handler, {
onCertificateIssued: this.handleCertificateEvent.bind(this),
onCertificateRenewed: this.handleCertificateEvent.bind(this)
});
// If NetworkProxy is already initialized, connect it with Port80Handler
if (this.networkProxy) {
this.networkProxy.setExternalPort80Handler(handler);
}
console.log('Port80Handler connected to NetworkProxyBridge');
}
/**
* Initialize NetworkProxy instance
*/
public async initialize(): Promise<void> {
if (!this.networkProxy && this.settings.useNetworkProxy && this.settings.useNetworkProxy.length > 0) {
// Configure NetworkProxy options based on PortProxy settings
const networkProxyOptions: any = {
port: this.settings.networkProxyPort!,
portProxyIntegration: true,
logLevel: this.settings.enableDetailedLogging ? 'debug' : 'info',
useExternalPort80Handler: !!this.port80Handler // Use Port80Handler if available
};
this.networkProxy = new NetworkProxy(networkProxyOptions);
console.log(`Initialized NetworkProxy on port ${this.settings.networkProxyPort}`);
// Connect Port80Handler if available
if (this.port80Handler) {
this.networkProxy.setExternalPort80Handler(this.port80Handler);
}
// Convert and apply domain configurations to NetworkProxy
await this.syncDomainConfigsToNetworkProxy();
}
}
/**
* Handle certificate issuance or renewal events
*/
private handleCertificateEvent(data: CertificateData): void {
if (!this.networkProxy) return;
console.log(`Received certificate for ${data.domain} from Port80Handler, updating NetworkProxy`);
try {
// Find existing config for this domain
const existingConfigs = this.networkProxy.getProxyConfigs()
.filter(config => config.hostName === data.domain);
if (existingConfigs.length > 0) {
// Update existing configs with new certificate
for (const config of existingConfigs) {
config.privateKey = data.privateKey;
config.publicKey = data.certificate;
}
// Apply updated configs
this.networkProxy.updateProxyConfigs(existingConfigs)
.then(() => console.log(`Updated certificate for ${data.domain} in NetworkProxy`))
.catch(err => console.log(`Error updating certificate in NetworkProxy: ${err}`));
} else {
// Create a new config for this domain
console.log(`No existing config found for ${data.domain}, creating new config in NetworkProxy`);
}
} catch (err) {
console.log(`Error handling certificate event: ${err}`);
}
}
/**
* Apply an external (static) certificate into NetworkProxy
*/
public applyExternalCertificate(data: CertificateData): void {
if (!this.networkProxy) {
console.log(`NetworkProxy not initialized: cannot apply external certificate for ${data.domain}`);
return;
}
this.handleCertificateEvent(data);
}
/**
* Get the NetworkProxy instance
*/
public getNetworkProxy(): NetworkProxy | null {
return this.networkProxy;
}
/**
* Get the NetworkProxy port
*/
public getNetworkProxyPort(): number {
return this.networkProxy ? this.networkProxy.getListeningPort() : this.settings.networkProxyPort || 8443;
}
/**
* Start NetworkProxy
*/
public async start(): Promise<void> {
if (this.networkProxy) {
await this.networkProxy.start();
console.log(`NetworkProxy started on port ${this.settings.networkProxyPort}`);
}
}
/**
* Stop NetworkProxy
*/
public async stop(): Promise<void> {
if (this.networkProxy) {
try {
console.log('Stopping NetworkProxy...');
await this.networkProxy.stop();
console.log('NetworkProxy stopped successfully');
} catch (err) {
console.log(`Error stopping NetworkProxy: ${err}`);
}
}
}
/**
* Register domains with Port80Handler
*/
public registerDomainsWithPort80Handler(domains: string[]): void {
if (!this.port80Handler) {
console.log('Cannot register domains - Port80Handler not initialized');
return;
}
for (const domain of domains) {
// Skip wildcards
if (domain.includes('*')) {
console.log(`Skipping wildcard domain for ACME: ${domain}`);
continue;
}
// Register the domain
try {
this.port80Handler.addDomain({
domainName: domain,
sslRedirect: true,
acmeMaintenance: true
});
console.log(`Registered domain with Port80Handler: ${domain}`);
} catch (err) {
console.log(`Error registering domain ${domain} with Port80Handler: ${err}`);
}
}
}
/**
* Forwards a TLS connection to a NetworkProxy for handling
*/
public forwardToNetworkProxy(
connectionId: string,
socket: plugins.net.Socket,
record: ConnectionRecord,
initialData: Buffer,
customProxyPort?: number,
onError?: (reason: string) => void
): void {
// Ensure NetworkProxy is initialized
if (!this.networkProxy) {
console.log(
`[${connectionId}] NetworkProxy not initialized. Cannot forward connection.`
);
if (onError) {
onError('network_proxy_not_initialized');
}
return;
}
// Use the custom port if provided, otherwise use the default NetworkProxy port
const proxyPort = customProxyPort || this.networkProxy.getListeningPort();
const proxyHost = 'localhost'; // Assuming NetworkProxy runs locally
if (this.settings.enableDetailedLogging) {
console.log(
`[${connectionId}] Forwarding TLS connection to NetworkProxy at ${proxyHost}:${proxyPort}`
);
}
// Create a connection to the NetworkProxy
const proxySocket = plugins.net.connect({
host: proxyHost,
port: proxyPort,
});
// Store the outgoing socket in the record
record.outgoing = proxySocket;
record.outgoingStartTime = Date.now();
record.usingNetworkProxy = true;
// Set up error handlers
proxySocket.on('error', (err) => {
console.log(`[${connectionId}] Error connecting to NetworkProxy: ${err.message}`);
if (onError) {
onError('network_proxy_connect_error');
}
});
// Handle connection to NetworkProxy
proxySocket.on('connect', () => {
if (this.settings.enableDetailedLogging) {
console.log(`[${connectionId}] Connected to NetworkProxy at ${proxyHost}:${proxyPort}`);
}
// First send the initial data that contains the TLS ClientHello
proxySocket.write(initialData);
// Now set up bidirectional piping between client and NetworkProxy
socket.pipe(proxySocket);
proxySocket.pipe(socket);
// Update activity on data transfer (caller should handle this)
if (this.settings.enableDetailedLogging) {
console.log(`[${connectionId}] TLS connection successfully forwarded to NetworkProxy`);
}
});
}
/**
* Synchronizes domain configurations to NetworkProxy
*/
public async syncDomainConfigsToNetworkProxy(): Promise<void> {
if (!this.networkProxy) {
console.log('Cannot sync configurations - NetworkProxy not initialized');
return;
}
try {
// Get SSL certificates from assets
// Import fs directly since it's not in plugins
const fs = await import('fs');
let certPair;
try {
certPair = {
key: fs.readFileSync('assets/certs/key.pem', 'utf8'),
cert: fs.readFileSync('assets/certs/cert.pem', 'utf8'),
};
} catch (certError) {
console.log(`Warning: Could not read default certificates: ${certError}`);
console.log(
'Using empty certificate placeholders - ACME will generate proper certificates if enabled'
);
// Use empty placeholders - NetworkProxy will use its internal defaults
// or ACME will generate proper ones if enabled
certPair = {
key: '',
cert: '',
};
}
// Convert domain configs to NetworkProxy configs
const proxyConfigs = this.networkProxy.convertSmartProxyConfigs(
this.settings.domainConfigs,
certPair
);
// Log ACME-eligible domains
const acmeEnabled = !!this.settings.acme?.enabled;
if (acmeEnabled) {
const acmeEligibleDomains = proxyConfigs
.filter((config) => !config.hostName.includes('*')) // Exclude wildcards
.map((config) => config.hostName);
if (acmeEligibleDomains.length > 0) {
console.log(`Domains eligible for ACME certificates: ${acmeEligibleDomains.join(', ')}`);
// Register these domains with Port80Handler if available
if (this.port80Handler) {
this.registerDomainsWithPort80Handler(acmeEligibleDomains);
}
} else {
console.log('No domains eligible for ACME certificates found in configuration');
}
}
// Update NetworkProxy with the converted configs
await this.networkProxy.updateProxyConfigs(proxyConfigs);
console.log(`Successfully synchronized ${proxyConfigs.length} domain configurations to NetworkProxy`);
} catch (err) {
console.log(`Failed to sync configurations: ${err}`);
}
}
/**
* Request a certificate for a specific domain
*/
public async requestCertificate(domain: string): Promise<boolean> {
// Delegate to Port80Handler if available
if (this.port80Handler) {
try {
// Check if the domain is already registered
const cert = this.port80Handler.getCertificate(domain);
if (cert) {
console.log(`Certificate already exists for ${domain}`);
return true;
}
// Register the domain for certificate issuance
this.port80Handler.addDomain({
domainName: domain,
sslRedirect: true,
acmeMaintenance: true
});
console.log(`Domain ${domain} registered for certificate issuance`);
return true;
} catch (err) {
console.log(`Error requesting certificate: ${err}`);
return false;
}
}
// Fall back to NetworkProxy if Port80Handler is not available
if (!this.networkProxy) {
console.log('Cannot request certificate - NetworkProxy not initialized');
return false;
}
if (!this.settings.acme?.enabled) {
console.log('Cannot request certificate - ACME is not enabled');
return false;
}
try {
const result = await this.networkProxy.requestCertificate(domain);
if (result) {
console.log(`Certificate request for ${domain} submitted successfully`);
} else {
console.log(`Certificate request for ${domain} failed`);
}
return result;
} catch (err) {
console.log(`Error requesting certificate: ${err}`);
return false;
}
}
}

View File

@ -0,0 +1,211 @@
import type { SmartProxyOptions } from './models/interfaces.js';
/**
* Manages port ranges and port-based configuration
*/
export class PortRangeManager {
constructor(private settings: SmartProxyOptions) {}
/**
* Get all ports that should be listened on
*/
public getListeningPorts(): Set<number> {
const listeningPorts = new Set<number>();
// Always include the main fromPort
listeningPorts.add(this.settings.fromPort);
// Add ports from global port ranges if defined
if (this.settings.globalPortRanges && this.settings.globalPortRanges.length > 0) {
for (const range of this.settings.globalPortRanges) {
for (let port = range.from; port <= range.to; port++) {
listeningPorts.add(port);
}
}
}
return listeningPorts;
}
/**
* Check if a port should use NetworkProxy for forwarding
*/
public shouldUseNetworkProxy(port: number): boolean {
return !!this.settings.useNetworkProxy && this.settings.useNetworkProxy.includes(port);
}
/**
* Check if port should use global forwarding
*/
public shouldUseGlobalForwarding(port: number): boolean {
return (
!!this.settings.forwardAllGlobalRanges &&
this.isPortInGlobalRanges(port)
);
}
/**
* Check if a port is in global ranges
*/
public isPortInGlobalRanges(port: number): boolean {
return (
this.settings.globalPortRanges &&
this.isPortInRanges(port, this.settings.globalPortRanges)
);
}
/**
* Check if a port falls within the specified ranges
*/
public isPortInRanges(port: number, ranges: Array<{ from: number; to: number }>): boolean {
return ranges.some((range) => port >= range.from && port <= range.to);
}
/**
* Get forwarding port for a specific listening port
* This determines what port to connect to on the target
*/
public getForwardingPort(listeningPort: number): number {
// If using global forwarding, forward to the original port
if (this.settings.forwardAllGlobalRanges && this.isPortInGlobalRanges(listeningPort)) {
return listeningPort;
}
// Otherwise use the configured toPort
return this.settings.toPort;
}
/**
* Find domain-specific port ranges that include a given port
*/
public findDomainPortRange(port: number): {
domainIndex: number,
range: { from: number, to: number }
} | undefined {
for (let i = 0; i < this.settings.domainConfigs.length; i++) {
const domain = this.settings.domainConfigs[i];
// Get port ranges from forwarding.advanced if available
const portRanges = domain.forwarding?.advanced?.portRanges;
if (portRanges && portRanges.length > 0) {
for (const range of portRanges) {
if (port >= range.from && port <= range.to) {
return { domainIndex: i, range };
}
}
}
}
return undefined;
}
/**
* Get a list of all configured ports
* This includes the fromPort, NetworkProxy ports, and ports from all ranges
*/
public getAllConfiguredPorts(): number[] {
const ports = new Set<number>();
// Add main listening port
ports.add(this.settings.fromPort);
// Add NetworkProxy port if configured
if (this.settings.networkProxyPort) {
ports.add(this.settings.networkProxyPort);
}
// Add NetworkProxy ports
if (this.settings.useNetworkProxy) {
for (const port of this.settings.useNetworkProxy) {
ports.add(port);
}
}
// Add global port ranges
if (this.settings.globalPortRanges) {
for (const range of this.settings.globalPortRanges) {
for (let port = range.from; port <= range.to; port++) {
ports.add(port);
}
}
}
// Add domain-specific port ranges
for (const domain of this.settings.domainConfigs) {
// Get port ranges from forwarding.advanced
const portRanges = domain.forwarding?.advanced?.portRanges;
if (portRanges && portRanges.length > 0) {
for (const range of portRanges) {
for (let port = range.from; port <= range.to; port++) {
ports.add(port);
}
}
}
// Add domain-specific NetworkProxy port if configured in forwarding.advanced
const networkProxyPort = domain.forwarding?.advanced?.networkProxyPort;
if (networkProxyPort) {
ports.add(networkProxyPort);
}
}
return Array.from(ports);
}
/**
* Validate port configuration
* Returns array of warning messages
*/
public validateConfiguration(): string[] {
const warnings: string[] = [];
// Check for overlapping port ranges
const portMappings = new Map<number, string[]>();
// Track global port ranges
if (this.settings.globalPortRanges) {
for (const range of this.settings.globalPortRanges) {
for (let port = range.from; port <= range.to; port++) {
if (!portMappings.has(port)) {
portMappings.set(port, []);
}
portMappings.get(port)!.push('Global Port Range');
}
}
}
// Track domain-specific port ranges
for (const domain of this.settings.domainConfigs) {
// Get port ranges from forwarding.advanced
const portRanges = domain.forwarding?.advanced?.portRanges;
if (portRanges && portRanges.length > 0) {
for (const range of portRanges) {
for (let port = range.from; port <= range.to; port++) {
if (!portMappings.has(port)) {
portMappings.set(port, []);
}
portMappings.get(port)!.push(`Domain: ${domain.domains.join(', ')}`);
}
}
}
}
// Check for ports with multiple mappings
for (const [port, mappings] of portMappings.entries()) {
if (mappings.length > 1) {
warnings.push(`Port ${port} has multiple mappings: ${mappings.join(', ')}`);
}
}
// Check if main ports are used elsewhere
if (portMappings.has(this.settings.fromPort) && portMappings.get(this.settings.fromPort)!.length > 0) {
warnings.push(`Main listening port ${this.settings.fromPort} is also used in port ranges`);
}
if (this.settings.networkProxyPort && portMappings.has(this.settings.networkProxyPort)) {
warnings.push(`NetworkProxy port ${this.settings.networkProxyPort} is also used in port ranges`);
}
return warnings;
}
}

View File

@ -0,0 +1,171 @@
import * as plugins from '../../plugins.js';
import type { SmartProxyOptions } from './models/interfaces.js';
/**
* Handles security aspects like IP tracking, rate limiting, and authorization
*/
export class SecurityManager {
private connectionsByIP: Map<string, Set<string>> = new Map();
private connectionRateByIP: Map<string, number[]> = new Map();
constructor(private settings: SmartProxyOptions) {}
/**
* Get connections count by IP
*/
public getConnectionCountByIP(ip: string): number {
return this.connectionsByIP.get(ip)?.size || 0;
}
/**
* Check and update connection rate for an IP
* @returns true if within rate limit, false if exceeding limit
*/
public checkConnectionRate(ip: string): boolean {
const now = Date.now();
const minute = 60 * 1000;
if (!this.connectionRateByIP.has(ip)) {
this.connectionRateByIP.set(ip, [now]);
return true;
}
// Get timestamps and filter out entries older than 1 minute
const timestamps = this.connectionRateByIP.get(ip)!.filter((time) => now - time < minute);
timestamps.push(now);
this.connectionRateByIP.set(ip, timestamps);
// Check if rate exceeds limit
return timestamps.length <= this.settings.connectionRateLimitPerMinute!;
}
/**
* Track connection by IP
*/
public trackConnectionByIP(ip: string, connectionId: string): void {
if (!this.connectionsByIP.has(ip)) {
this.connectionsByIP.set(ip, new Set());
}
this.connectionsByIP.get(ip)!.add(connectionId);
}
/**
* Remove connection tracking for an IP
*/
public removeConnectionByIP(ip: string, connectionId: string): void {
if (this.connectionsByIP.has(ip)) {
const connections = this.connectionsByIP.get(ip)!;
connections.delete(connectionId);
if (connections.size === 0) {
this.connectionsByIP.delete(ip);
}
}
}
/**
* Check if an IP is authorized using forwarding security rules
*
* This method is used to determine if an IP is allowed to connect, based on security
* rules configured in the forwarding configuration. The allowed and blocked IPs are
* typically derived from domain.forwarding.security.allowedIps and blockedIps through
* DomainConfigManager.getEffectiveIPRules().
*
* @param ip - The IP address to check
* @param allowedIPs - Array of allowed IP patterns from forwarding.security.allowedIps
* @param blockedIPs - Array of blocked IP patterns from forwarding.security.blockedIps
* @returns true if IP is authorized, false if blocked
*/
public isIPAuthorized(ip: string, allowedIPs: string[], blockedIPs: string[] = []): boolean {
// Skip IP validation if allowedIPs is empty
if (!ip || (allowedIPs.length === 0 && blockedIPs.length === 0)) {
return true;
}
// First check if IP is blocked - blocked IPs take precedence
if (blockedIPs.length > 0 && this.isGlobIPMatch(ip, blockedIPs)) {
return false;
}
// Then check if IP is allowed
return this.isGlobIPMatch(ip, allowedIPs);
}
/**
* Check if the IP matches any of the glob patterns from security configuration
*
* This method checks IP addresses against glob patterns and handles IPv4/IPv6 normalization.
* It's used to implement IP filtering based on the forwarding.security configuration.
*
* @param ip - The IP address to check
* @param patterns - Array of glob patterns from forwarding.security.allowedIps or blockedIps
* @returns true if IP matches any pattern, false otherwise
*/
private isGlobIPMatch(ip: string, patterns: string[]): boolean {
if (!ip || !patterns || patterns.length === 0) return false;
// Handle IPv4/IPv6 normalization for proper matching
const normalizeIP = (ip: string): string[] => {
if (!ip) return [];
// Handle IPv4-mapped IPv6 addresses (::ffff:127.0.0.1)
if (ip.startsWith('::ffff:')) {
const ipv4 = ip.slice(7);
return [ip, ipv4];
}
// Handle IPv4 addresses by also checking IPv4-mapped form
if (/^\d{1,3}(\.\d{1,3}){3}$/.test(ip)) {
return [ip, `::ffff:${ip}`];
}
return [ip];
};
// Normalize the IP being checked
const normalizedIPVariants = normalizeIP(ip);
if (normalizedIPVariants.length === 0) return false;
// Normalize the pattern IPs for consistent comparison
const expandedPatterns = patterns.flatMap(normalizeIP);
// Check for any match between normalized IP variants and patterns
return normalizedIPVariants.some((ipVariant) =>
expandedPatterns.some((pattern) => plugins.minimatch(ipVariant, pattern))
);
}
/**
* Check if IP should be allowed considering connection rate and max connections
* @returns Object with result and reason
*/
public validateIP(ip: string): { allowed: boolean; reason?: string } {
// Check connection count limit
if (
this.settings.maxConnectionsPerIP &&
this.getConnectionCountByIP(ip) >= this.settings.maxConnectionsPerIP
) {
return {
allowed: false,
reason: `Maximum connections per IP (${this.settings.maxConnectionsPerIP}) exceeded`
};
}
// Check connection rate limit
if (
this.settings.connectionRateLimitPerMinute &&
!this.checkConnectionRate(ip)
) {
return {
allowed: false,
reason: `Connection rate limit (${this.settings.connectionRateLimitPerMinute}/min) exceeded`
};
}
return { allowed: true };
}
/**
* Clears all IP tracking data (for shutdown)
*/
public clearIPTracking(): void {
this.connectionsByIP.clear();
this.connectionRateByIP.clear();
}
}

View File

@ -0,0 +1,656 @@
import * as plugins from '../../plugins.js';
// Importing from the new structure
import { ConnectionManager } from './connection-manager.js';
import { SecurityManager } from './security-manager.js';
import { DomainConfigManager } from './domain-config-manager.js';
import { TlsManager } from './tls-manager.js';
import { NetworkProxyBridge } from './network-proxy-bridge.js';
import { TimeoutManager } from './timeout-manager.js';
import { PortRangeManager } from './port-range-manager.js';
import { ConnectionHandler } from './connection-handler.js';
// External dependencies from migrated modules
import { Port80Handler } from '../../http/port80/port80-handler.js';
import { CertProvisioner } from '../../certificate/providers/cert-provisioner.js';
import type { CertificateData } from '../../certificate/models/certificate-types.js';
import { buildPort80Handler } from '../../certificate/acme/acme-factory.js';
import type { ForwardingType } from '../../forwarding/config/forwarding-types.js';
import { createPort80HandlerOptions } from '../../common/port80-adapter.js';
// Import types from models
import type { SmartProxyOptions, DomainConfig } from './models/interfaces.js';
// Provide backward compatibility types
export type { SmartProxyOptions as IPortProxySettings, DomainConfig as IDomainConfig };
/**
* SmartProxy - Main class that coordinates all components
*/
export class SmartProxy extends plugins.EventEmitter {
private netServers: plugins.net.Server[] = [];
private connectionLogger: NodeJS.Timeout | null = null;
private isShuttingDown: boolean = false;
// Component managers
private connectionManager: ConnectionManager;
private securityManager: SecurityManager;
public domainConfigManager: DomainConfigManager;
private tlsManager: TlsManager;
private networkProxyBridge: NetworkProxyBridge;
private timeoutManager: TimeoutManager;
private portRangeManager: PortRangeManager;
private connectionHandler: ConnectionHandler;
// Port80Handler for ACME certificate management
private port80Handler: Port80Handler | null = null;
// CertProvisioner for unified certificate workflows
private certProvisioner?: CertProvisioner;
constructor(settingsArg: SmartProxyOptions) {
super();
// Set reasonable defaults for all settings
this.settings = {
...settingsArg,
targetIP: settingsArg.targetIP || 'localhost',
initialDataTimeout: settingsArg.initialDataTimeout || 120000,
socketTimeout: settingsArg.socketTimeout || 3600000,
inactivityCheckInterval: settingsArg.inactivityCheckInterval || 60000,
maxConnectionLifetime: settingsArg.maxConnectionLifetime || 86400000,
inactivityTimeout: settingsArg.inactivityTimeout || 14400000,
gracefulShutdownTimeout: settingsArg.gracefulShutdownTimeout || 30000,
noDelay: settingsArg.noDelay !== undefined ? settingsArg.noDelay : true,
keepAlive: settingsArg.keepAlive !== undefined ? settingsArg.keepAlive : true,
keepAliveInitialDelay: settingsArg.keepAliveInitialDelay || 10000,
maxPendingDataSize: settingsArg.maxPendingDataSize || 10 * 1024 * 1024,
disableInactivityCheck: settingsArg.disableInactivityCheck || false,
enableKeepAliveProbes:
settingsArg.enableKeepAliveProbes !== undefined ? settingsArg.enableKeepAliveProbes : true,
enableDetailedLogging: settingsArg.enableDetailedLogging || false,
enableTlsDebugLogging: settingsArg.enableTlsDebugLogging || false,
enableRandomizedTimeouts: settingsArg.enableRandomizedTimeouts || false,
allowSessionTicket:
settingsArg.allowSessionTicket !== undefined ? settingsArg.allowSessionTicket : true,
maxConnectionsPerIP: settingsArg.maxConnectionsPerIP || 100,
connectionRateLimitPerMinute: settingsArg.connectionRateLimitPerMinute || 300,
keepAliveTreatment: settingsArg.keepAliveTreatment || 'extended',
keepAliveInactivityMultiplier: settingsArg.keepAliveInactivityMultiplier || 6,
extendedKeepAliveLifetime: settingsArg.extendedKeepAliveLifetime || 7 * 24 * 60 * 60 * 1000,
networkProxyPort: settingsArg.networkProxyPort || 8443,
acme: settingsArg.acme || {},
globalPortRanges: settingsArg.globalPortRanges || [],
};
// Set default ACME options if not provided
if (!this.settings.acme || Object.keys(this.settings.acme).length === 0) {
this.settings.acme = {
enabled: false,
port: 80,
accountEmail: 'admin@example.com',
useProduction: false,
renewThresholdDays: 30,
autoRenew: true,
certificateStore: './certs',
skipConfiguredCerts: false,
httpsRedirectPort: this.settings.fromPort,
renewCheckIntervalHours: 24,
domainForwards: []
};
}
// Initialize component managers
this.timeoutManager = new TimeoutManager(this.settings);
this.securityManager = new SecurityManager(this.settings);
this.connectionManager = new ConnectionManager(
this.settings,
this.securityManager,
this.timeoutManager
);
this.domainConfigManager = new DomainConfigManager(this.settings);
this.tlsManager = new TlsManager(this.settings);
this.networkProxyBridge = new NetworkProxyBridge(this.settings);
this.portRangeManager = new PortRangeManager(this.settings);
// Initialize connection handler
this.connectionHandler = new ConnectionHandler(
this.settings,
this.connectionManager,
this.securityManager,
this.domainConfigManager,
this.tlsManager,
this.networkProxyBridge,
this.timeoutManager,
this.portRangeManager
);
}
/**
* The settings for the port proxy
*/
public settings: SmartProxyOptions;
/**
* Initialize the Port80Handler for ACME certificate management
*/
private async initializePort80Handler(): Promise<void> {
const config = this.settings.acme!;
if (!config.enabled) {
console.log('ACME is disabled in configuration');
return;
}
try {
// Build and start the Port80Handler
this.port80Handler = buildPort80Handler({
...config,
httpsRedirectPort: config.httpsRedirectPort || this.settings.fromPort
});
// Share Port80Handler with NetworkProxyBridge before start
this.networkProxyBridge.setPort80Handler(this.port80Handler);
await this.port80Handler.start();
console.log(`Port80Handler started on port ${config.port}`);
} catch (err) {
console.log(`Error initializing Port80Handler: ${err}`);
}
}
/**
* Start the proxy server
*/
public async start() {
// Don't start if already shutting down
if (this.isShuttingDown) {
console.log("Cannot start SmartProxy while it's shutting down");
return;
}
// Process domain configs
// Note: ensureForwardingConfig is no longer needed since forwarding is now required
// Initialize domain config manager with the processed configs
this.domainConfigManager.updateDomainConfigs(this.settings.domainConfigs);
// Initialize Port80Handler if enabled
await this.initializePort80Handler();
// Initialize CertProvisioner for unified certificate workflows
if (this.port80Handler) {
const acme = this.settings.acme!;
// Convert domain forwards to use the new forwarding system if possible
const domainForwards = acme.domainForwards?.map(f => {
// If the domain has a forwarding config in domainConfigs, use that
const domainConfig = this.settings.domainConfigs.find(
dc => dc.domains.some(d => d === f.domain)
);
if (domainConfig?.forwarding) {
return {
domain: f.domain,
forwardConfig: f.forwardConfig,
acmeForwardConfig: f.acmeForwardConfig,
sslRedirect: f.sslRedirect || domainConfig.forwarding.http?.redirectToHttps || false
};
}
// Otherwise use the existing configuration
return {
domain: f.domain,
forwardConfig: f.forwardConfig,
acmeForwardConfig: f.acmeForwardConfig,
sslRedirect: f.sslRedirect || false
};
}) || [];
this.certProvisioner = new CertProvisioner(
this.settings.domainConfigs,
this.port80Handler,
this.networkProxyBridge,
this.settings.certProvisionFunction,
acme.renewThresholdDays!,
acme.renewCheckIntervalHours!,
acme.autoRenew!,
domainForwards
);
this.certProvisioner.on('certificate', (certData) => {
this.emit('certificate', {
domain: certData.domain,
publicKey: certData.certificate,
privateKey: certData.privateKey,
expiryDate: certData.expiryDate,
source: certData.source,
isRenewal: certData.isRenewal
});
});
await this.certProvisioner.start();
console.log('CertProvisioner started');
}
// Initialize and start NetworkProxy if needed
if (
this.settings.useNetworkProxy &&
this.settings.useNetworkProxy.length > 0
) {
await this.networkProxyBridge.initialize();
await this.networkProxyBridge.start();
}
// Validate port configuration
const configWarnings = this.portRangeManager.validateConfiguration();
if (configWarnings.length > 0) {
console.log("Port configuration warnings:");
for (const warning of configWarnings) {
console.log(` - ${warning}`);
}
}
// Get listening ports from PortRangeManager
const listeningPorts = this.portRangeManager.getListeningPorts();
// Create servers for each port
for (const port of listeningPorts) {
const server = plugins.net.createServer((socket) => {
// Check if shutting down
if (this.isShuttingDown) {
socket.end();
socket.destroy();
return;
}
// Delegate to connection handler
this.connectionHandler.handleConnection(socket);
}).on('error', (err: Error) => {
console.log(`Server Error on port ${port}: ${err.message}`);
});
server.listen(port, () => {
const isNetworkProxyPort = this.settings.useNetworkProxy?.includes(port);
console.log(
`SmartProxy -> OK: Now listening on port ${port}${
this.settings.sniEnabled && !isNetworkProxyPort ? ' (SNI passthrough enabled)' : ''
}${isNetworkProxyPort ? ' (NetworkProxy forwarding enabled)' : ''}`
);
});
this.netServers.push(server);
}
// Set up periodic connection logging and inactivity checks
this.connectionLogger = setInterval(() => {
// Immediately return if shutting down
if (this.isShuttingDown) return;
// Perform inactivity check
this.connectionManager.performInactivityCheck();
// Log connection statistics
const now = Date.now();
let maxIncoming = 0;
let maxOutgoing = 0;
let tlsConnections = 0;
let nonTlsConnections = 0;
let completedTlsHandshakes = 0;
let pendingTlsHandshakes = 0;
let keepAliveConnections = 0;
let networkProxyConnections = 0;
// Get connection records for analysis
const connectionRecords = this.connectionManager.getConnections();
// Analyze active connections
for (const record of connectionRecords.values()) {
// Track connection stats
if (record.isTLS) {
tlsConnections++;
if (record.tlsHandshakeComplete) {
completedTlsHandshakes++;
} else {
pendingTlsHandshakes++;
}
} else {
nonTlsConnections++;
}
if (record.hasKeepAlive) {
keepAliveConnections++;
}
if (record.usingNetworkProxy) {
networkProxyConnections++;
}
maxIncoming = Math.max(maxIncoming, now - record.incomingStartTime);
if (record.outgoingStartTime) {
maxOutgoing = Math.max(maxOutgoing, now - record.outgoingStartTime);
}
}
// Get termination stats
const terminationStats = this.connectionManager.getTerminationStats();
// Log detailed stats
console.log(
`Active connections: ${connectionRecords.size}. ` +
`Types: TLS=${tlsConnections} (Completed=${completedTlsHandshakes}, Pending=${pendingTlsHandshakes}), ` +
`Non-TLS=${nonTlsConnections}, KeepAlive=${keepAliveConnections}, NetworkProxy=${networkProxyConnections}. ` +
`Longest running: IN=${plugins.prettyMs(maxIncoming)}, OUT=${plugins.prettyMs(maxOutgoing)}. ` +
`Termination stats: ${JSON.stringify({
IN: terminationStats.incoming,
OUT: terminationStats.outgoing,
})}`
);
}, this.settings.inactivityCheckInterval || 60000);
// Make sure the interval doesn't keep the process alive
if (this.connectionLogger.unref) {
this.connectionLogger.unref();
}
}
/**
* Stop the proxy server
*/
public async stop() {
console.log('SmartProxy shutting down...');
this.isShuttingDown = true;
// Stop CertProvisioner if active
if (this.certProvisioner) {
await this.certProvisioner.stop();
console.log('CertProvisioner stopped');
}
// Stop the Port80Handler if running
if (this.port80Handler) {
try {
await this.port80Handler.stop();
console.log('Port80Handler stopped');
this.port80Handler = null;
} catch (err) {
console.log(`Error stopping Port80Handler: ${err}`);
}
}
// Stop accepting new connections
const closeServerPromises: Promise<void>[] = this.netServers.map(
(server) =>
new Promise<void>((resolve) => {
if (!server.listening) {
resolve();
return;
}
server.close((err) => {
if (err) {
console.log(`Error closing server: ${err.message}`);
}
resolve();
});
})
);
// Stop the connection logger
if (this.connectionLogger) {
clearInterval(this.connectionLogger);
this.connectionLogger = null;
}
// Wait for servers to close
await Promise.all(closeServerPromises);
console.log('All servers closed. Cleaning up active connections...');
// Clean up all active connections
this.connectionManager.clearConnections();
// Stop NetworkProxy
await this.networkProxyBridge.stop();
// Clear all servers
this.netServers = [];
console.log('SmartProxy shutdown complete.');
}
/**
* Updates the domain configurations for the proxy
*/
public async updateDomainConfigs(newDomainConfigs: DomainConfig[]): Promise<void> {
console.log(`Updating domain configurations (${newDomainConfigs.length} configs)`);
// Update domain configs in DomainConfigManager
this.domainConfigManager.updateDomainConfigs(newDomainConfigs);
// If NetworkProxy is initialized, resync the configurations
if (this.networkProxyBridge.getNetworkProxy()) {
await this.networkProxyBridge.syncDomainConfigsToNetworkProxy();
}
// If Port80Handler is running, provision certificates based on forwarding type
if (this.port80Handler && this.settings.acme?.enabled) {
for (const domainConfig of newDomainConfigs) {
// Skip certificate provisioning for http-only or passthrough configs that don't need certs
const forwardingType = domainConfig.forwarding.type;
const needsCertificate =
forwardingType === 'https-terminate-to-http' ||
forwardingType === 'https-terminate-to-https';
// Skip certificate provisioning if ACME is explicitly disabled for this domain
const acmeDisabled = domainConfig.forwarding.acme?.enabled === false;
if (!needsCertificate || acmeDisabled) {
if (this.settings.enableDetailedLogging) {
console.log(`Skipping certificate provisioning for ${domainConfig.domains.join(', ')} (${forwardingType})`);
}
continue;
}
for (const domain of domainConfig.domains) {
const isWildcard = domain.includes('*');
let provision: string | plugins.tsclass.network.ICert = 'http01';
// Check for ACME forwarding configuration in the domain
const forwardAcmeChallenges = domainConfig.forwarding.acme?.forwardChallenges;
if (this.settings.certProvisionFunction) {
try {
provision = await this.settings.certProvisionFunction(domain);
} catch (err) {
console.log(`certProvider error for ${domain}: ${err}`);
}
} else if (isWildcard) {
console.warn(`Skipping wildcard domain without certProvisionFunction: ${domain}`);
continue;
}
if (provision === 'http01') {
if (isWildcard) {
console.warn(`Skipping HTTP-01 for wildcard domain: ${domain}`);
continue;
}
// Create Port80Handler options from the forwarding configuration
const port80Config = createPort80HandlerOptions(domain, domainConfig.forwarding);
this.port80Handler.addDomain(port80Config);
console.log(`Registered domain ${domain} with Port80Handler for HTTP-01`);
} else {
// Static certificate (e.g., DNS-01 provisioned) supports wildcards
const certObj = provision as plugins.tsclass.network.ICert;
const certData: CertificateData = {
domain: certObj.domainName,
certificate: certObj.publicKey,
privateKey: certObj.privateKey,
expiryDate: new Date(certObj.validUntil)
};
this.networkProxyBridge.applyExternalCertificate(certData);
console.log(`Applied static certificate for ${domain} from certProvider`);
}
}
}
console.log('Provisioned certificates for new domains');
}
}
/**
* Request a certificate for a specific domain
*/
public async requestCertificate(domain: string): Promise<boolean> {
// Validate domain format
if (!this.isValidDomain(domain)) {
console.log(`Invalid domain format: ${domain}`);
return false;
}
// Use Port80Handler if available
if (this.port80Handler) {
try {
// Check if we already have a certificate
const cert = this.port80Handler.getCertificate(domain);
if (cert) {
console.log(`Certificate already exists for ${domain}, valid until ${cert.expiryDate.toISOString()}`);
return true;
}
// Register domain for certificate issuance
this.port80Handler.addDomain({
domainName: domain,
sslRedirect: true,
acmeMaintenance: true
});
console.log(`Domain ${domain} registered for certificate issuance`);
return true;
} catch (err) {
console.log(`Error registering domain with Port80Handler: ${err}`);
return false;
}
}
// Fall back to NetworkProxyBridge
return this.networkProxyBridge.requestCertificate(domain);
}
/**
* Validates if a domain name is valid for certificate issuance
*/
private isValidDomain(domain: string): boolean {
// Very basic domain validation
if (!domain || domain.length === 0) {
return false;
}
// Check for wildcard domains (they can't get ACME certs)
if (domain.includes('*')) {
console.log(`Wildcard domains like "${domain}" are not supported for ACME certificates`);
return false;
}
// Check if domain has at least one dot and no invalid characters
const validDomainRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
if (!validDomainRegex.test(domain)) {
console.log(`Domain "${domain}" has invalid format`);
return false;
}
return true;
}
/**
* Get statistics about current connections
*/
public getStatistics(): any {
const connectionRecords = this.connectionManager.getConnections();
const terminationStats = this.connectionManager.getTerminationStats();
let tlsConnections = 0;
let nonTlsConnections = 0;
let keepAliveConnections = 0;
let networkProxyConnections = 0;
// Analyze active connections
for (const record of connectionRecords.values()) {
if (record.isTLS) tlsConnections++;
else nonTlsConnections++;
if (record.hasKeepAlive) keepAliveConnections++;
if (record.usingNetworkProxy) networkProxyConnections++;
}
return {
activeConnections: connectionRecords.size,
tlsConnections,
nonTlsConnections,
keepAliveConnections,
networkProxyConnections,
terminationStats,
acmeEnabled: !!this.port80Handler,
port80HandlerPort: this.port80Handler ? this.settings.acme?.port : null
};
}
/**
* Get a list of eligible domains for ACME certificates
*/
public getEligibleDomainsForCertificates(): string[] {
// Collect all non-wildcard domains from domain configs
const domains: string[] = [];
for (const config of this.settings.domainConfigs) {
// Skip domains that can't be used with ACME
const eligibleDomains = config.domains.filter(domain =>
!domain.includes('*') && this.isValidDomain(domain)
);
domains.push(...eligibleDomains);
}
return domains;
}
/**
* Get status of certificates managed by Port80Handler
*/
public getCertificateStatus(): any {
if (!this.port80Handler) {
return {
enabled: false,
message: 'Port80Handler is not enabled'
};
}
// Get eligible domains
const eligibleDomains = this.getEligibleDomainsForCertificates();
const certificateStatus: Record<string, any> = {};
// Check each domain
for (const domain of eligibleDomains) {
const cert = this.port80Handler.getCertificate(domain);
if (cert) {
const now = new Date();
const expiryDate = cert.expiryDate;
const daysRemaining = Math.floor((expiryDate.getTime() - now.getTime()) / (24 * 60 * 60 * 1000));
certificateStatus[domain] = {
status: 'valid',
expiryDate: expiryDate.toISOString(),
daysRemaining,
renewalNeeded: daysRemaining <= (this.settings.acme?.renewThresholdDays ?? 0)
};
} else {
certificateStatus[domain] = {
status: 'missing',
message: 'No certificate found'
};
}
}
const acme = this.settings.acme!;
return {
enabled: true,
port: acme.port!,
useProduction: acme.useProduction!,
autoRenew: acme.autoRenew!,
certificates: certificateStatus
};
}
}

View File

@ -0,0 +1,190 @@
import type { ConnectionRecord, SmartProxyOptions } from './models/interfaces.js';
/**
* Manages timeouts and inactivity tracking for connections
*/
export class TimeoutManager {
constructor(private settings: SmartProxyOptions) {}
/**
* Ensure timeout values don't exceed Node.js max safe integer
*/
public ensureSafeTimeout(timeout: number): number {
const MAX_SAFE_TIMEOUT = 2147483647; // Maximum safe value (2^31 - 1)
return Math.min(Math.floor(timeout), MAX_SAFE_TIMEOUT);
}
/**
* Generate a slightly randomized timeout to prevent thundering herd
*/
public randomizeTimeout(baseTimeout: number, variationPercent: number = 5): number {
const safeBaseTimeout = this.ensureSafeTimeout(baseTimeout);
const variation = safeBaseTimeout * (variationPercent / 100);
return this.ensureSafeTimeout(
safeBaseTimeout + Math.floor(Math.random() * variation * 2) - variation
);
}
/**
* Update connection activity timestamp
*/
public updateActivity(record: ConnectionRecord): void {
record.lastActivity = Date.now();
// Clear any inactivity warning
if (record.inactivityWarningIssued) {
record.inactivityWarningIssued = false;
}
}
/**
* Calculate effective inactivity timeout based on connection type
*/
public getEffectiveInactivityTimeout(record: ConnectionRecord): number {
let effectiveTimeout = this.settings.inactivityTimeout || 14400000; // 4 hours default
// For immortal keep-alive connections, use an extremely long timeout
if (record.hasKeepAlive && this.settings.keepAliveTreatment === 'immortal') {
return Number.MAX_SAFE_INTEGER;
}
// For extended keep-alive connections, apply multiplier
if (record.hasKeepAlive && this.settings.keepAliveTreatment === 'extended') {
const multiplier = this.settings.keepAliveInactivityMultiplier || 6;
effectiveTimeout = effectiveTimeout * multiplier;
}
return this.ensureSafeTimeout(effectiveTimeout);
}
/**
* Calculate effective max lifetime based on connection type
*/
public getEffectiveMaxLifetime(record: ConnectionRecord): number {
// Use domain-specific timeout from forwarding.advanced if available
const baseTimeout = record.domainConfig?.forwarding?.advanced?.timeout ||
this.settings.maxConnectionLifetime ||
86400000; // 24 hours default
// For immortal keep-alive connections, use an extremely long lifetime
if (record.hasKeepAlive && this.settings.keepAliveTreatment === 'immortal') {
return Number.MAX_SAFE_INTEGER;
}
// For extended keep-alive connections, use the extended lifetime setting
if (record.hasKeepAlive && this.settings.keepAliveTreatment === 'extended') {
return this.ensureSafeTimeout(
this.settings.extendedKeepAliveLifetime || 7 * 24 * 60 * 60 * 1000 // 7 days default
);
}
// Apply randomization if enabled
if (this.settings.enableRandomizedTimeouts) {
return this.randomizeTimeout(baseTimeout);
}
return this.ensureSafeTimeout(baseTimeout);
}
/**
* Setup connection timeout
* @returns The cleanup timer
*/
public setupConnectionTimeout(
record: ConnectionRecord,
onTimeout: (record: ConnectionRecord, reason: string) => void
): NodeJS.Timeout {
// Clear any existing timer
if (record.cleanupTimer) {
clearTimeout(record.cleanupTimer);
}
// Calculate effective timeout
const effectiveLifetime = this.getEffectiveMaxLifetime(record);
// Set up the timeout
const timer = setTimeout(() => {
// Call the provided callback
onTimeout(record, 'connection_timeout');
}, effectiveLifetime);
// Make sure timeout doesn't keep the process alive
if (timer.unref) {
timer.unref();
}
return timer;
}
/**
* Check for inactivity on a connection
* @returns Object with check results
*/
public checkInactivity(record: ConnectionRecord): {
isInactive: boolean;
shouldWarn: boolean;
inactivityTime: number;
effectiveTimeout: number;
} {
// Skip for connections with inactivity check disabled
if (this.settings.disableInactivityCheck) {
return {
isInactive: false,
shouldWarn: false,
inactivityTime: 0,
effectiveTimeout: 0
};
}
// Skip for immortal keep-alive connections
if (record.hasKeepAlive && this.settings.keepAliveTreatment === 'immortal') {
return {
isInactive: false,
shouldWarn: false,
inactivityTime: 0,
effectiveTimeout: 0
};
}
const now = Date.now();
const inactivityTime = now - record.lastActivity;
const effectiveTimeout = this.getEffectiveInactivityTimeout(record);
// Check if inactive
const isInactive = inactivityTime > effectiveTimeout;
// For keep-alive connections, we should warn first
const shouldWarn = record.hasKeepAlive &&
isInactive &&
!record.inactivityWarningIssued;
return {
isInactive,
shouldWarn,
inactivityTime,
effectiveTimeout
};
}
/**
* Apply socket timeout settings
*/
public applySocketTimeouts(record: ConnectionRecord): void {
// Skip for immortal keep-alive connections
if (record.hasKeepAlive && this.settings.keepAliveTreatment === 'immortal') {
// Disable timeouts completely for immortal connections
record.incoming.setTimeout(0);
if (record.outgoing) {
record.outgoing.setTimeout(0);
}
return;
}
// Apply normal timeouts
const timeout = this.ensureSafeTimeout(this.settings.socketTimeout || 3600000); // 1 hour default
record.incoming.setTimeout(timeout);
if (record.outgoing) {
record.outgoing.setTimeout(timeout);
}
}
}

View File

@ -0,0 +1,206 @@
import * as plugins from '../../plugins.js';
import type { SmartProxyOptions } from './models/interfaces.js';
import { SniHandler } from '../../tls/sni/sni-handler.js';
/**
* Interface for connection information used for SNI extraction
*/
interface IConnectionInfo {
sourceIp: string;
sourcePort: number;
destIp: string;
destPort: number;
}
/**
* Manages TLS-related operations including SNI extraction and validation
*/
export class TlsManager {
constructor(private settings: SmartProxyOptions) {}
/**
* Check if a data chunk appears to be a TLS handshake
*/
public isTlsHandshake(chunk: Buffer): boolean {
return SniHandler.isTlsHandshake(chunk);
}
/**
* Check if a data chunk appears to be a TLS ClientHello
*/
public isClientHello(chunk: Buffer): boolean {
return SniHandler.isClientHello(chunk);
}
/**
* Extract Server Name Indication (SNI) from TLS handshake
*/
public extractSNI(
chunk: Buffer,
connInfo: IConnectionInfo,
previousDomain?: string
): string | undefined {
// Use the SniHandler to process the TLS packet
return SniHandler.processTlsPacket(
chunk,
connInfo,
this.settings.enableTlsDebugLogging || false,
previousDomain
);
}
/**
* Handle session resumption attempts
*/
public handleSessionResumption(
chunk: Buffer,
connectionId: string,
hasSNI: boolean
): { shouldBlock: boolean; reason?: string } {
// Skip if session tickets are allowed
if (this.settings.allowSessionTicket !== false) {
return { shouldBlock: false };
}
// Check for session resumption attempt
const resumptionInfo = SniHandler.hasSessionResumption(
chunk,
this.settings.enableTlsDebugLogging || false
);
// If this is a resumption attempt without SNI, block it
if (resumptionInfo.isResumption && !hasSNI && !resumptionInfo.hasSNI) {
if (this.settings.enableTlsDebugLogging) {
console.log(
`[${connectionId}] Session resumption detected without SNI and allowSessionTicket=false. ` +
`Terminating connection to force new TLS handshake.`
);
}
return {
shouldBlock: true,
reason: 'session_ticket_blocked'
};
}
return { shouldBlock: false };
}
/**
* Check for SNI mismatch during renegotiation
*/
public checkRenegotiationSNI(
chunk: Buffer,
connInfo: IConnectionInfo,
expectedDomain: string,
connectionId: string
): { hasMismatch: boolean; extractedSNI?: string } {
// Only process if this looks like a TLS ClientHello
if (!this.isClientHello(chunk)) {
return { hasMismatch: false };
}
try {
// Extract SNI with renegotiation support
const newSNI = SniHandler.extractSNIWithResumptionSupport(
chunk,
connInfo,
this.settings.enableTlsDebugLogging || false
);
// Skip if no SNI was found
if (!newSNI) return { hasMismatch: false };
// Check for SNI mismatch
if (newSNI !== expectedDomain) {
if (this.settings.enableTlsDebugLogging) {
console.log(
`[${connectionId}] Renegotiation with different SNI: ${expectedDomain} -> ${newSNI}. ` +
`Terminating connection - SNI domain switching is not allowed.`
);
}
return { hasMismatch: true, extractedSNI: newSNI };
} else if (this.settings.enableTlsDebugLogging) {
console.log(
`[${connectionId}] Renegotiation detected with same SNI: ${newSNI}. Allowing.`
);
}
} catch (err) {
console.log(
`[${connectionId}] Error processing ClientHello: ${err}. Allowing connection to continue.`
);
}
return { hasMismatch: false };
}
/**
* Create a renegotiation handler function for a connection
*/
public createRenegotiationHandler(
connectionId: string,
lockedDomain: string,
connInfo: IConnectionInfo,
onMismatch: (connectionId: string, reason: string) => void
): (chunk: Buffer) => void {
return (chunk: Buffer) => {
const result = this.checkRenegotiationSNI(chunk, connInfo, lockedDomain, connectionId);
if (result.hasMismatch) {
onMismatch(connectionId, 'sni_mismatch');
}
};
}
/**
* Analyze TLS connection for browser fingerprinting
* This helps identify browser vs non-browser connections
*/
public analyzeClientHello(chunk: Buffer): {
isBrowserConnection: boolean;
isRenewal: boolean;
hasSNI: boolean;
} {
// Default result
const result = {
isBrowserConnection: false,
isRenewal: false,
hasSNI: false
};
try {
// Check if it's a ClientHello
if (!this.isClientHello(chunk)) {
return result;
}
// Check for session resumption
const resumptionInfo = SniHandler.hasSessionResumption(
chunk,
this.settings.enableTlsDebugLogging || false
);
// Extract SNI
const sni = SniHandler.extractSNI(
chunk,
this.settings.enableTlsDebugLogging || false
);
// Update result
result.isRenewal = resumptionInfo.isResumption;
result.hasSNI = !!sni;
// Browsers typically:
// 1. Send SNI extension
// 2. Have a variety of extensions (ALPN, etc.)
// 3. Use standard cipher suites
// ...more complex heuristics could be implemented here
// Simple heuristic: presence of SNI suggests browser
result.isBrowserConnection = !!sni;
return result;
} catch (err) {
console.log(`Error analyzing ClientHello: ${err}`);
return result;
}
}
}