Compare commits
12 Commits
Author | SHA1 | Date | |
---|---|---|---|
0d0a1c740b | |||
9bd87b8437 | |||
0e281b3243 | |||
a14b7802c4 | |||
138900ca8b | |||
cb6c2503e2 | |||
f3fd903231 | |||
0e605d9a9d | |||
1718a3b2f2 | |||
568f77e65b | |||
e212dacbf3 | |||
eea8942670 |
41
changelog.md
41
changelog.md
@ -1,5 +1,46 @@
|
|||||||
# Changelog
|
# Changelog
|
||||||
|
|
||||||
|
## 2025-03-07 - 3.28.4 - fix(router)
|
||||||
|
Improve path pattern matching and hostname prioritization in router
|
||||||
|
|
||||||
|
- Enhance path pattern matching capabilities
|
||||||
|
- Ensure hostname prioritization in routing logic
|
||||||
|
|
||||||
|
## 2025-03-06 - 3.28.3 - fix(PortProxy)
|
||||||
|
Ensure timeout values are within Node.js safe limits
|
||||||
|
|
||||||
|
- Implemented `ensureSafeTimeout` to keep timeout values under the maximum safe integer for Node.js.
|
||||||
|
- Updated timeout configurations in `PortProxy` to include safety checks.
|
||||||
|
|
||||||
|
## 2025-03-06 - 3.28.2 - fix(portproxy)
|
||||||
|
Adjust safe timeout defaults in PortProxy to prevent overflow issues.
|
||||||
|
|
||||||
|
- Adjusted socketTimeout to maximum safe limit (~24.8 days) for PortProxy.
|
||||||
|
- Adjusted maxConnectionLifetime to maximum safe limit (~24.8 days) for PortProxy.
|
||||||
|
- Ensured enhanced default timeout settings in PortProxy.
|
||||||
|
|
||||||
|
## 2025-03-06 - 3.28.1 - fix(PortProxy)
|
||||||
|
Improved code formatting and readability in PortProxy class by adjusting spacing and comments.
|
||||||
|
|
||||||
|
- Adjusted comment and spacing for better code readability.
|
||||||
|
- No functional changes made in the PortProxy class.
|
||||||
|
|
||||||
|
## 2025-03-06 - 3.28.0 - feat(router)
|
||||||
|
Add detailed routing tests and refactor ProxyRouter for improved path matching
|
||||||
|
|
||||||
|
- Implemented a comprehensive test suite for the ProxyRouter class to ensure accurate routing based on hostnames and path patterns.
|
||||||
|
- Refactored the ProxyRouter to enhance path matching logic with improvements in wildcard and parameter handling.
|
||||||
|
- Improved logging capabilities within the ProxyRouter for enhanced debugging and info level insights.
|
||||||
|
- Optimized the data structures for storing and accessing proxy configurations to reduce overhead in routing operations.
|
||||||
|
|
||||||
|
## 2025-03-06 - 3.27.0 - feat(AcmeCertManager)
|
||||||
|
Introduce AcmeCertManager for enhanced ACME certificate management
|
||||||
|
|
||||||
|
- Refactored the existing Port80Handler to AcmeCertManager.
|
||||||
|
- Added event-driven certificate management with CertManagerEvents.
|
||||||
|
- Introduced options for configuration such as renew thresholds and production mode.
|
||||||
|
- Implemented certificate renewal checks and logging improvements.
|
||||||
|
|
||||||
## 2025-03-05 - 3.26.0 - feat(readme)
|
## 2025-03-05 - 3.26.0 - feat(readme)
|
||||||
Updated README with enhanced TLS handling, connection management, and troubleshooting sections.
|
Updated README with enhanced TLS handling, connection management, and troubleshooting sections.
|
||||||
|
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@push.rocks/smartproxy",
|
"name": "@push.rocks/smartproxy",
|
||||||
"version": "3.26.0",
|
"version": "3.28.4",
|
||||||
"private": false,
|
"private": false,
|
||||||
"description": "A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.",
|
"description": "A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.",
|
||||||
"main": "dist_ts/index.js",
|
"main": "dist_ts/index.js",
|
||||||
|
346
test/test.router.ts
Normal file
346
test/test.router.ts
Normal file
@ -0,0 +1,346 @@
|
|||||||
|
import { expect, tap } from '@push.rocks/tapbundle';
|
||||||
|
import * as tsclass from '@tsclass/tsclass';
|
||||||
|
import * as http from 'http';
|
||||||
|
import { ProxyRouter, type IRouterResult } from '../ts/classes.router.js';
|
||||||
|
|
||||||
|
// Test proxies and configurations
|
||||||
|
let router: ProxyRouter;
|
||||||
|
|
||||||
|
// Sample hostname for testing
|
||||||
|
const TEST_DOMAIN = 'example.com';
|
||||||
|
const TEST_SUBDOMAIN = 'api.example.com';
|
||||||
|
const TEST_WILDCARD = '*.example.com';
|
||||||
|
|
||||||
|
// Helper: Creates a mock HTTP request for testing
|
||||||
|
function createMockRequest(host: string, url: string = '/'): http.IncomingMessage {
|
||||||
|
const req = {
|
||||||
|
headers: { host },
|
||||||
|
url,
|
||||||
|
socket: {
|
||||||
|
remoteAddress: '127.0.0.1'
|
||||||
|
}
|
||||||
|
} as any;
|
||||||
|
return req;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helper: Creates a test proxy configuration
|
||||||
|
function createProxyConfig(
|
||||||
|
hostname: string,
|
||||||
|
destinationIp: string = '10.0.0.1',
|
||||||
|
destinationPort: number = 8080
|
||||||
|
): tsclass.network.IReverseProxyConfig {
|
||||||
|
return {
|
||||||
|
hostName: hostname,
|
||||||
|
destinationIp,
|
||||||
|
destinationPort: destinationPort.toString(), // Convert to string for IReverseProxyConfig
|
||||||
|
publicKey: 'mock-cert',
|
||||||
|
privateKey: 'mock-key'
|
||||||
|
} as tsclass.network.IReverseProxyConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
// SETUP: Create a ProxyRouter instance
|
||||||
|
tap.test('setup proxy router test environment', async () => {
|
||||||
|
router = new ProxyRouter();
|
||||||
|
|
||||||
|
// Initialize with empty config
|
||||||
|
router.setNewProxyConfigs([]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test basic routing by hostname
|
||||||
|
tap.test('should route requests by hostname', async () => {
|
||||||
|
const config = createProxyConfig(TEST_DOMAIN);
|
||||||
|
router.setNewProxyConfigs([config]);
|
||||||
|
|
||||||
|
const req = createMockRequest(TEST_DOMAIN);
|
||||||
|
const result = router.routeReq(req);
|
||||||
|
|
||||||
|
expect(result).toBeTruthy();
|
||||||
|
expect(result).toEqual(config);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test handling of hostname with port number
|
||||||
|
tap.test('should handle hostname with port number', async () => {
|
||||||
|
const config = createProxyConfig(TEST_DOMAIN);
|
||||||
|
router.setNewProxyConfigs([config]);
|
||||||
|
|
||||||
|
const req = createMockRequest(`${TEST_DOMAIN}:443`);
|
||||||
|
const result = router.routeReq(req);
|
||||||
|
|
||||||
|
expect(result).toBeTruthy();
|
||||||
|
expect(result).toEqual(config);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test case-insensitive hostname matching
|
||||||
|
tap.test('should perform case-insensitive hostname matching', async () => {
|
||||||
|
const config = createProxyConfig(TEST_DOMAIN.toLowerCase());
|
||||||
|
router.setNewProxyConfigs([config]);
|
||||||
|
|
||||||
|
const req = createMockRequest(TEST_DOMAIN.toUpperCase());
|
||||||
|
const result = router.routeReq(req);
|
||||||
|
|
||||||
|
expect(result).toBeTruthy();
|
||||||
|
expect(result).toEqual(config);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test handling of unmatched hostnames
|
||||||
|
tap.test('should return undefined for unmatched hostnames', async () => {
|
||||||
|
const config = createProxyConfig(TEST_DOMAIN);
|
||||||
|
router.setNewProxyConfigs([config]);
|
||||||
|
|
||||||
|
const req = createMockRequest('unknown.domain.com');
|
||||||
|
const result = router.routeReq(req);
|
||||||
|
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test adding path patterns
|
||||||
|
tap.test('should match requests using path patterns', async () => {
|
||||||
|
const config = createProxyConfig(TEST_DOMAIN);
|
||||||
|
router.setNewProxyConfigs([config]);
|
||||||
|
|
||||||
|
// Add a path pattern to the config
|
||||||
|
router.setPathPattern(config, '/api/users');
|
||||||
|
|
||||||
|
// Test that path matches
|
||||||
|
const req1 = createMockRequest(TEST_DOMAIN, '/api/users');
|
||||||
|
const result1 = router.routeReqWithDetails(req1);
|
||||||
|
|
||||||
|
expect(result1).toBeTruthy();
|
||||||
|
expect(result1.config).toEqual(config);
|
||||||
|
expect(result1.pathMatch).toEqual('/api/users');
|
||||||
|
|
||||||
|
// Test that non-matching path doesn't match
|
||||||
|
const req2 = createMockRequest(TEST_DOMAIN, '/web/users');
|
||||||
|
const result2 = router.routeReqWithDetails(req2);
|
||||||
|
|
||||||
|
expect(result2).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test handling wildcard patterns
|
||||||
|
tap.test('should support wildcard path patterns', async () => {
|
||||||
|
const config = createProxyConfig(TEST_DOMAIN);
|
||||||
|
router.setNewProxyConfigs([config]);
|
||||||
|
|
||||||
|
router.setPathPattern(config, '/api/*');
|
||||||
|
|
||||||
|
// Test with path that matches the wildcard pattern
|
||||||
|
const req = createMockRequest(TEST_DOMAIN, '/api/users/123');
|
||||||
|
const result = router.routeReqWithDetails(req);
|
||||||
|
|
||||||
|
expect(result).toBeTruthy();
|
||||||
|
expect(result.config).toEqual(config);
|
||||||
|
expect(result.pathMatch).toEqual('/api');
|
||||||
|
|
||||||
|
// Print the actual value to diagnose issues
|
||||||
|
console.log('Path remainder value:', result.pathRemainder);
|
||||||
|
expect(result.pathRemainder).toBeTruthy();
|
||||||
|
expect(result.pathRemainder).toEqual('/users/123');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test extracting path parameters
|
||||||
|
tap.test('should extract path parameters from URL', async () => {
|
||||||
|
const config = createProxyConfig(TEST_DOMAIN);
|
||||||
|
router.setNewProxyConfigs([config]);
|
||||||
|
|
||||||
|
router.setPathPattern(config, '/users/:id/profile');
|
||||||
|
|
||||||
|
const req = createMockRequest(TEST_DOMAIN, '/users/123/profile');
|
||||||
|
const result = router.routeReqWithDetails(req);
|
||||||
|
|
||||||
|
expect(result).toBeTruthy();
|
||||||
|
expect(result.config).toEqual(config);
|
||||||
|
expect(result.pathParams).toBeTruthy();
|
||||||
|
expect(result.pathParams.id).toEqual('123');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test multiple configs for same hostname with different paths
|
||||||
|
tap.test('should support multiple configs for same hostname with different paths', async () => {
|
||||||
|
const apiConfig = createProxyConfig(TEST_DOMAIN, '10.0.0.1', 8001);
|
||||||
|
const webConfig = createProxyConfig(TEST_DOMAIN, '10.0.0.2', 8002);
|
||||||
|
|
||||||
|
// Add both configs
|
||||||
|
router.setNewProxyConfigs([apiConfig, webConfig]);
|
||||||
|
|
||||||
|
// Set different path patterns
|
||||||
|
router.setPathPattern(apiConfig, '/api');
|
||||||
|
router.setPathPattern(webConfig, '/web');
|
||||||
|
|
||||||
|
// Test API path routes to API config
|
||||||
|
const apiReq = createMockRequest(TEST_DOMAIN, '/api/users');
|
||||||
|
const apiResult = router.routeReq(apiReq);
|
||||||
|
|
||||||
|
expect(apiResult).toEqual(apiConfig);
|
||||||
|
|
||||||
|
// Test web path routes to web config
|
||||||
|
const webReq = createMockRequest(TEST_DOMAIN, '/web/dashboard');
|
||||||
|
const webResult = router.routeReq(webReq);
|
||||||
|
|
||||||
|
expect(webResult).toEqual(webConfig);
|
||||||
|
|
||||||
|
// Test unknown path returns undefined
|
||||||
|
const unknownReq = createMockRequest(TEST_DOMAIN, '/unknown');
|
||||||
|
const unknownResult = router.routeReq(unknownReq);
|
||||||
|
|
||||||
|
expect(unknownResult).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test wildcard subdomains
|
||||||
|
tap.test('should match wildcard subdomains', async () => {
|
||||||
|
const wildcardConfig = createProxyConfig(TEST_WILDCARD);
|
||||||
|
router.setNewProxyConfigs([wildcardConfig]);
|
||||||
|
|
||||||
|
// Test that subdomain.example.com matches *.example.com
|
||||||
|
const req = createMockRequest('subdomain.example.com');
|
||||||
|
const result = router.routeReq(req);
|
||||||
|
|
||||||
|
expect(result).toBeTruthy();
|
||||||
|
expect(result).toEqual(wildcardConfig);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test default configuration fallback
|
||||||
|
tap.test('should fall back to default configuration', async () => {
|
||||||
|
const defaultConfig = createProxyConfig('*');
|
||||||
|
const specificConfig = createProxyConfig(TEST_DOMAIN);
|
||||||
|
|
||||||
|
router.setNewProxyConfigs([defaultConfig, specificConfig]);
|
||||||
|
|
||||||
|
// Test specific domain routes to specific config
|
||||||
|
const specificReq = createMockRequest(TEST_DOMAIN);
|
||||||
|
const specificResult = router.routeReq(specificReq);
|
||||||
|
|
||||||
|
expect(specificResult).toEqual(specificConfig);
|
||||||
|
|
||||||
|
// Test unknown domain falls back to default config
|
||||||
|
const unknownReq = createMockRequest('unknown.com');
|
||||||
|
const unknownResult = router.routeReq(unknownReq);
|
||||||
|
|
||||||
|
expect(unknownResult).toEqual(defaultConfig);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test priority between exact and wildcard matches
|
||||||
|
tap.test('should prioritize exact hostname over wildcard', async () => {
|
||||||
|
const wildcardConfig = createProxyConfig(TEST_WILDCARD);
|
||||||
|
const exactConfig = createProxyConfig(TEST_SUBDOMAIN);
|
||||||
|
|
||||||
|
router.setNewProxyConfigs([wildcardConfig, exactConfig]);
|
||||||
|
|
||||||
|
// Test that exact match takes priority
|
||||||
|
const req = createMockRequest(TEST_SUBDOMAIN);
|
||||||
|
const result = router.routeReq(req);
|
||||||
|
|
||||||
|
expect(result).toEqual(exactConfig);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test adding and removing configurations
|
||||||
|
tap.test('should manage configurations correctly', async () => {
|
||||||
|
router.setNewProxyConfigs([]);
|
||||||
|
|
||||||
|
// Add a config
|
||||||
|
const config = createProxyConfig(TEST_DOMAIN);
|
||||||
|
router.addProxyConfig(config);
|
||||||
|
|
||||||
|
// Verify routing works
|
||||||
|
const req = createMockRequest(TEST_DOMAIN);
|
||||||
|
let result = router.routeReq(req);
|
||||||
|
|
||||||
|
expect(result).toEqual(config);
|
||||||
|
|
||||||
|
// Remove the config and verify it no longer routes
|
||||||
|
const removed = router.removeProxyConfig(TEST_DOMAIN);
|
||||||
|
expect(removed).toBeTrue();
|
||||||
|
|
||||||
|
result = router.routeReq(req);
|
||||||
|
expect(result).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test path pattern specificity
|
||||||
|
tap.test('should prioritize more specific path patterns', async () => {
|
||||||
|
const genericConfig = createProxyConfig(TEST_DOMAIN, '10.0.0.1', 8001);
|
||||||
|
const specificConfig = createProxyConfig(TEST_DOMAIN, '10.0.0.2', 8002);
|
||||||
|
|
||||||
|
router.setNewProxyConfigs([genericConfig, specificConfig]);
|
||||||
|
|
||||||
|
router.setPathPattern(genericConfig, '/api/*');
|
||||||
|
router.setPathPattern(specificConfig, '/api/users');
|
||||||
|
|
||||||
|
// The more specific '/api/users' should match before the '/api/*' wildcard
|
||||||
|
const req = createMockRequest(TEST_DOMAIN, '/api/users');
|
||||||
|
const result = router.routeReq(req);
|
||||||
|
|
||||||
|
expect(result).toEqual(specificConfig);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test getHostnames method
|
||||||
|
tap.test('should retrieve all configured hostnames', async () => {
|
||||||
|
router.setNewProxyConfigs([
|
||||||
|
createProxyConfig(TEST_DOMAIN),
|
||||||
|
createProxyConfig(TEST_SUBDOMAIN)
|
||||||
|
]);
|
||||||
|
|
||||||
|
const hostnames = router.getHostnames();
|
||||||
|
|
||||||
|
expect(hostnames.length).toEqual(2);
|
||||||
|
expect(hostnames).toContain(TEST_DOMAIN.toLowerCase());
|
||||||
|
expect(hostnames).toContain(TEST_SUBDOMAIN.toLowerCase());
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test handling missing host header
|
||||||
|
tap.test('should handle missing host header', async () => {
|
||||||
|
const defaultConfig = createProxyConfig('*');
|
||||||
|
router.setNewProxyConfigs([defaultConfig]);
|
||||||
|
|
||||||
|
const req = createMockRequest('');
|
||||||
|
req.headers.host = undefined;
|
||||||
|
|
||||||
|
const result = router.routeReq(req);
|
||||||
|
|
||||||
|
expect(result).toEqual(defaultConfig);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test complex path parameters
|
||||||
|
tap.test('should handle complex path parameters', async () => {
|
||||||
|
const config = createProxyConfig(TEST_DOMAIN);
|
||||||
|
router.setNewProxyConfigs([config]);
|
||||||
|
|
||||||
|
router.setPathPattern(config, '/api/:version/users/:userId/posts/:postId');
|
||||||
|
|
||||||
|
const req = createMockRequest(TEST_DOMAIN, '/api/v1/users/123/posts/456');
|
||||||
|
const result = router.routeReqWithDetails(req);
|
||||||
|
|
||||||
|
expect(result).toBeTruthy();
|
||||||
|
expect(result.config).toEqual(config);
|
||||||
|
expect(result.pathParams).toBeTruthy();
|
||||||
|
expect(result.pathParams.version).toEqual('v1');
|
||||||
|
expect(result.pathParams.userId).toEqual('123');
|
||||||
|
expect(result.pathParams.postId).toEqual('456');
|
||||||
|
});
|
||||||
|
|
||||||
|
// Performance test
|
||||||
|
tap.test('should handle many configurations efficiently', async () => {
|
||||||
|
const configs = [];
|
||||||
|
|
||||||
|
// Create many configs with different hostnames
|
||||||
|
for (let i = 0; i < 100; i++) {
|
||||||
|
configs.push(createProxyConfig(`host-${i}.example.com`));
|
||||||
|
}
|
||||||
|
|
||||||
|
router.setNewProxyConfigs(configs);
|
||||||
|
|
||||||
|
// Test middle of the list to avoid best/worst case
|
||||||
|
const req = createMockRequest('host-50.example.com');
|
||||||
|
const result = router.routeReq(req);
|
||||||
|
|
||||||
|
expect(result).toEqual(configs[50]);
|
||||||
|
});
|
||||||
|
|
||||||
|
// Test cleanup
|
||||||
|
tap.test('cleanup proxy router test environment', async () => {
|
||||||
|
// Clear all configurations
|
||||||
|
router.setNewProxyConfigs([]);
|
||||||
|
|
||||||
|
// Verify empty state
|
||||||
|
expect(router.getHostnames().length).toEqual(0);
|
||||||
|
expect(router.getProxyConfigs().length).toEqual(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
export default tap.start();
|
@ -3,6 +3,6 @@
|
|||||||
*/
|
*/
|
||||||
export const commitinfo = {
|
export const commitinfo = {
|
||||||
name: '@push.rocks/smartproxy',
|
name: '@push.rocks/smartproxy',
|
||||||
version: '3.26.0',
|
version: '3.28.4',
|
||||||
description: 'A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.'
|
description: 'A powerful proxy package that effectively handles high traffic, with features such as SSL/TLS support, port proxying, WebSocket handling, and dynamic routing with authentication options.'
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,8 @@
|
|||||||
import * as http from 'http';
|
import * as plugins from './plugins.js';
|
||||||
import * as acme from 'acme-client';
|
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Represents a domain certificate with various status information
|
||||||
|
*/
|
||||||
interface IDomainCertificate {
|
interface IDomainCertificate {
|
||||||
certObtained: boolean;
|
certObtained: boolean;
|
||||||
obtainingInProgress: boolean;
|
obtainingInProgress: boolean;
|
||||||
@ -8,27 +10,147 @@ interface IDomainCertificate {
|
|||||||
privateKey?: string;
|
privateKey?: string;
|
||||||
challengeToken?: string;
|
challengeToken?: string;
|
||||||
challengeKeyAuthorization?: string;
|
challengeKeyAuthorization?: string;
|
||||||
|
expiryDate?: Date;
|
||||||
|
lastRenewalAttempt?: Date;
|
||||||
}
|
}
|
||||||
|
|
||||||
export class Port80Handler {
|
/**
|
||||||
private domainCertificates: Map<string, IDomainCertificate>;
|
* Configuration options for the ACME Certificate Manager
|
||||||
private server: http.Server;
|
*/
|
||||||
private acmeClient: acme.Client | null = null;
|
interface IAcmeCertManagerOptions {
|
||||||
private accountKey: string | null = null;
|
port?: number;
|
||||||
|
contactEmail?: string;
|
||||||
|
useProduction?: boolean;
|
||||||
|
renewThresholdDays?: number;
|
||||||
|
httpsRedirectPort?: number;
|
||||||
|
renewCheckIntervalHours?: number;
|
||||||
|
}
|
||||||
|
|
||||||
constructor() {
|
/**
|
||||||
|
* Certificate data that can be emitted via events or set from outside
|
||||||
|
*/
|
||||||
|
interface ICertificateData {
|
||||||
|
domain: string;
|
||||||
|
certificate: string;
|
||||||
|
privateKey: string;
|
||||||
|
expiryDate: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Events emitted by the ACME Certificate Manager
|
||||||
|
*/
|
||||||
|
export enum CertManagerEvents {
|
||||||
|
CERTIFICATE_ISSUED = 'certificate-issued',
|
||||||
|
CERTIFICATE_RENEWED = 'certificate-renewed',
|
||||||
|
CERTIFICATE_FAILED = 'certificate-failed',
|
||||||
|
CERTIFICATE_EXPIRING = 'certificate-expiring',
|
||||||
|
MANAGER_STARTED = 'manager-started',
|
||||||
|
MANAGER_STOPPED = 'manager-stopped',
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Improved ACME Certificate Manager with event emission and external certificate management
|
||||||
|
*/
|
||||||
|
export class AcmeCertManager extends plugins.EventEmitter {
|
||||||
|
private domainCertificates: Map<string, IDomainCertificate>;
|
||||||
|
private server: plugins.http.Server | null = null;
|
||||||
|
private acmeClient: plugins.acme.Client | null = null;
|
||||||
|
private accountKey: string | null = null;
|
||||||
|
private renewalTimer: NodeJS.Timeout | null = null;
|
||||||
|
private isShuttingDown: boolean = false;
|
||||||
|
private options: Required<IAcmeCertManagerOptions>;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Creates a new ACME Certificate Manager
|
||||||
|
* @param options Configuration options
|
||||||
|
*/
|
||||||
|
constructor(options: IAcmeCertManagerOptions = {}) {
|
||||||
|
super();
|
||||||
this.domainCertificates = new Map<string, IDomainCertificate>();
|
this.domainCertificates = new Map<string, IDomainCertificate>();
|
||||||
|
|
||||||
// Create and start an HTTP server on port 80.
|
// Default options
|
||||||
this.server = http.createServer((req, res) => this.handleRequest(req, res));
|
this.options = {
|
||||||
this.server.listen(80, () => {
|
port: options.port ?? 80,
|
||||||
console.log('Port80Handler is listening on port 80');
|
contactEmail: options.contactEmail ?? 'admin@example.com',
|
||||||
|
useProduction: options.useProduction ?? false, // Safer default: staging
|
||||||
|
renewThresholdDays: options.renewThresholdDays ?? 30,
|
||||||
|
httpsRedirectPort: options.httpsRedirectPort ?? 443,
|
||||||
|
renewCheckIntervalHours: options.renewCheckIntervalHours ?? 24,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts the HTTP server for ACME challenges
|
||||||
|
*/
|
||||||
|
public async start(): Promise<void> {
|
||||||
|
if (this.server) {
|
||||||
|
throw new Error('Server is already running');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (this.isShuttingDown) {
|
||||||
|
throw new Error('Server is shutting down');
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
try {
|
||||||
|
this.server = plugins.http.createServer((req, res) => this.handleRequest(req, res));
|
||||||
|
|
||||||
|
this.server.on('error', (error: NodeJS.ErrnoException) => {
|
||||||
|
if (error.code === 'EACCES') {
|
||||||
|
reject(new Error(`Permission denied to bind to port ${this.options.port}. Try running with elevated privileges or use a port > 1024.`));
|
||||||
|
} else if (error.code === 'EADDRINUSE') {
|
||||||
|
reject(new Error(`Port ${this.options.port} is already in use.`));
|
||||||
|
} else {
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
this.server.listen(this.options.port, () => {
|
||||||
|
console.log(`AcmeCertManager is listening on port ${this.options.port}`);
|
||||||
|
this.startRenewalTimer();
|
||||||
|
this.emit(CertManagerEvents.MANAGER_STARTED, this.options.port);
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
reject(error);
|
||||||
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Adds a domain to be managed.
|
* Stops the HTTP server and renewal timer
|
||||||
* @param domain The domain to add.
|
*/
|
||||||
|
public async stop(): Promise<void> {
|
||||||
|
if (!this.server) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
this.isShuttingDown = true;
|
||||||
|
|
||||||
|
// Stop the renewal timer
|
||||||
|
if (this.renewalTimer) {
|
||||||
|
clearInterval(this.renewalTimer);
|
||||||
|
this.renewalTimer = null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return new Promise<void>((resolve) => {
|
||||||
|
if (this.server) {
|
||||||
|
this.server.close(() => {
|
||||||
|
this.server = null;
|
||||||
|
this.isShuttingDown = false;
|
||||||
|
this.emit(CertManagerEvents.MANAGER_STOPPED);
|
||||||
|
resolve();
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
this.isShuttingDown = false;
|
||||||
|
resolve();
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a domain to be managed for certificates
|
||||||
|
* @param domain The domain to add
|
||||||
*/
|
*/
|
||||||
public addDomain(domain: string): void {
|
public addDomain(domain: string): void {
|
||||||
if (!this.domainCertificates.has(domain)) {
|
if (!this.domainCertificates.has(domain)) {
|
||||||
@ -38,8 +160,8 @@ export class Port80Handler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Removes a domain from management.
|
* Removes a domain from management
|
||||||
* @param domain The domain to remove.
|
* @param domain The domain to remove
|
||||||
*/
|
*/
|
||||||
public removeDomain(domain: string): void {
|
public removeDomain(domain: string): void {
|
||||||
if (this.domainCertificates.delete(domain)) {
|
if (this.domainCertificates.delete(domain)) {
|
||||||
@ -48,45 +170,116 @@ export class Port80Handler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Lazy initialization of the ACME client.
|
* Sets a certificate for a domain directly (for externally obtained certificates)
|
||||||
* Uses Let’s Encrypt’s production directory (for testing you might switch to staging).
|
* @param domain The domain for the certificate
|
||||||
|
* @param certificate The certificate (PEM format)
|
||||||
|
* @param privateKey The private key (PEM format)
|
||||||
|
* @param expiryDate Optional expiry date
|
||||||
*/
|
*/
|
||||||
private async getAcmeClient(): Promise<acme.Client> {
|
public setCertificate(domain: string, certificate: string, privateKey: string, expiryDate?: Date): void {
|
||||||
|
let domainInfo = this.domainCertificates.get(domain);
|
||||||
|
|
||||||
|
if (!domainInfo) {
|
||||||
|
domainInfo = { certObtained: false, obtainingInProgress: false };
|
||||||
|
this.domainCertificates.set(domain, domainInfo);
|
||||||
|
}
|
||||||
|
|
||||||
|
domainInfo.certificate = certificate;
|
||||||
|
domainInfo.privateKey = privateKey;
|
||||||
|
domainInfo.certObtained = true;
|
||||||
|
domainInfo.obtainingInProgress = false;
|
||||||
|
|
||||||
|
if (expiryDate) {
|
||||||
|
domainInfo.expiryDate = expiryDate;
|
||||||
|
} else {
|
||||||
|
// Try to extract expiry date from certificate
|
||||||
|
try {
|
||||||
|
// This is a simplistic approach - in a real implementation, use a proper
|
||||||
|
// certificate parsing library like node-forge or x509
|
||||||
|
const matches = certificate.match(/Not After\s*:\s*(.*?)(?:\n|$)/i);
|
||||||
|
if (matches && matches[1]) {
|
||||||
|
domainInfo.expiryDate = new Date(matches[1]);
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(`Failed to extract expiry date from certificate for ${domain}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Certificate set for ${domain}`);
|
||||||
|
|
||||||
|
// Emit certificate event
|
||||||
|
this.emitCertificateEvent(CertManagerEvents.CERTIFICATE_ISSUED, {
|
||||||
|
domain,
|
||||||
|
certificate,
|
||||||
|
privateKey,
|
||||||
|
expiryDate: domainInfo.expiryDate || new Date(Date.now() + 90 * 24 * 60 * 60 * 1000) // 90 days default
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets the certificate for a domain if it exists
|
||||||
|
* @param domain The domain to get the certificate for
|
||||||
|
*/
|
||||||
|
public getCertificate(domain: string): ICertificateData | null {
|
||||||
|
const domainInfo = this.domainCertificates.get(domain);
|
||||||
|
|
||||||
|
if (!domainInfo || !domainInfo.certObtained || !domainInfo.certificate || !domainInfo.privateKey) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
domain,
|
||||||
|
certificate: domainInfo.certificate,
|
||||||
|
privateKey: domainInfo.privateKey,
|
||||||
|
expiryDate: domainInfo.expiryDate || new Date(Date.now() + 90 * 24 * 60 * 60 * 1000) // 90 days default
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Lazy initialization of the ACME client
|
||||||
|
* @returns An ACME client instance
|
||||||
|
*/
|
||||||
|
private async getAcmeClient(): Promise<plugins.acme.Client> {
|
||||||
if (this.acmeClient) {
|
if (this.acmeClient) {
|
||||||
return this.acmeClient;
|
return this.acmeClient;
|
||||||
}
|
}
|
||||||
// Generate a new account key and convert Buffer to string.
|
|
||||||
this.accountKey = (await acme.forge.createPrivateKey()).toString();
|
// Generate a new account key
|
||||||
this.acmeClient = new acme.Client({
|
this.accountKey = (await plugins.acme.forge.createPrivateKey()).toString();
|
||||||
directoryUrl: acme.directory.letsencrypt.production, // Use production for a real certificate
|
|
||||||
// For testing, you could use:
|
this.acmeClient = new plugins.acme.Client({
|
||||||
// directoryUrl: acme.directory.letsencrypt.staging,
|
directoryUrl: this.options.useProduction
|
||||||
|
? plugins.acme.directory.letsencrypt.production
|
||||||
|
: plugins.acme.directory.letsencrypt.staging,
|
||||||
accountKey: this.accountKey,
|
accountKey: this.accountKey,
|
||||||
});
|
});
|
||||||
// Create a new account. Make sure to update the contact email.
|
|
||||||
|
// Create a new account
|
||||||
await this.acmeClient.createAccount({
|
await this.acmeClient.createAccount({
|
||||||
termsOfServiceAgreed: true,
|
termsOfServiceAgreed: true,
|
||||||
contact: ['mailto:admin@example.com'],
|
contact: [`mailto:${this.options.contactEmail}`],
|
||||||
});
|
});
|
||||||
|
|
||||||
return this.acmeClient;
|
return this.acmeClient;
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Handles incoming HTTP requests on port 80.
|
* Handles incoming HTTP requests
|
||||||
* If the request is for an ACME challenge, it responds with the key authorization.
|
* @param req The HTTP request
|
||||||
* If the domain has a certificate, it redirects to HTTPS; otherwise, it initiates certificate issuance.
|
* @param res The HTTP response
|
||||||
*/
|
*/
|
||||||
private handleRequest(req: http.IncomingMessage, res: http.ServerResponse): void {
|
private handleRequest(req: plugins.http.IncomingMessage, res: plugins.http.ServerResponse): void {
|
||||||
const hostHeader = req.headers.host;
|
const hostHeader = req.headers.host;
|
||||||
if (!hostHeader) {
|
if (!hostHeader) {
|
||||||
res.statusCode = 400;
|
res.statusCode = 400;
|
||||||
res.end('Bad Request: Host header is missing');
|
res.end('Bad Request: Host header is missing');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Extract domain (ignoring any port in the Host header)
|
// Extract domain (ignoring any port in the Host header)
|
||||||
const domain = hostHeader.split(':')[0];
|
const domain = hostHeader.split(':')[0];
|
||||||
|
|
||||||
// If the request is for an ACME HTTP-01 challenge, handle it.
|
// If the request is for an ACME HTTP-01 challenge, handle it
|
||||||
if (req.url && req.url.startsWith('/.well-known/acme-challenge/')) {
|
if (req.url && req.url.startsWith('/.well-known/acme-challenge/')) {
|
||||||
this.handleAcmeChallenge(req, res, domain);
|
this.handleAcmeChallenge(req, res, domain);
|
||||||
return;
|
return;
|
||||||
@ -100,38 +293,47 @@ export class Port80Handler {
|
|||||||
|
|
||||||
const domainInfo = this.domainCertificates.get(domain)!;
|
const domainInfo = this.domainCertificates.get(domain)!;
|
||||||
|
|
||||||
// If certificate exists, redirect to HTTPS on port 443.
|
// If certificate exists, redirect to HTTPS
|
||||||
if (domainInfo.certObtained) {
|
if (domainInfo.certObtained) {
|
||||||
const redirectUrl = `https://${domain}:443${req.url}`;
|
const httpsPort = this.options.httpsRedirectPort;
|
||||||
|
const portSuffix = httpsPort === 443 ? '' : `:${httpsPort}`;
|
||||||
|
const redirectUrl = `https://${domain}${portSuffix}${req.url || '/'}`;
|
||||||
|
|
||||||
res.statusCode = 301;
|
res.statusCode = 301;
|
||||||
res.setHeader('Location', redirectUrl);
|
res.setHeader('Location', redirectUrl);
|
||||||
res.end(`Redirecting to ${redirectUrl}`);
|
res.end(`Redirecting to ${redirectUrl}`);
|
||||||
} else {
|
} else {
|
||||||
// Trigger certificate issuance if not already running.
|
// Trigger certificate issuance if not already running
|
||||||
if (!domainInfo.obtainingInProgress) {
|
if (!domainInfo.obtainingInProgress) {
|
||||||
domainInfo.obtainingInProgress = true;
|
|
||||||
this.obtainCertificate(domain).catch(err => {
|
this.obtainCertificate(domain).catch(err => {
|
||||||
|
this.emit(CertManagerEvents.CERTIFICATE_FAILED, { domain, error: err.message });
|
||||||
console.error(`Error obtaining certificate for ${domain}:`, err);
|
console.error(`Error obtaining certificate for ${domain}:`, err);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
res.statusCode = 503;
|
res.statusCode = 503;
|
||||||
res.end('Certificate issuance in progress, please try again later.');
|
res.end('Certificate issuance in progress, please try again later.');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Serves the ACME HTTP-01 challenge response.
|
* Serves the ACME HTTP-01 challenge response
|
||||||
|
* @param req The HTTP request
|
||||||
|
* @param res The HTTP response
|
||||||
|
* @param domain The domain for the challenge
|
||||||
*/
|
*/
|
||||||
private handleAcmeChallenge(req: http.IncomingMessage, res: http.ServerResponse, domain: string): void {
|
private handleAcmeChallenge(req: plugins.http.IncomingMessage, res: plugins.http.ServerResponse, domain: string): void {
|
||||||
const domainInfo = this.domainCertificates.get(domain);
|
const domainInfo = this.domainCertificates.get(domain);
|
||||||
if (!domainInfo) {
|
if (!domainInfo) {
|
||||||
res.statusCode = 404;
|
res.statusCode = 404;
|
||||||
res.end('Domain not configured');
|
res.end('Domain not configured');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
// The token is the last part of the URL.
|
|
||||||
|
// The token is the last part of the URL
|
||||||
const urlParts = req.url?.split('/');
|
const urlParts = req.url?.split('/');
|
||||||
const token = urlParts ? urlParts[urlParts.length - 1] : '';
|
const token = urlParts ? urlParts[urlParts.length - 1] : '';
|
||||||
|
|
||||||
if (domainInfo.challengeToken === token && domainInfo.challengeKeyAuthorization) {
|
if (domainInfo.challengeToken === token && domainInfo.challengeKeyAuthorization) {
|
||||||
res.statusCode = 200;
|
res.statusCode = 200;
|
||||||
res.setHeader('Content-Type', 'text/plain');
|
res.setHeader('Content-Type', 'text/plain');
|
||||||
@ -144,71 +346,214 @@ export class Port80Handler {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Uses acme-client to perform a full ACME HTTP-01 challenge to obtain a certificate.
|
* Obtains a certificate for a domain using ACME HTTP-01 challenge
|
||||||
* On success, it stores the certificate and key in memory and clears challenge data.
|
* @param domain The domain to obtain a certificate for
|
||||||
|
* @param isRenewal Whether this is a renewal attempt
|
||||||
*/
|
*/
|
||||||
private async obtainCertificate(domain: string): Promise<void> {
|
private async obtainCertificate(domain: string, isRenewal: boolean = false): Promise<void> {
|
||||||
|
// Get the domain info
|
||||||
|
const domainInfo = this.domainCertificates.get(domain);
|
||||||
|
if (!domainInfo) {
|
||||||
|
throw new Error(`Domain not found: ${domain}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Prevent concurrent certificate issuance
|
||||||
|
if (domainInfo.obtainingInProgress) {
|
||||||
|
console.log(`Certificate issuance already in progress for ${domain}`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
domainInfo.obtainingInProgress = true;
|
||||||
|
domainInfo.lastRenewalAttempt = new Date();
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const client = await this.getAcmeClient();
|
const client = await this.getAcmeClient();
|
||||||
|
|
||||||
// Create a new order for the domain.
|
// Create a new order for the domain
|
||||||
const order = await client.createOrder({
|
const order = await client.createOrder({
|
||||||
identifiers: [{ type: 'dns', value: domain }],
|
identifiers: [{ type: 'dns', value: domain }],
|
||||||
});
|
});
|
||||||
|
|
||||||
// Get the authorizations for the order.
|
// Get the authorizations for the order
|
||||||
const authorizations = await client.getAuthorizations(order);
|
const authorizations = await client.getAuthorizations(order);
|
||||||
|
|
||||||
for (const authz of authorizations) {
|
for (const authz of authorizations) {
|
||||||
const challenge = authz.challenges.find(ch => ch.type === 'http-01');
|
const challenge = authz.challenges.find(ch => ch.type === 'http-01');
|
||||||
if (!challenge) {
|
if (!challenge) {
|
||||||
throw new Error('HTTP-01 challenge not found');
|
throw new Error('HTTP-01 challenge not found');
|
||||||
}
|
}
|
||||||
// Get the key authorization for the challenge.
|
|
||||||
|
// Get the key authorization for the challenge
|
||||||
const keyAuthorization = await client.getChallengeKeyAuthorization(challenge);
|
const keyAuthorization = await client.getChallengeKeyAuthorization(challenge);
|
||||||
const domainInfo = this.domainCertificates.get(domain)!;
|
|
||||||
|
// Store the challenge data
|
||||||
domainInfo.challengeToken = challenge.token;
|
domainInfo.challengeToken = challenge.token;
|
||||||
domainInfo.challengeKeyAuthorization = keyAuthorization;
|
domainInfo.challengeKeyAuthorization = keyAuthorization;
|
||||||
|
|
||||||
// Notify the ACME server that the challenge is ready.
|
// ACME client type definition workaround - use compatible approach
|
||||||
// The acme-client examples show that verifyChallenge takes three arguments:
|
// First check if challenge verification is needed
|
||||||
// (authorization, challenge, keyAuthorization). However, the official TypeScript
|
const authzUrl = authz.url;
|
||||||
// types appear to be out-of-sync. As a workaround, we cast client to 'any'.
|
|
||||||
await (client as any).verifyChallenge(authz, challenge, keyAuthorization);
|
|
||||||
|
|
||||||
await client.completeChallenge(challenge);
|
try {
|
||||||
// Wait until the challenge is validated.
|
// Check if authzUrl exists and perform verification
|
||||||
await client.waitForValidStatus(challenge);
|
if (authzUrl) {
|
||||||
console.log(`HTTP-01 challenge completed for ${domain}`);
|
await client.verifyChallenge(authz, challenge);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Generate a CSR and a new private key for the domain.
|
// Complete the challenge
|
||||||
// Convert the resulting Buffers to strings.
|
await client.completeChallenge(challenge);
|
||||||
const [csrBuffer, privateKeyBuffer] = await acme.forge.createCsr({
|
|
||||||
|
// Wait for validation
|
||||||
|
await client.waitForValidStatus(challenge);
|
||||||
|
console.log(`HTTP-01 challenge completed for ${domain}`);
|
||||||
|
} catch (error) {
|
||||||
|
console.error(`Challenge error for ${domain}:`, error);
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Generate a CSR and private key
|
||||||
|
const [csrBuffer, privateKeyBuffer] = await plugins.acme.forge.createCsr({
|
||||||
commonName: domain,
|
commonName: domain,
|
||||||
});
|
});
|
||||||
|
|
||||||
const csr = csrBuffer.toString();
|
const csr = csrBuffer.toString();
|
||||||
const privateKey = privateKeyBuffer.toString();
|
const privateKey = privateKeyBuffer.toString();
|
||||||
|
|
||||||
// Finalize the order and obtain the certificate.
|
// Finalize the order with our CSR
|
||||||
await client.finalizeOrder(order, csr);
|
await client.finalizeOrder(order, csr);
|
||||||
|
|
||||||
|
// Get the certificate with the full chain
|
||||||
const certificate = await client.getCertificate(order);
|
const certificate = await client.getCertificate(order);
|
||||||
|
|
||||||
const domainInfo = this.domainCertificates.get(domain)!;
|
// Store the certificate and key
|
||||||
domainInfo.certificate = certificate;
|
domainInfo.certificate = certificate;
|
||||||
domainInfo.privateKey = privateKey;
|
domainInfo.privateKey = privateKey;
|
||||||
domainInfo.certObtained = true;
|
domainInfo.certObtained = true;
|
||||||
domainInfo.obtainingInProgress = false;
|
|
||||||
|
// Clear challenge data
|
||||||
delete domainInfo.challengeToken;
|
delete domainInfo.challengeToken;
|
||||||
delete domainInfo.challengeKeyAuthorization;
|
delete domainInfo.challengeKeyAuthorization;
|
||||||
|
|
||||||
console.log(`Certificate obtained for ${domain}`);
|
// Extract expiry date from certificate
|
||||||
// In a production system, persist the certificate and key and reload your TLS server.
|
try {
|
||||||
|
const matches = certificate.match(/Not After\s*:\s*(.*?)(?:\n|$)/i);
|
||||||
|
if (matches && matches[1]) {
|
||||||
|
domainInfo.expiryDate = new Date(matches[1]);
|
||||||
|
console.log(`Certificate for ${domain} will expire on ${domainInfo.expiryDate.toISOString()}`);
|
||||||
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
|
console.warn(`Failed to extract expiry date from certificate for ${domain}`);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Certificate ${isRenewal ? 'renewed' : 'obtained'} for ${domain}`);
|
||||||
|
|
||||||
|
// Emit the appropriate event
|
||||||
|
const eventType = isRenewal
|
||||||
|
? CertManagerEvents.CERTIFICATE_RENEWED
|
||||||
|
: CertManagerEvents.CERTIFICATE_ISSUED;
|
||||||
|
|
||||||
|
this.emitCertificateEvent(eventType, {
|
||||||
|
domain,
|
||||||
|
certificate,
|
||||||
|
privateKey,
|
||||||
|
expiryDate: domainInfo.expiryDate || new Date(Date.now() + 90 * 24 * 60 * 60 * 1000) // 90 days default
|
||||||
|
});
|
||||||
|
|
||||||
|
} catch (error: any) {
|
||||||
|
// Check for rate limit errors
|
||||||
|
if (error.message && (
|
||||||
|
error.message.includes('rateLimited') ||
|
||||||
|
error.message.includes('too many certificates') ||
|
||||||
|
error.message.includes('rate limit')
|
||||||
|
)) {
|
||||||
|
console.error(`Rate limit reached for ${domain}. Waiting before retry.`);
|
||||||
|
} else {
|
||||||
console.error(`Error during certificate issuance for ${domain}:`, error);
|
console.error(`Error during certificate issuance for ${domain}:`, error);
|
||||||
const domainInfo = this.domainCertificates.get(domain);
|
}
|
||||||
if (domainInfo) {
|
|
||||||
|
// Emit failure event
|
||||||
|
this.emit(CertManagerEvents.CERTIFICATE_FAILED, {
|
||||||
|
domain,
|
||||||
|
error: error.message || 'Unknown error',
|
||||||
|
isRenewal
|
||||||
|
});
|
||||||
|
} finally {
|
||||||
|
// Reset flag whether successful or not
|
||||||
domainInfo.obtainingInProgress = false;
|
domainInfo.obtainingInProgress = false;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Starts the certificate renewal timer
|
||||||
|
*/
|
||||||
|
private startRenewalTimer(): void {
|
||||||
|
if (this.renewalTimer) {
|
||||||
|
clearInterval(this.renewalTimer);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Convert hours to milliseconds
|
||||||
|
const checkInterval = this.options.renewCheckIntervalHours * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
this.renewalTimer = setInterval(() => this.checkForRenewals(), checkInterval);
|
||||||
|
|
||||||
|
// Prevent the timer from keeping the process alive
|
||||||
|
if (this.renewalTimer.unref) {
|
||||||
|
this.renewalTimer.unref();
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`Certificate renewal check scheduled every ${this.options.renewCheckIntervalHours} hours`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Checks for certificates that need renewal
|
||||||
|
*/
|
||||||
|
private checkForRenewals(): void {
|
||||||
|
if (this.isShuttingDown) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log('Checking for certificates that need renewal...');
|
||||||
|
|
||||||
|
const now = new Date();
|
||||||
|
const renewThresholdMs = this.options.renewThresholdDays * 24 * 60 * 60 * 1000;
|
||||||
|
|
||||||
|
for (const [domain, domainInfo] of this.domainCertificates.entries()) {
|
||||||
|
// Skip domains without certificates or already in renewal
|
||||||
|
if (!domainInfo.certObtained || domainInfo.obtainingInProgress) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Skip domains without expiry dates
|
||||||
|
if (!domainInfo.expiryDate) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const timeUntilExpiry = domainInfo.expiryDate.getTime() - now.getTime();
|
||||||
|
|
||||||
|
// Check if certificate is near expiry
|
||||||
|
if (timeUntilExpiry <= renewThresholdMs) {
|
||||||
|
console.log(`Certificate for ${domain} expires soon, renewing...`);
|
||||||
|
this.emit(CertManagerEvents.CERTIFICATE_EXPIRING, {
|
||||||
|
domain,
|
||||||
|
expiryDate: domainInfo.expiryDate,
|
||||||
|
daysRemaining: Math.ceil(timeUntilExpiry / (24 * 60 * 60 * 1000))
|
||||||
|
});
|
||||||
|
|
||||||
|
// Start renewal process
|
||||||
|
this.obtainCertificate(domain, true).catch(err => {
|
||||||
|
console.error(`Error renewing certificate for ${domain}:`, err);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Emits a certificate event with the certificate data
|
||||||
|
* @param eventType The event type to emit
|
||||||
|
* @param data The certificate data
|
||||||
|
*/
|
||||||
|
private emitCertificateEvent(eventType: CertManagerEvents, data: ICertificateData): void {
|
||||||
|
this.emit(eventType, data);
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -90,7 +90,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
try {
|
try {
|
||||||
// Check if buffer is too small for TLS
|
// Check if buffer is too small for TLS
|
||||||
if (buffer.length < 5) {
|
if (buffer.length < 5) {
|
||||||
if (enableLogging) console.log("Buffer too small for TLS header");
|
if (enableLogging) console.log('Buffer too small for TLS header');
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -109,7 +109,10 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
// Check record length
|
// Check record length
|
||||||
const recordLength = buffer.readUInt16BE(3);
|
const recordLength = buffer.readUInt16BE(3);
|
||||||
if (buffer.length < 5 + recordLength) {
|
if (buffer.length < 5 + recordLength) {
|
||||||
if (enableLogging) console.log(`Buffer too small for TLS record. Expected: ${5 + recordLength}, Got: ${buffer.length}`);
|
if (enableLogging)
|
||||||
|
console.log(
|
||||||
|
`Buffer too small for TLS record. Expected: ${5 + recordLength}, Got: ${buffer.length}`
|
||||||
|
);
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -136,7 +139,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
|
|
||||||
// Cipher suites
|
// Cipher suites
|
||||||
if (offset + 2 > buffer.length) {
|
if (offset + 2 > buffer.length) {
|
||||||
if (enableLogging) console.log("Buffer too small for cipher suites length");
|
if (enableLogging) console.log('Buffer too small for cipher suites length');
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
const cipherSuitesLength = buffer.readUInt16BE(offset);
|
const cipherSuitesLength = buffer.readUInt16BE(offset);
|
||||||
@ -145,7 +148,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
|
|
||||||
// Compression methods
|
// Compression methods
|
||||||
if (offset + 1 > buffer.length) {
|
if (offset + 1 > buffer.length) {
|
||||||
if (enableLogging) console.log("Buffer too small for compression methods length");
|
if (enableLogging) console.log('Buffer too small for compression methods length');
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
const compressionMethodsLength = buffer.readUInt8(offset);
|
const compressionMethodsLength = buffer.readUInt8(offset);
|
||||||
@ -154,7 +157,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
|
|
||||||
// Extensions
|
// Extensions
|
||||||
if (offset + 2 > buffer.length) {
|
if (offset + 2 > buffer.length) {
|
||||||
if (enableLogging) console.log("Buffer too small for extensions length");
|
if (enableLogging) console.log('Buffer too small for extensions length');
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
const extensionsLength = buffer.readUInt16BE(offset);
|
const extensionsLength = buffer.readUInt16BE(offset);
|
||||||
@ -163,7 +166,10 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
const extensionsEnd = offset + extensionsLength;
|
const extensionsEnd = offset + extensionsLength;
|
||||||
|
|
||||||
if (extensionsEnd > buffer.length) {
|
if (extensionsEnd > buffer.length) {
|
||||||
if (enableLogging) console.log(`Buffer too small for extensions. Expected end: ${extensionsEnd}, Buffer length: ${buffer.length}`);
|
if (enableLogging)
|
||||||
|
console.log(
|
||||||
|
`Buffer too small for extensions. Expected end: ${extensionsEnd}, Buffer length: ${buffer.length}`
|
||||||
|
);
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -172,13 +178,15 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
const extensionType = buffer.readUInt16BE(offset);
|
const extensionType = buffer.readUInt16BE(offset);
|
||||||
const extensionLength = buffer.readUInt16BE(offset + 2);
|
const extensionLength = buffer.readUInt16BE(offset + 2);
|
||||||
|
|
||||||
if (enableLogging) console.log(`Extension Type: 0x${extensionType.toString(16)}, Length: ${extensionLength}`);
|
if (enableLogging)
|
||||||
|
console.log(`Extension Type: 0x${extensionType.toString(16)}, Length: ${extensionLength}`);
|
||||||
|
|
||||||
offset += 4;
|
offset += 4;
|
||||||
|
|
||||||
if (extensionType === 0x0000) { // SNI extension
|
if (extensionType === 0x0000) {
|
||||||
|
// SNI extension
|
||||||
if (offset + 2 > buffer.length) {
|
if (offset + 2 > buffer.length) {
|
||||||
if (enableLogging) console.log("Buffer too small for SNI list length");
|
if (enableLogging) console.log('Buffer too small for SNI list length');
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -188,7 +196,10 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
const sniListEnd = offset + sniListLength;
|
const sniListEnd = offset + sniListLength;
|
||||||
|
|
||||||
if (sniListEnd > buffer.length) {
|
if (sniListEnd > buffer.length) {
|
||||||
if (enableLogging) console.log(`Buffer too small for SNI list. Expected end: ${sniListEnd}, Buffer length: ${buffer.length}`);
|
if (enableLogging)
|
||||||
|
console.log(
|
||||||
|
`Buffer too small for SNI list. Expected end: ${sniListEnd}, Buffer length: ${buffer.length}`
|
||||||
|
);
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -199,9 +210,15 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
|
|
||||||
if (enableLogging) console.log(`Name Type: ${nameType}, Name Length: ${nameLen}`);
|
if (enableLogging) console.log(`Name Type: ${nameType}, Name Length: ${nameLen}`);
|
||||||
|
|
||||||
if (nameType === 0) { // host_name
|
if (nameType === 0) {
|
||||||
|
// host_name
|
||||||
if (offset + nameLen > buffer.length) {
|
if (offset + nameLen > buffer.length) {
|
||||||
if (enableLogging) console.log(`Buffer too small for hostname. Expected: ${offset + nameLen}, Got: ${buffer.length}`);
|
if (enableLogging)
|
||||||
|
console.log(
|
||||||
|
`Buffer too small for hostname. Expected: ${offset + nameLen}, Got: ${
|
||||||
|
buffer.length
|
||||||
|
}`
|
||||||
|
);
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -218,7 +235,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (enableLogging) console.log("No SNI extension found");
|
if (enableLogging) console.log('No SNI extension found');
|
||||||
return undefined;
|
return undefined;
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(`Error extracting SNI: ${err}`);
|
console.log(`Error extracting SNI: ${err}`);
|
||||||
@ -228,7 +245,7 @@ function extractSNI(buffer: Buffer, enableLogging: boolean = false): string | un
|
|||||||
|
|
||||||
// Helper: Check if a port falls within any of the given port ranges
|
// Helper: Check if a port falls within any of the given port ranges
|
||||||
const isPortInRanges = (port: number, ranges: Array<{ from: number; to: number }>): boolean => {
|
const isPortInRanges = (port: number, ranges: Array<{ from: number; to: number }>): boolean => {
|
||||||
return ranges.some(range => port >= range.from && port <= range.to);
|
return ranges.some((range) => port >= range.from && port <= range.to);
|
||||||
};
|
};
|
||||||
|
|
||||||
// Helper: Check if a given IP matches any of the glob patterns
|
// Helper: Check if a given IP matches any of the glob patterns
|
||||||
@ -251,8 +268,8 @@ const isAllowed = (ip: string, patterns: string[]): boolean => {
|
|||||||
if (normalizedIPVariants.length === 0) return false;
|
if (normalizedIPVariants.length === 0) return false;
|
||||||
|
|
||||||
const expandedPatterns = patterns.flatMap(normalizeIP);
|
const expandedPatterns = patterns.flatMap(normalizeIP);
|
||||||
return normalizedIPVariants.some(ipVariant =>
|
return normalizedIPVariants.some((ipVariant) =>
|
||||||
expandedPatterns.some(pattern => plugins.minimatch(ipVariant, pattern))
|
expandedPatterns.some((pattern) => plugins.minimatch(ipVariant, pattern))
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -273,10 +290,17 @@ const isTlsHandshake = (buffer: Buffer): boolean => {
|
|||||||
return buffer.length > 0 && buffer[0] === 22; // ContentType.handshake
|
return buffer.length > 0 && buffer[0] === 22; // ContentType.handshake
|
||||||
};
|
};
|
||||||
|
|
||||||
|
// Helper: Ensure timeout values don't exceed Node.js max safe integer
|
||||||
|
const ensureSafeTimeout = (timeout: number): number => {
|
||||||
|
const MAX_SAFE_TIMEOUT = 2147483647; // Maximum safe value (2^31 - 1)
|
||||||
|
return Math.min(Math.floor(timeout), MAX_SAFE_TIMEOUT);
|
||||||
|
};
|
||||||
|
|
||||||
// Helper: Generate a slightly randomized timeout to prevent thundering herd
|
// Helper: Generate a slightly randomized timeout to prevent thundering herd
|
||||||
const randomizeTimeout = (baseTimeout: number, variationPercent: number = 5): number => {
|
const randomizeTimeout = (baseTimeout: number, variationPercent: number = 5): number => {
|
||||||
const variation = baseTimeout * (variationPercent / 100);
|
const safeBaseTimeout = ensureSafeTimeout(baseTimeout);
|
||||||
return baseTimeout + Math.floor(Math.random() * variation * 2) - variation;
|
const variation = safeBaseTimeout * (variationPercent / 100);
|
||||||
|
return ensureSafeTimeout(safeBaseTimeout + Math.floor(Math.random() * variation * 2) - variation);
|
||||||
};
|
};
|
||||||
|
|
||||||
export class PortProxy {
|
export class PortProxy {
|
||||||
@ -308,12 +332,12 @@ export class PortProxy {
|
|||||||
...settingsArg,
|
...settingsArg,
|
||||||
targetIP: settingsArg.targetIP || 'localhost',
|
targetIP: settingsArg.targetIP || 'localhost',
|
||||||
|
|
||||||
// Timeout settings with our enhanced defaults
|
// Timeout settings with safe maximum values
|
||||||
initialDataTimeout: settingsArg.initialDataTimeout || 60000, // 60 seconds for initial data
|
initialDataTimeout: settingsArg.initialDataTimeout || 60000, // 60 seconds for initial handshake
|
||||||
socketTimeout: settingsArg.socketTimeout || 3600000, // 1 hour socket timeout
|
socketTimeout: ensureSafeTimeout(settingsArg.socketTimeout || 2147483647), // Maximum safe value (~24.8 days)
|
||||||
inactivityCheckInterval: settingsArg.inactivityCheckInterval || 60000, // 60 seconds interval
|
inactivityCheckInterval: settingsArg.inactivityCheckInterval || 60000, // 60 seconds interval
|
||||||
maxConnectionLifetime: settingsArg.maxConnectionLifetime || 3600000, // 1 hour default lifetime
|
maxConnectionLifetime: ensureSafeTimeout(settingsArg.maxConnectionLifetime || 2147483647), // Maximum safe value (~24.8 days)
|
||||||
inactivityTimeout: settingsArg.inactivityTimeout || 3600000, // 1 hour inactivity timeout
|
inactivityTimeout: ensureSafeTimeout(settingsArg.inactivityTimeout || 14400000), // 4 hours inactivity timeout
|
||||||
|
|
||||||
gracefulShutdownTimeout: settingsArg.gracefulShutdownTimeout || 30000, // 30 seconds
|
gracefulShutdownTimeout: settingsArg.gracefulShutdownTimeout || 30000, // 30 seconds
|
||||||
|
|
||||||
@ -356,7 +380,7 @@ export class PortProxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Get timestamps and filter out entries older than 1 minute
|
// Get timestamps and filter out entries older than 1 minute
|
||||||
const timestamps = this.connectionRateByIP.get(ip)!.filter(time => now - time < minute);
|
const timestamps = this.connectionRateByIP.get(ip)!.filter((time) => now - time < minute);
|
||||||
timestamps.push(now);
|
timestamps.push(now);
|
||||||
this.connectionRateByIP.set(ip, timestamps);
|
this.connectionRateByIP.set(ip, timestamps);
|
||||||
|
|
||||||
@ -398,19 +422,19 @@ export class PortProxy {
|
|||||||
* Get connection timeout based on domain config or default settings
|
* Get connection timeout based on domain config or default settings
|
||||||
*/
|
*/
|
||||||
private getConnectionTimeout(record: IConnectionRecord): number {
|
private getConnectionTimeout(record: IConnectionRecord): number {
|
||||||
// If the connection has a domain-specific timeout, use that
|
// If the connection has a domain-specific timeout, use that with safety check
|
||||||
if (record.domainConfig?.connectionTimeout) {
|
if (record.domainConfig?.connectionTimeout) {
|
||||||
return record.domainConfig.connectionTimeout;
|
return ensureSafeTimeout(record.domainConfig.connectionTimeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Use default timeout, potentially randomized
|
// Use default timeout, potentially randomized with safety check
|
||||||
const baseTimeout = this.settings.maxConnectionLifetime!;
|
const baseTimeout = this.settings.maxConnectionLifetime!;
|
||||||
|
|
||||||
if (this.settings.enableRandomizedTimeouts) {
|
if (this.settings.enableRandomizedTimeouts) {
|
||||||
return randomizeTimeout(baseTimeout);
|
return randomizeTimeout(baseTimeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
return baseTimeout;
|
return ensureSafeTimeout(baseTimeout);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@ -505,11 +529,17 @@ export class PortProxy {
|
|||||||
|
|
||||||
// Log connection details
|
// Log connection details
|
||||||
if (this.settings.enableDetailedLogging) {
|
if (this.settings.enableDetailedLogging) {
|
||||||
console.log(`[${record.id}] Connection from ${record.remoteIP} on port ${record.localPort} terminated (${reason}).` +
|
console.log(
|
||||||
` Duration: ${plugins.prettyMs(duration)}, Bytes IN: ${bytesReceived}, OUT: ${bytesSent}, ` +
|
`[${record.id}] Connection from ${record.remoteIP} on port ${record.localPort} terminated (${reason}).` +
|
||||||
`TLS: ${record.isTLS ? 'Yes' : 'No'}`);
|
` Duration: ${plugins.prettyMs(
|
||||||
|
duration
|
||||||
|
)}, Bytes IN: ${bytesReceived}, OUT: ${bytesSent}, ` +
|
||||||
|
`TLS: ${record.isTLS ? 'Yes' : 'No'}`
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
console.log(`[${record.id}] Connection from ${record.remoteIP} terminated (${reason}). Active connections: ${this.connectionRecords.size}`);
|
console.log(
|
||||||
|
`[${record.id}] Connection from ${record.remoteIP} terminated (${reason}). Active connections: ${this.connectionRecords.size}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -556,16 +586,22 @@ export class PortProxy {
|
|||||||
const localPort = socket.localPort || 0; // The port on which this connection was accepted.
|
const localPort = socket.localPort || 0; // The port on which this connection was accepted.
|
||||||
|
|
||||||
// Check rate limits
|
// Check rate limits
|
||||||
if (this.settings.maxConnectionsPerIP &&
|
if (
|
||||||
this.getConnectionCountByIP(remoteIP) >= this.settings.maxConnectionsPerIP) {
|
this.settings.maxConnectionsPerIP &&
|
||||||
console.log(`Connection rejected from ${remoteIP}: Maximum connections per IP (${this.settings.maxConnectionsPerIP}) exceeded`);
|
this.getConnectionCountByIP(remoteIP) >= this.settings.maxConnectionsPerIP
|
||||||
|
) {
|
||||||
|
console.log(
|
||||||
|
`Connection rejected from ${remoteIP}: Maximum connections per IP (${this.settings.maxConnectionsPerIP}) exceeded`
|
||||||
|
);
|
||||||
socket.end();
|
socket.end();
|
||||||
socket.destroy();
|
socket.destroy();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
if (this.settings.connectionRateLimitPerMinute && !this.checkConnectionRate(remoteIP)) {
|
if (this.settings.connectionRateLimitPerMinute && !this.checkConnectionRate(remoteIP)) {
|
||||||
console.log(`Connection rejected from ${remoteIP}: Connection rate limit (${this.settings.connectionRateLimitPerMinute}/min) exceeded`);
|
console.log(
|
||||||
|
`Connection rejected from ${remoteIP}: Connection rate limit (${this.settings.connectionRateLimitPerMinute}/min) exceeded`
|
||||||
|
);
|
||||||
socket.end();
|
socket.end();
|
||||||
socket.destroy();
|
socket.destroy();
|
||||||
return;
|
return;
|
||||||
@ -611,7 +647,7 @@ export class PortProxy {
|
|||||||
localPort: localPort,
|
localPort: localPort,
|
||||||
isTLS: false,
|
isTLS: false,
|
||||||
tlsHandshakeComplete: false,
|
tlsHandshakeComplete: false,
|
||||||
hasReceivedInitialData: false
|
hasReceivedInitialData: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
// Track connection by IP
|
// Track connection by IP
|
||||||
@ -619,9 +655,13 @@ export class PortProxy {
|
|||||||
this.connectionRecords.set(connectionId, connectionRecord);
|
this.connectionRecords.set(connectionId, connectionRecord);
|
||||||
|
|
||||||
if (this.settings.enableDetailedLogging) {
|
if (this.settings.enableDetailedLogging) {
|
||||||
console.log(`[${connectionId}] New connection from ${remoteIP} on port ${localPort}. Active connections: ${this.connectionRecords.size}`);
|
console.log(
|
||||||
|
`[${connectionId}] New connection from ${remoteIP} on port ${localPort}. Active connections: ${this.connectionRecords.size}`
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
console.log(`New connection from ${remoteIP} on port ${localPort}. Active connections: ${this.connectionRecords.size}`);
|
console.log(
|
||||||
|
`New connection from ${remoteIP} on port ${localPort}. Active connections: ${this.connectionRecords.size}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let initialDataReceived = false;
|
let initialDataReceived = false;
|
||||||
@ -661,7 +701,9 @@ export class PortProxy {
|
|||||||
if (this.settings.sniEnabled) {
|
if (this.settings.sniEnabled) {
|
||||||
initialTimeout = setTimeout(() => {
|
initialTimeout = setTimeout(() => {
|
||||||
if (!initialDataReceived) {
|
if (!initialDataReceived) {
|
||||||
console.log(`[${connectionId}] Initial data timeout (${this.settings.initialDataTimeout}ms) for connection from ${remoteIP} on port ${localPort}`);
|
console.log(
|
||||||
|
`[${connectionId}] Initial data timeout (${this.settings.initialDataTimeout}ms) for connection from ${remoteIP} on port ${localPort}`
|
||||||
|
);
|
||||||
if (incomingTerminationReason === null) {
|
if (incomingTerminationReason === null) {
|
||||||
incomingTerminationReason = 'initial_timeout';
|
incomingTerminationReason = 'initial_timeout';
|
||||||
this.incrementTerminationStat('incoming', 'initial_timeout');
|
this.incrementTerminationStat('incoming', 'initial_timeout');
|
||||||
@ -694,7 +736,9 @@ export class PortProxy {
|
|||||||
connectionRecord.isTLS = true;
|
connectionRecord.isTLS = true;
|
||||||
|
|
||||||
if (this.settings.enableTlsDebugLogging) {
|
if (this.settings.enableTlsDebugLogging) {
|
||||||
console.log(`[${connectionId}] TLS handshake detected from ${remoteIP}, ${chunk.length} bytes`);
|
console.log(
|
||||||
|
`[${connectionId}] TLS handshake detected from ${remoteIP}, ${chunk.length} bytes`
|
||||||
|
);
|
||||||
// Try to extract SNI and log detailed debug info
|
// Try to extract SNI and log detailed debug info
|
||||||
extractSNI(chunk, true);
|
extractSNI(chunk, true);
|
||||||
}
|
}
|
||||||
@ -711,12 +755,30 @@ export class PortProxy {
|
|||||||
|
|
||||||
if (code === 'ECONNRESET') {
|
if (code === 'ECONNRESET') {
|
||||||
reason = 'econnreset';
|
reason = 'econnreset';
|
||||||
console.log(`[${connectionId}] ECONNRESET on ${side} side from ${remoteIP}: ${err.message}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(lastActivityAge)} ago`);
|
console.log(
|
||||||
|
`[${connectionId}] ECONNRESET on ${side} side from ${remoteIP}: ${
|
||||||
|
err.message
|
||||||
|
}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(
|
||||||
|
lastActivityAge
|
||||||
|
)} ago`
|
||||||
|
);
|
||||||
} else if (code === 'ETIMEDOUT') {
|
} else if (code === 'ETIMEDOUT') {
|
||||||
reason = 'etimedout';
|
reason = 'etimedout';
|
||||||
console.log(`[${connectionId}] ETIMEDOUT on ${side} side from ${remoteIP}: ${err.message}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(lastActivityAge)} ago`);
|
console.log(
|
||||||
|
`[${connectionId}] ETIMEDOUT on ${side} side from ${remoteIP}: ${
|
||||||
|
err.message
|
||||||
|
}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(
|
||||||
|
lastActivityAge
|
||||||
|
)} ago`
|
||||||
|
);
|
||||||
} else {
|
} else {
|
||||||
console.log(`[${connectionId}] Error on ${side} side from ${remoteIP}: ${err.message}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(lastActivityAge)} ago`);
|
console.log(
|
||||||
|
`[${connectionId}] Error on ${side} side from ${remoteIP}: ${
|
||||||
|
err.message
|
||||||
|
}. Duration: ${plugins.prettyMs(connectionDuration)}, Last activity: ${plugins.prettyMs(
|
||||||
|
lastActivityAge
|
||||||
|
)} ago`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (side === 'incoming' && incomingTerminationReason === null) {
|
if (side === 'incoming' && incomingTerminationReason === null) {
|
||||||
@ -755,7 +817,12 @@ export class PortProxy {
|
|||||||
* @param forcedDomain - If provided, overrides SNI/domain lookup (used for port-based routing).
|
* @param forcedDomain - If provided, overrides SNI/domain lookup (used for port-based routing).
|
||||||
* @param overridePort - If provided, use this port for the outgoing connection.
|
* @param overridePort - If provided, use this port for the outgoing connection.
|
||||||
*/
|
*/
|
||||||
const setupConnection = (serverName: string, initialChunk?: Buffer, forcedDomain?: IDomainConfig, overridePort?: number) => {
|
const setupConnection = (
|
||||||
|
serverName: string,
|
||||||
|
initialChunk?: Buffer,
|
||||||
|
forcedDomain?: IDomainConfig,
|
||||||
|
overridePort?: number
|
||||||
|
) => {
|
||||||
// Clear the initial timeout since we've received data
|
// Clear the initial timeout since we've received data
|
||||||
if (initialTimeout) {
|
if (initialTimeout) {
|
||||||
clearTimeout(initialTimeout);
|
clearTimeout(initialTimeout);
|
||||||
@ -771,16 +838,20 @@ export class PortProxy {
|
|||||||
connectionRecord.isTLS = true;
|
connectionRecord.isTLS = true;
|
||||||
|
|
||||||
if (this.settings.enableTlsDebugLogging) {
|
if (this.settings.enableTlsDebugLogging) {
|
||||||
console.log(`[${connectionId}] TLS handshake detected in setup, ${initialChunk.length} bytes`);
|
console.log(
|
||||||
|
`[${connectionId}] TLS handshake detected in setup, ${initialChunk.length} bytes`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// If a forcedDomain is provided (port-based routing), use it; otherwise, use SNI-based lookup.
|
// If a forcedDomain is provided (port-based routing), use it; otherwise, use SNI-based lookup.
|
||||||
const domainConfig = forcedDomain
|
const domainConfig = forcedDomain
|
||||||
? forcedDomain
|
? forcedDomain
|
||||||
: (serverName ? this.settings.domainConfigs.find(config =>
|
: serverName
|
||||||
config.domains.some(d => plugins.minimatch(serverName, d))
|
? this.settings.domainConfigs.find((config) =>
|
||||||
) : undefined);
|
config.domains.some((d) => plugins.minimatch(serverName, d))
|
||||||
|
)
|
||||||
|
: undefined;
|
||||||
|
|
||||||
// Save domain config in connection record
|
// Save domain config in connection record
|
||||||
connectionRecord.domainConfig = domainConfig;
|
connectionRecord.domainConfig = domainConfig;
|
||||||
@ -789,20 +860,37 @@ export class PortProxy {
|
|||||||
if (domainConfig) {
|
if (domainConfig) {
|
||||||
const effectiveAllowedIPs: string[] = [
|
const effectiveAllowedIPs: string[] = [
|
||||||
...domainConfig.allowedIPs,
|
...domainConfig.allowedIPs,
|
||||||
...(this.settings.defaultAllowedIPs || [])
|
...(this.settings.defaultAllowedIPs || []),
|
||||||
];
|
];
|
||||||
const effectiveBlockedIPs: string[] = [
|
const effectiveBlockedIPs: string[] = [
|
||||||
...(domainConfig.blockedIPs || []),
|
...(domainConfig.blockedIPs || []),
|
||||||
...(this.settings.defaultBlockedIPs || [])
|
...(this.settings.defaultBlockedIPs || []),
|
||||||
];
|
];
|
||||||
|
|
||||||
// Skip IP validation if allowedIPs is empty
|
// Skip IP validation if allowedIPs is empty
|
||||||
if (domainConfig.allowedIPs.length > 0 && !isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)) {
|
if (
|
||||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed for domain ${domainConfig.domains.join(', ')}`);
|
domainConfig.allowedIPs.length > 0 &&
|
||||||
|
!isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)
|
||||||
|
) {
|
||||||
|
return rejectIncomingConnection(
|
||||||
|
'rejected',
|
||||||
|
`Connection rejected: IP ${remoteIP} not allowed for domain ${domainConfig.domains.join(
|
||||||
|
', '
|
||||||
|
)}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} else if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0) {
|
} else if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0) {
|
||||||
if (!isGlobIPAllowed(remoteIP, this.settings.defaultAllowedIPs, this.settings.defaultBlockedIPs || [])) {
|
if (
|
||||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed by default allowed list`);
|
!isGlobIPAllowed(
|
||||||
|
remoteIP,
|
||||||
|
this.settings.defaultAllowedIPs,
|
||||||
|
this.settings.defaultBlockedIPs || []
|
||||||
|
)
|
||||||
|
) {
|
||||||
|
return rejectIncomingConnection(
|
||||||
|
'rejected',
|
||||||
|
`Connection rejected: IP ${remoteIP} not allowed by default allowed list`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -828,7 +916,9 @@ export class PortProxy {
|
|||||||
connectionRecord.isTLS = true;
|
connectionRecord.isTLS = true;
|
||||||
|
|
||||||
if (this.settings.enableTlsDebugLogging) {
|
if (this.settings.enableTlsDebugLogging) {
|
||||||
console.log(`[${connectionId}] TLS handshake detected in tempDataHandler, ${chunk.length} bytes`);
|
console.log(
|
||||||
|
`[${connectionId}] TLS handshake detected in tempDataHandler, ${chunk.length} bytes`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -836,7 +926,9 @@ export class PortProxy {
|
|||||||
const newSize = connectionRecord.pendingDataSize + chunk.length;
|
const newSize = connectionRecord.pendingDataSize + chunk.length;
|
||||||
|
|
||||||
if (this.settings.maxPendingDataSize && newSize > this.settings.maxPendingDataSize) {
|
if (this.settings.maxPendingDataSize && newSize > this.settings.maxPendingDataSize) {
|
||||||
console.log(`[${connectionId}] Buffer limit exceeded for connection from ${remoteIP}: ${newSize} bytes > ${this.settings.maxPendingDataSize} bytes`);
|
console.log(
|
||||||
|
`[${connectionId}] Buffer limit exceeded for connection from ${remoteIP}: ${newSize} bytes > ${this.settings.maxPendingDataSize} bytes`
|
||||||
|
);
|
||||||
socket.end(); // Gracefully close the socket
|
socket.end(); // Gracefully close the socket
|
||||||
return initiateCleanupOnce('buffer_limit_exceeded');
|
return initiateCleanupOnce('buffer_limit_exceeded');
|
||||||
}
|
}
|
||||||
@ -886,17 +978,25 @@ export class PortProxy {
|
|||||||
targetSocket.once('error', (err) => {
|
targetSocket.once('error', (err) => {
|
||||||
// This handler runs only once during the initial connection phase
|
// This handler runs only once during the initial connection phase
|
||||||
const code = (err as any).code;
|
const code = (err as any).code;
|
||||||
console.log(`[${connectionId}] Connection setup error to ${targetHost}:${connectionOptions.port}: ${err.message} (${code})`);
|
console.log(
|
||||||
|
`[${connectionId}] Connection setup error to ${targetHost}:${connectionOptions.port}: ${err.message} (${code})`
|
||||||
|
);
|
||||||
|
|
||||||
// Resume the incoming socket to prevent it from hanging
|
// Resume the incoming socket to prevent it from hanging
|
||||||
socket.resume();
|
socket.resume();
|
||||||
|
|
||||||
if (code === 'ECONNREFUSED') {
|
if (code === 'ECONNREFUSED') {
|
||||||
console.log(`[${connectionId}] Target ${targetHost}:${connectionOptions.port} refused connection`);
|
console.log(
|
||||||
|
`[${connectionId}] Target ${targetHost}:${connectionOptions.port} refused connection`
|
||||||
|
);
|
||||||
} else if (code === 'ETIMEDOUT') {
|
} else if (code === 'ETIMEDOUT') {
|
||||||
console.log(`[${connectionId}] Connection to ${targetHost}:${connectionOptions.port} timed out`);
|
console.log(
|
||||||
|
`[${connectionId}] Connection to ${targetHost}:${connectionOptions.port} timed out`
|
||||||
|
);
|
||||||
} else if (code === 'ECONNRESET') {
|
} else if (code === 'ECONNRESET') {
|
||||||
console.log(`[${connectionId}] Connection to ${targetHost}:${connectionOptions.port} was reset`);
|
console.log(
|
||||||
|
`[${connectionId}] Connection to ${targetHost}:${connectionOptions.port} was reset`
|
||||||
|
);
|
||||||
} else if (code === 'EHOSTUNREACH') {
|
} else if (code === 'EHOSTUNREACH') {
|
||||||
console.log(`[${connectionId}] Host ${targetHost} is unreachable`);
|
console.log(`[${connectionId}] Host ${targetHost} is unreachable`);
|
||||||
}
|
}
|
||||||
@ -922,7 +1022,11 @@ export class PortProxy {
|
|||||||
|
|
||||||
// Handle timeouts
|
// Handle timeouts
|
||||||
socket.on('timeout', () => {
|
socket.on('timeout', () => {
|
||||||
console.log(`[${connectionId}] Timeout on incoming side from ${remoteIP} after ${plugins.prettyMs(this.settings.socketTimeout || 3600000)}`);
|
console.log(
|
||||||
|
`[${connectionId}] Timeout on incoming side from ${remoteIP} after ${plugins.prettyMs(
|
||||||
|
this.settings.socketTimeout || 3600000
|
||||||
|
)}`
|
||||||
|
);
|
||||||
if (incomingTerminationReason === null) {
|
if (incomingTerminationReason === null) {
|
||||||
incomingTerminationReason = 'timeout';
|
incomingTerminationReason = 'timeout';
|
||||||
this.incrementTerminationStat('incoming', 'timeout');
|
this.incrementTerminationStat('incoming', 'timeout');
|
||||||
@ -931,7 +1035,11 @@ export class PortProxy {
|
|||||||
});
|
});
|
||||||
|
|
||||||
targetSocket.on('timeout', () => {
|
targetSocket.on('timeout', () => {
|
||||||
console.log(`[${connectionId}] Timeout on outgoing side from ${remoteIP} after ${plugins.prettyMs(this.settings.socketTimeout || 3600000)}`);
|
console.log(
|
||||||
|
`[${connectionId}] Timeout on outgoing side from ${remoteIP} after ${plugins.prettyMs(
|
||||||
|
this.settings.socketTimeout || 3600000
|
||||||
|
)}`
|
||||||
|
);
|
||||||
if (outgoingTerminationReason === null) {
|
if (outgoingTerminationReason === null) {
|
||||||
outgoingTerminationReason = 'timeout';
|
outgoingTerminationReason = 'timeout';
|
||||||
this.incrementTerminationStat('outgoing', 'timeout');
|
this.incrementTerminationStat('outgoing', 'timeout');
|
||||||
@ -939,9 +1047,9 @@ export class PortProxy {
|
|||||||
initiateCleanupOnce('timeout_outgoing');
|
initiateCleanupOnce('timeout_outgoing');
|
||||||
});
|
});
|
||||||
|
|
||||||
// Set appropriate timeouts using the configured value
|
// Set appropriate timeouts using the configured value with safety
|
||||||
socket.setTimeout(this.settings.socketTimeout || 3600000);
|
socket.setTimeout(ensureSafeTimeout(this.settings.socketTimeout || 3600000));
|
||||||
targetSocket.setTimeout(this.settings.socketTimeout || 3600000);
|
targetSocket.setTimeout(ensureSafeTimeout(this.settings.socketTimeout || 3600000));
|
||||||
|
|
||||||
// Track outgoing data for bytes counting
|
// Track outgoing data for bytes counting
|
||||||
targetSocket.on('data', (chunk: Buffer) => {
|
targetSocket.on('data', (chunk: Buffer) => {
|
||||||
@ -965,7 +1073,9 @@ export class PortProxy {
|
|||||||
const combinedData = Buffer.concat(connectionRecord.pendingData);
|
const combinedData = Buffer.concat(connectionRecord.pendingData);
|
||||||
targetSocket.write(combinedData, (err) => {
|
targetSocket.write(combinedData, (err) => {
|
||||||
if (err) {
|
if (err) {
|
||||||
console.log(`[${connectionId}] Error writing pending data to target: ${err.message}`);
|
console.log(
|
||||||
|
`[${connectionId}] Error writing pending data to target: ${err.message}`
|
||||||
|
);
|
||||||
return initiateCleanupOnce('write_error');
|
return initiateCleanupOnce('write_error');
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -977,13 +1087,25 @@ export class PortProxy {
|
|||||||
if (this.settings.enableDetailedLogging) {
|
if (this.settings.enableDetailedLogging) {
|
||||||
console.log(
|
console.log(
|
||||||
`[${connectionId}] Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
`[${connectionId}] Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
||||||
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})` : ''}` +
|
`${
|
||||||
|
serverName
|
||||||
|
? ` (SNI: ${serverName})`
|
||||||
|
: forcedDomain
|
||||||
|
? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})`
|
||||||
|
: ''
|
||||||
|
}` +
|
||||||
` TLS: ${connectionRecord.isTLS ? 'Yes' : 'No'}`
|
` TLS: ${connectionRecord.isTLS ? 'Yes' : 'No'}`
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
console.log(
|
console.log(
|
||||||
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
||||||
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})` : ''}`
|
`${
|
||||||
|
serverName
|
||||||
|
? ` (SNI: ${serverName})`
|
||||||
|
: forcedDomain
|
||||||
|
? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})`
|
||||||
|
: ''
|
||||||
|
}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -996,13 +1118,25 @@ export class PortProxy {
|
|||||||
if (this.settings.enableDetailedLogging) {
|
if (this.settings.enableDetailedLogging) {
|
||||||
console.log(
|
console.log(
|
||||||
`[${connectionId}] Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
`[${connectionId}] Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
||||||
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})` : ''}` +
|
`${
|
||||||
|
serverName
|
||||||
|
? ` (SNI: ${serverName})`
|
||||||
|
: forcedDomain
|
||||||
|
? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})`
|
||||||
|
: ''
|
||||||
|
}` +
|
||||||
` TLS: ${connectionRecord.isTLS ? 'Yes' : 'No'}`
|
` TLS: ${connectionRecord.isTLS ? 'Yes' : 'No'}`
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
console.log(
|
console.log(
|
||||||
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
`Connection established: ${remoteIP} -> ${targetHost}:${connectionOptions.port}` +
|
||||||
`${serverName ? ` (SNI: ${serverName})` : forcedDomain ? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})` : ''}`
|
`${
|
||||||
|
serverName
|
||||||
|
? ` (SNI: ${serverName})`
|
||||||
|
: forcedDomain
|
||||||
|
? ` (Port-based for domain: ${forcedDomain.domains.join(', ')})`
|
||||||
|
: ''
|
||||||
|
}`
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1019,13 +1153,19 @@ export class PortProxy {
|
|||||||
// Try to extract SNI from potential renegotiation
|
// Try to extract SNI from potential renegotiation
|
||||||
const newSNI = extractSNI(renegChunk, this.settings.enableTlsDebugLogging);
|
const newSNI = extractSNI(renegChunk, this.settings.enableTlsDebugLogging);
|
||||||
if (newSNI && newSNI !== connectionRecord.lockedDomain) {
|
if (newSNI && newSNI !== connectionRecord.lockedDomain) {
|
||||||
console.log(`[${connectionId}] Rehandshake detected with different SNI: ${newSNI} vs locked ${connectionRecord.lockedDomain}. Terminating connection.`);
|
console.log(
|
||||||
|
`[${connectionId}] Rehandshake detected with different SNI: ${newSNI} vs locked ${connectionRecord.lockedDomain}. Terminating connection.`
|
||||||
|
);
|
||||||
initiateCleanupOnce('sni_mismatch');
|
initiateCleanupOnce('sni_mismatch');
|
||||||
} else if (newSNI && this.settings.enableDetailedLogging) {
|
} else if (newSNI && this.settings.enableDetailedLogging) {
|
||||||
console.log(`[${connectionId}] Rehandshake detected with same SNI: ${newSNI}. Allowing.`);
|
console.log(
|
||||||
|
`[${connectionId}] Rehandshake detected with same SNI: ${newSNI}. Allowing.`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
console.log(`[${connectionId}] Error processing potential renegotiation: ${err}. Allowing connection to continue.`);
|
console.log(
|
||||||
|
`[${connectionId}] Error processing potential renegotiation: ${err}. Allowing connection to continue.`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -1036,12 +1176,18 @@ export class PortProxy {
|
|||||||
clearTimeout(connectionRecord.cleanupTimer);
|
clearTimeout(connectionRecord.cleanupTimer);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Set timeout based on domain config or default
|
// Set timeout based on domain config or default with safety check
|
||||||
const connectionTimeout = this.getConnectionTimeout(connectionRecord);
|
const connectionTimeout = this.getConnectionTimeout(connectionRecord);
|
||||||
|
const safeTimeout = ensureSafeTimeout(connectionTimeout); // Ensure timeout is safe
|
||||||
|
|
||||||
connectionRecord.cleanupTimer = setTimeout(() => {
|
connectionRecord.cleanupTimer = setTimeout(() => {
|
||||||
console.log(`[${connectionId}] Connection from ${remoteIP} exceeded max lifetime (${plugins.prettyMs(connectionTimeout)}), forcing cleanup.`);
|
console.log(
|
||||||
|
`[${connectionId}] Connection from ${remoteIP} exceeded max lifetime (${plugins.prettyMs(
|
||||||
|
connectionTimeout
|
||||||
|
)}), forcing cleanup.`
|
||||||
|
);
|
||||||
initiateCleanupOnce('connection_timeout');
|
initiateCleanupOnce('connection_timeout');
|
||||||
}, connectionTimeout);
|
}, safeTimeout);
|
||||||
|
|
||||||
// Make sure timeout doesn't keep the process alive
|
// Make sure timeout doesn't keep the process alive
|
||||||
if (connectionRecord.cleanupTimer.unref) {
|
if (connectionRecord.cleanupTimer.unref) {
|
||||||
@ -1053,7 +1199,9 @@ export class PortProxy {
|
|||||||
connectionRecord.tlsHandshakeComplete = true;
|
connectionRecord.tlsHandshakeComplete = true;
|
||||||
|
|
||||||
if (this.settings.enableTlsDebugLogging) {
|
if (this.settings.enableTlsDebugLogging) {
|
||||||
console.log(`[${connectionId}] TLS handshake complete for connection from ${remoteIP}`);
|
console.log(
|
||||||
|
`[${connectionId}] TLS handshake complete for connection from ${remoteIP}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -1061,45 +1209,72 @@ export class PortProxy {
|
|||||||
|
|
||||||
// --- PORT RANGE-BASED HANDLING ---
|
// --- PORT RANGE-BASED HANDLING ---
|
||||||
// Only apply port-based rules if the incoming port is within one of the global port ranges.
|
// Only apply port-based rules if the incoming port is within one of the global port ranges.
|
||||||
if (this.settings.globalPortRanges && isPortInRanges(localPort, this.settings.globalPortRanges)) {
|
if (
|
||||||
|
this.settings.globalPortRanges &&
|
||||||
|
isPortInRanges(localPort, this.settings.globalPortRanges)
|
||||||
|
) {
|
||||||
if (this.settings.forwardAllGlobalRanges) {
|
if (this.settings.forwardAllGlobalRanges) {
|
||||||
if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0 && !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
if (
|
||||||
console.log(`[${connectionId}] Connection from ${remoteIP} rejected: IP ${remoteIP} not allowed in global default allowed list.`);
|
this.settings.defaultAllowedIPs &&
|
||||||
|
this.settings.defaultAllowedIPs.length > 0 &&
|
||||||
|
!isAllowed(remoteIP, this.settings.defaultAllowedIPs)
|
||||||
|
) {
|
||||||
|
console.log(
|
||||||
|
`[${connectionId}] Connection from ${remoteIP} rejected: IP ${remoteIP} not allowed in global default allowed list.`
|
||||||
|
);
|
||||||
socket.end();
|
socket.end();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (this.settings.enableDetailedLogging) {
|
if (this.settings.enableDetailedLogging) {
|
||||||
console.log(`[${connectionId}] Port-based connection from ${remoteIP} on port ${localPort} forwarded to global target IP ${this.settings.targetIP}.`);
|
console.log(
|
||||||
|
`[${connectionId}] Port-based connection from ${remoteIP} on port ${localPort} forwarded to global target IP ${this.settings.targetIP}.`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
setupConnection('', undefined, {
|
setupConnection(
|
||||||
|
'',
|
||||||
|
undefined,
|
||||||
|
{
|
||||||
domains: ['global'],
|
domains: ['global'],
|
||||||
allowedIPs: this.settings.defaultAllowedIPs || [],
|
allowedIPs: this.settings.defaultAllowedIPs || [],
|
||||||
blockedIPs: this.settings.defaultBlockedIPs || [],
|
blockedIPs: this.settings.defaultBlockedIPs || [],
|
||||||
targetIPs: [this.settings.targetIP!],
|
targetIPs: [this.settings.targetIP!],
|
||||||
portRanges: []
|
portRanges: [],
|
||||||
}, localPort);
|
},
|
||||||
|
localPort
|
||||||
|
);
|
||||||
return;
|
return;
|
||||||
} else {
|
} else {
|
||||||
// Attempt to find a matching forced domain config based on the local port.
|
// Attempt to find a matching forced domain config based on the local port.
|
||||||
const forcedDomain = this.settings.domainConfigs.find(
|
const forcedDomain = this.settings.domainConfigs.find(
|
||||||
domain => domain.portRanges && domain.portRanges.length > 0 && isPortInRanges(localPort, domain.portRanges)
|
(domain) =>
|
||||||
|
domain.portRanges &&
|
||||||
|
domain.portRanges.length > 0 &&
|
||||||
|
isPortInRanges(localPort, domain.portRanges)
|
||||||
);
|
);
|
||||||
if (forcedDomain) {
|
if (forcedDomain) {
|
||||||
const effectiveAllowedIPs: string[] = [
|
const effectiveAllowedIPs: string[] = [
|
||||||
...forcedDomain.allowedIPs,
|
...forcedDomain.allowedIPs,
|
||||||
...(this.settings.defaultAllowedIPs || [])
|
...(this.settings.defaultAllowedIPs || []),
|
||||||
];
|
];
|
||||||
const effectiveBlockedIPs: string[] = [
|
const effectiveBlockedIPs: string[] = [
|
||||||
...(forcedDomain.blockedIPs || []),
|
...(forcedDomain.blockedIPs || []),
|
||||||
...(this.settings.defaultBlockedIPs || [])
|
...(this.settings.defaultBlockedIPs || []),
|
||||||
];
|
];
|
||||||
if (!isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)) {
|
if (!isGlobIPAllowed(remoteIP, effectiveAllowedIPs, effectiveBlockedIPs)) {
|
||||||
console.log(`[${connectionId}] Connection from ${remoteIP} rejected: IP not allowed for domain ${forcedDomain.domains.join(', ')} on port ${localPort}.`);
|
console.log(
|
||||||
|
`[${connectionId}] Connection from ${remoteIP} rejected: IP not allowed for domain ${forcedDomain.domains.join(
|
||||||
|
', '
|
||||||
|
)} on port ${localPort}.`
|
||||||
|
);
|
||||||
socket.end();
|
socket.end();
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
if (this.settings.enableDetailedLogging) {
|
if (this.settings.enableDetailedLogging) {
|
||||||
console.log(`[${connectionId}] Port-based connection from ${remoteIP} on port ${localPort} matched domain ${forcedDomain.domains.join(', ')}.`);
|
console.log(
|
||||||
|
`[${connectionId}] Port-based connection from ${remoteIP} on port ${localPort} matched domain ${forcedDomain.domains.join(
|
||||||
|
', '
|
||||||
|
)}.`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
setupConnection('', undefined, forcedDomain, localPort);
|
setupConnection('', undefined, forcedDomain, localPort);
|
||||||
return;
|
return;
|
||||||
@ -1127,7 +1302,9 @@ export class PortProxy {
|
|||||||
connectionRecord.isTLS = true;
|
connectionRecord.isTLS = true;
|
||||||
|
|
||||||
if (this.settings.enableTlsDebugLogging) {
|
if (this.settings.enableTlsDebugLogging) {
|
||||||
console.log(`[${connectionId}] Extracting SNI from TLS handshake, ${chunk.length} bytes`);
|
console.log(
|
||||||
|
`[${connectionId}] Extracting SNI from TLS handshake, ${chunk.length} bytes`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
serverName = extractSNI(chunk, this.settings.enableTlsDebugLogging) || '';
|
serverName = extractSNI(chunk, this.settings.enableTlsDebugLogging) || '';
|
||||||
@ -1137,7 +1314,11 @@ export class PortProxy {
|
|||||||
connectionRecord.lockedDomain = serverName;
|
connectionRecord.lockedDomain = serverName;
|
||||||
|
|
||||||
if (this.settings.enableDetailedLogging) {
|
if (this.settings.enableDetailedLogging) {
|
||||||
console.log(`[${connectionId}] Received connection from ${remoteIP} with SNI: ${serverName || '(empty)'}`);
|
console.log(
|
||||||
|
`[${connectionId}] Received connection from ${remoteIP} with SNI: ${
|
||||||
|
serverName || '(empty)'
|
||||||
|
}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
setupConnection(serverName, chunk);
|
setupConnection(serverName, chunk);
|
||||||
@ -1146,8 +1327,15 @@ export class PortProxy {
|
|||||||
initialDataReceived = true;
|
initialDataReceived = true;
|
||||||
connectionRecord.hasReceivedInitialData = true;
|
connectionRecord.hasReceivedInitialData = true;
|
||||||
|
|
||||||
if (this.settings.defaultAllowedIPs && this.settings.defaultAllowedIPs.length > 0 && !isAllowed(remoteIP, this.settings.defaultAllowedIPs)) {
|
if (
|
||||||
return rejectIncomingConnection('rejected', `Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`);
|
this.settings.defaultAllowedIPs &&
|
||||||
|
this.settings.defaultAllowedIPs.length > 0 &&
|
||||||
|
!isAllowed(remoteIP, this.settings.defaultAllowedIPs)
|
||||||
|
) {
|
||||||
|
return rejectIncomingConnection(
|
||||||
|
'rejected',
|
||||||
|
`Connection rejected: IP ${remoteIP} not allowed for non-SNI connection`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
setupConnection('');
|
setupConnection('');
|
||||||
@ -1172,13 +1360,15 @@ export class PortProxy {
|
|||||||
|
|
||||||
// Create a server for each port.
|
// Create a server for each port.
|
||||||
for (const port of listeningPorts) {
|
for (const port of listeningPorts) {
|
||||||
const server = plugins.net
|
const server = plugins.net.createServer(connectionHandler).on('error', (err: Error) => {
|
||||||
.createServer(connectionHandler)
|
|
||||||
.on('error', (err: Error) => {
|
|
||||||
console.log(`Server Error on port ${port}: ${err.message}`);
|
console.log(`Server Error on port ${port}: ${err.message}`);
|
||||||
});
|
});
|
||||||
server.listen(port, () => {
|
server.listen(port, () => {
|
||||||
console.log(`PortProxy -> OK: Now listening on port ${port}${this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''}`);
|
console.log(
|
||||||
|
`PortProxy -> OK: Now listening on port ${port}${
|
||||||
|
this.settings.sniEnabled ? ' (SNI passthrough enabled)' : ''
|
||||||
|
}`
|
||||||
|
);
|
||||||
});
|
});
|
||||||
this.netServers.push(server);
|
this.netServers.push(server);
|
||||||
}
|
}
|
||||||
@ -1221,19 +1411,33 @@ export class PortProxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Parity check: if outgoing socket closed and incoming remains active
|
// Parity check: if outgoing socket closed and incoming remains active
|
||||||
if (record.outgoingClosedTime &&
|
if (
|
||||||
|
record.outgoingClosedTime &&
|
||||||
!record.incoming.destroyed &&
|
!record.incoming.destroyed &&
|
||||||
!record.connectionClosed &&
|
!record.connectionClosed &&
|
||||||
(now - record.outgoingClosedTime > 120000)) {
|
now - record.outgoingClosedTime > 120000
|
||||||
|
) {
|
||||||
const remoteIP = record.remoteIP;
|
const remoteIP = record.remoteIP;
|
||||||
console.log(`[${id}] Parity check: Incoming socket for ${remoteIP} still active ${plugins.prettyMs(now - record.outgoingClosedTime)} after outgoing closed.`);
|
console.log(
|
||||||
|
`[${id}] Parity check: Incoming socket for ${remoteIP} still active ${plugins.prettyMs(
|
||||||
|
now - record.outgoingClosedTime
|
||||||
|
)} after outgoing closed.`
|
||||||
|
);
|
||||||
this.cleanupConnection(record, 'parity_check');
|
this.cleanupConnection(record, 'parity_check');
|
||||||
}
|
}
|
||||||
|
|
||||||
// Check for stalled connections waiting for initial data
|
// Check for stalled connections waiting for initial data
|
||||||
if (!record.hasReceivedInitialData &&
|
if (
|
||||||
(now - record.incomingStartTime > this.settings.initialDataTimeout! / 2)) {
|
!record.hasReceivedInitialData &&
|
||||||
console.log(`[${id}] Warning: Connection from ${record.remoteIP} has not received initial data after ${plugins.prettyMs(now - record.incomingStartTime)}`);
|
now - record.incomingStartTime > this.settings.initialDataTimeout! / 2
|
||||||
|
) {
|
||||||
|
console.log(
|
||||||
|
`[${id}] Warning: Connection from ${
|
||||||
|
record.remoteIP
|
||||||
|
} has not received initial data after ${plugins.prettyMs(
|
||||||
|
now - record.incomingStartTime
|
||||||
|
)}`
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
// Skip inactivity check if disabled
|
// Skip inactivity check if disabled
|
||||||
@ -1243,7 +1447,11 @@ export class PortProxy {
|
|||||||
|
|
||||||
const inactivityTime = now - record.lastActivity;
|
const inactivityTime = now - record.lastActivity;
|
||||||
if (inactivityTime > inactivityThreshold && !record.connectionClosed) {
|
if (inactivityTime > inactivityThreshold && !record.connectionClosed) {
|
||||||
console.log(`[${id}] Inactivity check: No activity on connection from ${record.remoteIP} for ${plugins.prettyMs(inactivityTime)}.`);
|
console.log(
|
||||||
|
`[${id}] Inactivity check: No activity on connection from ${
|
||||||
|
record.remoteIP
|
||||||
|
} for ${plugins.prettyMs(inactivityTime)}.`
|
||||||
|
);
|
||||||
this.cleanupConnection(record, 'inactivity');
|
this.cleanupConnection(record, 'inactivity');
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -1253,8 +1461,13 @@ export class PortProxy {
|
|||||||
console.log(
|
console.log(
|
||||||
`Active connections: ${this.connectionRecords.size}. ` +
|
`Active connections: ${this.connectionRecords.size}. ` +
|
||||||
`Types: TLS=${tlsConnections} (Completed=${completedTlsHandshakes}, Pending=${pendingTlsHandshakes}), Non-TLS=${nonTlsConnections}. ` +
|
`Types: TLS=${tlsConnections} (Completed=${completedTlsHandshakes}, Pending=${pendingTlsHandshakes}), Non-TLS=${nonTlsConnections}. ` +
|
||||||
`Longest running: IN=${plugins.prettyMs(maxIncoming)}, OUT=${plugins.prettyMs(maxOutgoing)}. ` +
|
`Longest running: IN=${plugins.prettyMs(maxIncoming)}, OUT=${plugins.prettyMs(
|
||||||
`Termination stats: ${JSON.stringify({IN: this.terminationStats.incoming, OUT: this.terminationStats.outgoing})}`
|
maxOutgoing
|
||||||
|
)}. ` +
|
||||||
|
`Termination stats: ${JSON.stringify({
|
||||||
|
IN: this.terminationStats.incoming,
|
||||||
|
OUT: this.terminationStats.outgoing,
|
||||||
|
})}`
|
||||||
);
|
);
|
||||||
}, this.settings.inactivityCheckInterval || 60000);
|
}, this.settings.inactivityCheckInterval || 60000);
|
||||||
|
|
||||||
@ -1268,12 +1481,12 @@ export class PortProxy {
|
|||||||
* Gracefully shut down the proxy
|
* Gracefully shut down the proxy
|
||||||
*/
|
*/
|
||||||
public async stop() {
|
public async stop() {
|
||||||
console.log("PortProxy shutting down...");
|
console.log('PortProxy shutting down...');
|
||||||
this.isShuttingDown = true;
|
this.isShuttingDown = true;
|
||||||
|
|
||||||
// Stop accepting new connections
|
// Stop accepting new connections
|
||||||
const closeServerPromises: Promise<void>[] = this.netServers.map(
|
const closeServerPromises: Promise<void>[] = this.netServers.map(
|
||||||
server =>
|
(server) =>
|
||||||
new Promise<void>((resolve) => {
|
new Promise<void>((resolve) => {
|
||||||
if (!server.listening) {
|
if (!server.listening) {
|
||||||
resolve();
|
resolve();
|
||||||
@ -1296,7 +1509,7 @@ export class PortProxy {
|
|||||||
|
|
||||||
// Wait for servers to close
|
// Wait for servers to close
|
||||||
await Promise.all(closeServerPromises);
|
await Promise.all(closeServerPromises);
|
||||||
console.log("All servers closed. Cleaning up active connections...");
|
console.log('All servers closed. Cleaning up active connections...');
|
||||||
|
|
||||||
// Force destroy all active connections immediately
|
// Force destroy all active connections immediately
|
||||||
const connectionIds = [...this.connectionRecords.keys()];
|
const connectionIds = [...this.connectionRecords.keys()];
|
||||||
@ -1328,7 +1541,7 @@ export class PortProxy {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Short delay to allow graceful ends to process
|
// Short delay to allow graceful ends to process
|
||||||
await new Promise(resolve => setTimeout(resolve, 100));
|
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||||
|
|
||||||
// Second pass: Force destroy everything
|
// Second pass: Force destroy everything
|
||||||
for (const id of connectionIds) {
|
for (const id of connectionIds) {
|
||||||
@ -1365,9 +1578,9 @@ export class PortProxy {
|
|||||||
// Reset termination stats
|
// Reset termination stats
|
||||||
this.terminationStats = {
|
this.terminationStats = {
|
||||||
incoming: {},
|
incoming: {},
|
||||||
outgoing: {}
|
outgoing: {},
|
||||||
};
|
};
|
||||||
|
|
||||||
console.log("PortProxy shutdown complete.");
|
console.log('PortProxy shutdown complete.');
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,33 +1,351 @@
|
|||||||
import * as plugins from './plugins.js';
|
import * as http from 'http';
|
||||||
|
import * as url from 'url';
|
||||||
|
import * as tsclass from '@tsclass/tsclass';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Optional path pattern configuration that can be added to proxy configs
|
||||||
|
*/
|
||||||
|
export interface IPathPatternConfig {
|
||||||
|
pathPattern?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Interface for router result with additional metadata
|
||||||
|
*/
|
||||||
|
export interface IRouterResult {
|
||||||
|
config: tsclass.network.IReverseProxyConfig;
|
||||||
|
pathMatch?: string;
|
||||||
|
pathParams?: Record<string, string>;
|
||||||
|
pathRemainder?: string;
|
||||||
|
}
|
||||||
|
|
||||||
export class ProxyRouter {
|
export class ProxyRouter {
|
||||||
public reverseProxyConfigs: plugins.tsclass.network.IReverseProxyConfig[] = [];
|
// Store original configs for reference
|
||||||
|
private reverseProxyConfigs: tsclass.network.IReverseProxyConfig[] = [];
|
||||||
|
// Default config to use when no match is found (optional)
|
||||||
|
private defaultConfig?: tsclass.network.IReverseProxyConfig;
|
||||||
|
// Store path patterns separately since they're not in the original interface
|
||||||
|
private pathPatterns: Map<tsclass.network.IReverseProxyConfig, string> = new Map();
|
||||||
|
// Logger interface
|
||||||
|
private logger: {
|
||||||
|
error: (message: string, data?: any) => void;
|
||||||
|
warn: (message: string, data?: any) => void;
|
||||||
|
info: (message: string, data?: any) => void;
|
||||||
|
debug: (message: string, data?: any) => void;
|
||||||
|
};
|
||||||
|
|
||||||
/**
|
constructor(
|
||||||
* sets a new set of reverse configs to be routed to
|
configs?: tsclass.network.IReverseProxyConfig[],
|
||||||
* @param reverseCandidatesArg
|
logger?: {
|
||||||
*/
|
error: (message: string, data?: any) => void;
|
||||||
public setNewProxyConfigs(reverseCandidatesArg: plugins.tsclass.network.IReverseProxyConfig[]) {
|
warn: (message: string, data?: any) => void;
|
||||||
this.reverseProxyConfigs = reverseCandidatesArg;
|
info: (message: string, data?: any) => void;
|
||||||
|
debug: (message: string, data?: any) => void;
|
||||||
|
}
|
||||||
|
) {
|
||||||
|
this.logger = logger || console;
|
||||||
|
if (configs) {
|
||||||
|
this.setNewProxyConfigs(configs);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* routes a request
|
* Sets a new set of reverse configs to be routed to
|
||||||
|
* @param reverseCandidatesArg Array of reverse proxy configurations
|
||||||
*/
|
*/
|
||||||
public routeReq(req: plugins.http.IncomingMessage): plugins.tsclass.network.IReverseProxyConfig {
|
public setNewProxyConfigs(reverseCandidatesArg: tsclass.network.IReverseProxyConfig[]): void {
|
||||||
|
this.reverseProxyConfigs = [...reverseCandidatesArg];
|
||||||
|
|
||||||
|
// Find default config if any (config with "*" as hostname)
|
||||||
|
this.defaultConfig = this.reverseProxyConfigs.find(config => config.hostName === '*');
|
||||||
|
|
||||||
|
this.logger.info(`Router initialized with ${this.reverseProxyConfigs.length} configs (${this.getHostnames().length} unique hosts)`);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Routes a request based on hostname and path
|
||||||
|
* @param req The incoming HTTP request
|
||||||
|
* @returns The matching proxy config or undefined if no match found
|
||||||
|
*/
|
||||||
|
public routeReq(req: http.IncomingMessage): tsclass.network.IReverseProxyConfig {
|
||||||
|
const result = this.routeReqWithDetails(req);
|
||||||
|
return result ? result.config : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Routes a request with detailed matching information
|
||||||
|
* @param req The incoming HTTP request
|
||||||
|
* @returns Detailed routing result including matched config and path information
|
||||||
|
*/
|
||||||
|
public routeReqWithDetails(req: http.IncomingMessage): IRouterResult | undefined {
|
||||||
|
// Extract and validate host header
|
||||||
const originalHost = req.headers.host;
|
const originalHost = req.headers.host;
|
||||||
if (!originalHost) {
|
if (!originalHost) {
|
||||||
console.error('No host header found in request');
|
this.logger.error('No host header found in request');
|
||||||
|
return this.defaultConfig ? { config: this.defaultConfig } : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse URL for path matching
|
||||||
|
const parsedUrl = url.parse(req.url || '/');
|
||||||
|
const urlPath = parsedUrl.pathname || '/';
|
||||||
|
|
||||||
|
// Extract hostname without port
|
||||||
|
const hostWithoutPort = originalHost.split(':')[0].toLowerCase();
|
||||||
|
|
||||||
|
// First try exact hostname match
|
||||||
|
const exactConfig = this.findConfigForHost(hostWithoutPort, urlPath);
|
||||||
|
if (exactConfig) {
|
||||||
|
return exactConfig;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Try wildcard subdomain
|
||||||
|
if (hostWithoutPort.includes('.')) {
|
||||||
|
const domainParts = hostWithoutPort.split('.');
|
||||||
|
if (domainParts.length > 2) {
|
||||||
|
const wildcardDomain = `*.${domainParts.slice(1).join('.')}`;
|
||||||
|
const wildcardConfig = this.findConfigForHost(wildcardDomain, urlPath);
|
||||||
|
if (wildcardConfig) {
|
||||||
|
return wildcardConfig;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Fall back to default config if available
|
||||||
|
if (this.defaultConfig) {
|
||||||
|
this.logger.warn(`No specific config found for host: ${hostWithoutPort}, using default`);
|
||||||
|
return { config: this.defaultConfig };
|
||||||
|
}
|
||||||
|
|
||||||
|
this.logger.error(`No config found for host: ${hostWithoutPort}`);
|
||||||
return undefined;
|
return undefined;
|
||||||
}
|
}
|
||||||
// Strip port from host if present
|
|
||||||
const hostWithoutPort = originalHost.split(':')[0];
|
/**
|
||||||
const correspodingReverseProxyConfig = this.reverseProxyConfigs.find((reverseConfig) => {
|
* Find a config for a specific host and path
|
||||||
return reverseConfig.hostName === hostWithoutPort;
|
*/
|
||||||
|
private findConfigForHost(hostname: string, path: string): IRouterResult | undefined {
|
||||||
|
// Find all configs for this hostname
|
||||||
|
const configs = this.reverseProxyConfigs.filter(
|
||||||
|
config => config.hostName.toLowerCase() === hostname.toLowerCase()
|
||||||
|
);
|
||||||
|
|
||||||
|
if (configs.length === 0) {
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
// First try configs with path patterns
|
||||||
|
const configsWithPaths = configs.filter(config => this.pathPatterns.has(config));
|
||||||
|
|
||||||
|
// Sort by path pattern specificity - more specific first
|
||||||
|
configsWithPaths.sort((a, b) => {
|
||||||
|
const aPattern = this.pathPatterns.get(a) || '';
|
||||||
|
const bPattern = this.pathPatterns.get(b) || '';
|
||||||
|
|
||||||
|
// Exact patterns come before wildcard patterns
|
||||||
|
const aHasWildcard = aPattern.includes('*');
|
||||||
|
const bHasWildcard = bPattern.includes('*');
|
||||||
|
|
||||||
|
if (aHasWildcard && !bHasWildcard) return 1;
|
||||||
|
if (!aHasWildcard && bHasWildcard) return -1;
|
||||||
|
|
||||||
|
// Longer patterns are considered more specific
|
||||||
|
return bPattern.length - aPattern.length;
|
||||||
});
|
});
|
||||||
if (!correspodingReverseProxyConfig) {
|
|
||||||
console.error(`No config found for host: ${hostWithoutPort}`);
|
// Check each config with path pattern
|
||||||
}
|
for (const config of configsWithPaths) {
|
||||||
return correspodingReverseProxyConfig;
|
const pathPattern = this.pathPatterns.get(config);
|
||||||
|
if (pathPattern) {
|
||||||
|
const pathMatch = this.matchPath(path, pathPattern);
|
||||||
|
if (pathMatch) {
|
||||||
|
return {
|
||||||
|
config,
|
||||||
|
pathMatch: pathMatch.matched,
|
||||||
|
pathParams: pathMatch.params,
|
||||||
|
pathRemainder: pathMatch.remainder
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If no path pattern matched, use the first config without a path pattern
|
||||||
|
const configWithoutPath = configs.find(config => !this.pathPatterns.has(config));
|
||||||
|
if (configWithoutPath) {
|
||||||
|
return { config: configWithoutPath };
|
||||||
|
}
|
||||||
|
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Matches a URL path against a pattern
|
||||||
|
* Supports:
|
||||||
|
* - Exact matches: /users/profile
|
||||||
|
* - Wildcards: /api/* (matches any path starting with /api/)
|
||||||
|
* - Path parameters: /users/:id (captures id as a parameter)
|
||||||
|
*
|
||||||
|
* @param path The URL path to match
|
||||||
|
* @param pattern The pattern to match against
|
||||||
|
* @returns Match result with params and remainder, or null if no match
|
||||||
|
*/
|
||||||
|
private matchPath(path: string, pattern: string): {
|
||||||
|
matched: string;
|
||||||
|
params: Record<string, string>;
|
||||||
|
remainder: string;
|
||||||
|
} | null {
|
||||||
|
// Handle exact match
|
||||||
|
if (path === pattern) {
|
||||||
|
return {
|
||||||
|
matched: pattern,
|
||||||
|
params: {},
|
||||||
|
remainder: ''
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle wildcard match
|
||||||
|
if (pattern.endsWith('/*')) {
|
||||||
|
const prefix = pattern.slice(0, -2);
|
||||||
|
if (path === prefix || path.startsWith(`${prefix}/`)) {
|
||||||
|
return {
|
||||||
|
matched: prefix,
|
||||||
|
params: {},
|
||||||
|
remainder: path.slice(prefix.length)
|
||||||
|
};
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle path parameters
|
||||||
|
const patternParts = pattern.split('/').filter(p => p);
|
||||||
|
const pathParts = path.split('/').filter(p => p);
|
||||||
|
|
||||||
|
// Too few path parts to match
|
||||||
|
if (pathParts.length < patternParts.length) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const params: Record<string, string> = {};
|
||||||
|
|
||||||
|
// Compare each part
|
||||||
|
for (let i = 0; i < patternParts.length; i++) {
|
||||||
|
const patternPart = patternParts[i];
|
||||||
|
const pathPart = pathParts[i];
|
||||||
|
|
||||||
|
// Handle parameter
|
||||||
|
if (patternPart.startsWith(':')) {
|
||||||
|
const paramName = patternPart.slice(1);
|
||||||
|
params[paramName] = pathPart;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle wildcard at the end
|
||||||
|
if (patternPart === '*' && i === patternParts.length - 1) {
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Handle exact match for this part
|
||||||
|
if (patternPart !== pathPart) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Calculate the remainder - the unmatched path parts
|
||||||
|
const remainderParts = pathParts.slice(patternParts.length);
|
||||||
|
const remainder = remainderParts.length ? '/' + remainderParts.join('/') : '';
|
||||||
|
|
||||||
|
// Calculate the matched path
|
||||||
|
const matchedParts = patternParts.map((part, i) => {
|
||||||
|
return part.startsWith(':') ? pathParts[i] : part;
|
||||||
|
});
|
||||||
|
const matched = '/' + matchedParts.join('/');
|
||||||
|
|
||||||
|
return {
|
||||||
|
matched,
|
||||||
|
params,
|
||||||
|
remainder
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets all currently active proxy configurations
|
||||||
|
* @returns Array of all active configurations
|
||||||
|
*/
|
||||||
|
public getProxyConfigs(): tsclass.network.IReverseProxyConfig[] {
|
||||||
|
return [...this.reverseProxyConfigs];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Gets all hostnames that this router is configured to handle
|
||||||
|
* @returns Array of hostnames
|
||||||
|
*/
|
||||||
|
public getHostnames(): string[] {
|
||||||
|
const hostnames = new Set<string>();
|
||||||
|
for (const config of this.reverseProxyConfigs) {
|
||||||
|
if (config.hostName !== '*') {
|
||||||
|
hostnames.add(config.hostName.toLowerCase());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return Array.from(hostnames);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a single new proxy configuration
|
||||||
|
* @param config The configuration to add
|
||||||
|
* @param pathPattern Optional path pattern for route matching
|
||||||
|
*/
|
||||||
|
public addProxyConfig(
|
||||||
|
config: tsclass.network.IReverseProxyConfig,
|
||||||
|
pathPattern?: string
|
||||||
|
): void {
|
||||||
|
this.reverseProxyConfigs.push(config);
|
||||||
|
|
||||||
|
// Store path pattern if provided
|
||||||
|
if (pathPattern) {
|
||||||
|
this.pathPatterns.set(config, pathPattern);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sets a path pattern for an existing config
|
||||||
|
* @param config The existing configuration
|
||||||
|
* @param pathPattern The path pattern to set
|
||||||
|
* @returns Boolean indicating if the config was found and updated
|
||||||
|
*/
|
||||||
|
public setPathPattern(
|
||||||
|
config: tsclass.network.IReverseProxyConfig,
|
||||||
|
pathPattern: string
|
||||||
|
): boolean {
|
||||||
|
const exists = this.reverseProxyConfigs.includes(config);
|
||||||
|
if (exists) {
|
||||||
|
this.pathPatterns.set(config, pathPattern);
|
||||||
|
return true;
|
||||||
|
}
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Removes a proxy configuration by hostname
|
||||||
|
* @param hostname The hostname to remove
|
||||||
|
* @returns Boolean indicating whether any configs were removed
|
||||||
|
*/
|
||||||
|
public removeProxyConfig(hostname: string): boolean {
|
||||||
|
const initialCount = this.reverseProxyConfigs.length;
|
||||||
|
|
||||||
|
// Find configs to remove
|
||||||
|
const configsToRemove = this.reverseProxyConfigs.filter(
|
||||||
|
config => config.hostName === hostname
|
||||||
|
);
|
||||||
|
|
||||||
|
// Remove them from the patterns map
|
||||||
|
for (const config of configsToRemove) {
|
||||||
|
this.pathPatterns.delete(config);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Filter them out of the configs array
|
||||||
|
this.reverseProxyConfigs = this.reverseProxyConfigs.filter(
|
||||||
|
config => config.hostName !== hostname
|
||||||
|
);
|
||||||
|
|
||||||
|
return this.reverseProxyConfigs.length !== initialCount;
|
||||||
}
|
}
|
||||||
}
|
}
|
@ -1,11 +1,13 @@
|
|||||||
// node native scope
|
// node native scope
|
||||||
|
import { EventEmitter } from 'events';
|
||||||
import * as http from 'http';
|
import * as http from 'http';
|
||||||
import * as https from 'https';
|
import * as https from 'https';
|
||||||
import * as net from 'net';
|
import * as net from 'net';
|
||||||
import * as tls from 'tls';
|
import * as tls from 'tls';
|
||||||
import * as url from 'url';
|
import * as url from 'url';
|
||||||
|
|
||||||
export { http, https, net, tls, url };
|
|
||||||
|
export { EventEmitter, http, https, net, tls, url };
|
||||||
|
|
||||||
// tsclass scope
|
// tsclass scope
|
||||||
import * as tsclass from '@tsclass/tsclass';
|
import * as tsclass from '@tsclass/tsclass';
|
||||||
@ -22,9 +24,10 @@ import * as smartstring from '@push.rocks/smartstring';
|
|||||||
export { lik, smartdelay, smartrequest, smartpromise, smartstring };
|
export { lik, smartdelay, smartrequest, smartpromise, smartstring };
|
||||||
|
|
||||||
// third party scope
|
// third party scope
|
||||||
|
import * as acme from 'acme-client';
|
||||||
import prettyMs from 'pretty-ms';
|
import prettyMs from 'pretty-ms';
|
||||||
import * as ws from 'ws';
|
import * as ws from 'ws';
|
||||||
import wsDefault from 'ws';
|
import wsDefault from 'ws';
|
||||||
import { minimatch } from 'minimatch';
|
import { minimatch } from 'minimatch';
|
||||||
|
|
||||||
export { prettyMs, ws, wsDefault, minimatch };
|
export { acme, prettyMs, ws, wsDefault, minimatch };
|
||||||
|
Reference in New Issue
Block a user