fix(connection): improve connection handling and timeouts

This commit is contained in:
2026-02-26 16:58:30 +00:00
parent 697d51a9d4
commit 94266222fe
5 changed files with 46 additions and 12 deletions

View File

@@ -18,8 +18,8 @@ export class ProtocolDetector {
private fragmentManager: DetectionFragmentManager;
private tlsDetector: TlsDetector;
private httpDetector: HttpDetector;
private connectionProtocols: Map<string, 'tls' | 'http'> = new Map();
private connectionProtocols: Map<string, { protocol: 'tls' | 'http'; createdAt: number }> = new Map();
constructor() {
this.fragmentManager = new DetectionFragmentManager();
this.tlsDetector = new TlsDetector();
@@ -124,8 +124,9 @@ export class ProtocolDetector {
const connectionId = DetectionFragmentManager.createConnectionId(context);
// Check if we already know the protocol for this connection
const knownProtocol = this.connectionProtocols.get(connectionId);
const knownEntry = this.connectionProtocols.get(connectionId);
const knownProtocol = knownEntry?.protocol;
if (knownProtocol === 'http') {
const result = this.httpDetector.detectWithContext(buffer, context, options);
if (result) {
@@ -163,7 +164,7 @@ export class ProtocolDetector {
if (!knownProtocol) {
// First peek to determine protocol type
if (this.tlsDetector.canHandle(buffer)) {
this.connectionProtocols.set(connectionId, 'tls');
this.connectionProtocols.set(connectionId, { protocol: 'tls', createdAt: Date.now() });
// Handle TLS with fragment accumulation
const handler = this.fragmentManager.getHandler('tls');
const fragmentResult = handler.addFragment(connectionId, buffer);
@@ -189,7 +190,7 @@ export class ProtocolDetector {
}
if (this.httpDetector.canHandle(buffer)) {
this.connectionProtocols.set(connectionId, 'http');
this.connectionProtocols.set(connectionId, { protocol: 'http', createdAt: Date.now() });
const result = this.httpDetector.detectWithContext(buffer, context, options);
if (result) {
if (result.isComplete) {
@@ -221,6 +222,14 @@ export class ProtocolDetector {
private cleanupInstance(): void {
this.fragmentManager.cleanup();
// Remove stale connectionProtocols entries (abandoned handshakes, port scanners)
const maxAge = 30_000; // 30 seconds
const now = Date.now();
for (const [id, entry] of this.connectionProtocols) {
if (now - entry.createdAt > maxAge) {
this.connectionProtocols.delete(id);
}
}
}
/**
@@ -242,8 +251,7 @@ export class ProtocolDetector {
* @param _maxAge Maximum age in milliseconds (default: 30 seconds)
*/
static cleanupConnections(_maxAge: number = 30000): void {
// Cleanup is now handled internally by the fragment manager
this.getInstance().fragmentManager.cleanup();
this.getInstance().cleanupInstance();
}
/**