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

@ -32,6 +32,11 @@ gerbil:
site_block_size: 30
subnet_group: 100.89.137.0/20
wg_site:
start_port: 51820
block_size: 24
subnet_group: 100.89.137.0/20
rate_limits:
global:
window_minutes: 1

View file

@ -12,6 +12,7 @@ import {
} from "@server/lib/consts";
import { passwordSchema } from "@server/auth/passwordSchema";
import stoi from "./stoi";
import { start } from "repl";
const portSchema = z.number().positive().gt(0).lte(65535);
const hostnameSchema = z
@ -112,6 +113,7 @@ const configSchema = z.object({
wg_site: z.object({
block_size: z.number().positive().gt(0),
subnet_group: z.string(),
start_port: portSchema
}),
rate_limits: z.object({
global: z.object({

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;
}