/** * Port allocator for virtual host tunnel local ports. * Each virtual host gets a unique port on 127.0.0.1 starting at TUNNEL_PORT_BASE. * Released ports are recycled via a free list. */ const TUNNEL_PORT_BASE = 19000; let nextTunnelPortIndex = 0; const tunnelPortFreeList = []; /** * Allocate a unique local port for a virtual host tunnel. * Recycles ports from the free list before incrementing the counter. * @returns {number} An available port number >= TUNNEL_PORT_BASE. */ function allocateTunnelPort() { if (tunnelPortFreeList.length > 0) return tunnelPortFreeList.pop(); return TUNNEL_PORT_BASE + (nextTunnelPortIndex++); } /** * Return a port to the free list so it can be reused by a future allocation. * Silently ignores invalid ports and duplicate releases. * @param {number} port - The port to release. Must be >= TUNNEL_PORT_BASE. */ function releaseTunnelPort(port) { if (typeof port === 'number' && port >= TUNNEL_PORT_BASE && !tunnelPortFreeList.includes(port)) { tunnelPortFreeList.push(port); } } module.exports = { TUNNEL_PORT_BASE, allocateTunnelPort, releaseTunnelPort };