Add host setup functions and client components
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
import type {
|
||||
BUN_SQLITE_WGUI_CLIENTS,
|
||||
BUN_SQLITE_WGUI_HOSTS,
|
||||
BUN_SQLITE_WGUI_VARIABLES,
|
||||
} from "@/db/types/db";
|
||||
import type { APIResponseObject } from "@moduletrace/bunext/types";
|
||||
import BunSQLite from "@moduletrace/bun-sqlite";
|
||||
import type { TableType } from "@/src/types";
|
||||
|
||||
type Params = {
|
||||
host?: BUN_SQLITE_WGUI_HOSTS;
|
||||
};
|
||||
|
||||
/**
|
||||
* Function to grab the next available client
|
||||
* private IP address within the host's subnet.
|
||||
* Checks the clients records and increments
|
||||
* the last octet of the last client
|
||||
* @param param0
|
||||
*/
|
||||
export default async function grabNextAvailableClientIPAddress({
|
||||
host,
|
||||
}: Params): Promise<APIResponseObject> {
|
||||
const variables_res = await BunSQLite.select<
|
||||
BUN_SQLITE_WGUI_VARIABLES,
|
||||
TableType
|
||||
>({
|
||||
table: "variables",
|
||||
});
|
||||
|
||||
const variables = variables_res.payload;
|
||||
|
||||
const HOST_WG_IP =
|
||||
host?.wg_ip_address ||
|
||||
variables?.find((v) => v.key == "main_host_wg_ip_address")?.value;
|
||||
|
||||
if (!HOST_WG_IP) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `No Host Private IP address provided`,
|
||||
};
|
||||
}
|
||||
|
||||
const parts = HOST_WG_IP.split(".");
|
||||
|
||||
if (parts.length !== 4) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `Invalid Host Private IP address: ${HOST_WG_IP}`,
|
||||
};
|
||||
}
|
||||
|
||||
const host_last_octet = Number(parts[3]);
|
||||
|
||||
if (Number.isNaN(host_last_octet)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `Invalid Host Private IP address: ${HOST_WG_IP}`,
|
||||
};
|
||||
}
|
||||
|
||||
const subnet = `${parts[0]}.${parts[1]}.${parts[2]}.`;
|
||||
|
||||
const clients_res = await BunSQLite.select<
|
||||
BUN_SQLITE_WGUI_CLIENTS,
|
||||
TableType
|
||||
>({
|
||||
table: "clients",
|
||||
});
|
||||
|
||||
const clients = clients_res.payload || [];
|
||||
|
||||
let max_last_octet = host_last_octet;
|
||||
|
||||
for (const client of clients) {
|
||||
const client_ip = client?.wg_ip_address;
|
||||
|
||||
if (!client_ip || !client_ip.startsWith(subnet)) continue;
|
||||
|
||||
const client_last_octet = Number(client_ip.split(".")[3]);
|
||||
|
||||
if (Number.isNaN(client_last_octet)) continue;
|
||||
|
||||
if (client_last_octet > max_last_octet) {
|
||||
max_last_octet = client_last_octet;
|
||||
}
|
||||
}
|
||||
|
||||
const next_last_octet = max_last_octet + 1;
|
||||
|
||||
if (next_last_octet > 254) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `No available client IP address in subnet ${subnet}0/24`,
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
success: true,
|
||||
msg: `${subnet}${next_last_octet}`,
|
||||
};
|
||||
}
|
||||
Reference in New Issue
Block a user