Handle port correctly

This commit is contained in:
Owen 2025-02-21 12:52:24 -05:00
parent a57d32d05d
commit 757d628bc8
No known key found for this signature in database
GPG key ID: 8271FDFFD9E0CCBD
3 changed files with 30 additions and 1 deletions

View file

@ -41,7 +41,7 @@ export const handleGetConfigMessage: MessageHandler = async (context) => {
return;
}
const { publicKey, endpoint, listenPort } = message.data as Input;
const { publicKey, endpoint } = message.data as Input;
const siteId = newt.siteId;
@ -58,6 +58,7 @@ export const handleGetConfigMessage: MessageHandler = async (context) => {
let site: Site | undefined;
if (!site) {
const address = await getNextAvailableSubnet();
const listenPort = await getNextAvailablePort();
// create a new exit node
const [updateRes] = await db
@ -146,3 +147,24 @@ async function getNextAvailableSubnet(): Promise<string> {
subnet.split("/")[1];
return subnet;
}
async function getNextAvailablePort(): Promise<number> {
// Get all existing ports from exitNodes table
const existingPorts = await db.select({
listenPort: sites.listenPort,
}).from(sites);
// Find the first available port between 1024 and 65535
let nextPort = config.getRawConfig().wg_site.start_port;
for (const port of existingPorts) {
if (port.listenPort && port.listenPort > nextPort) {
break;
}
nextPort++;
if (nextPort > 65535) {
throw new Error('No available ports remaining in space');
}
}
return nextPort;
}