fosrl.pangolin/server/routers/gerbil/getConfig.ts

184 lines
5.6 KiB
TypeScript
Raw Normal View History

2025-06-04 12:02:07 -04:00
import { Request, Response, NextFunction } from "express";
import { z } from "zod";
import { sites, resources, targets, exitNodes } from "@server/db";
import { db } from "@server/db";
import { eq } from "drizzle-orm";
2025-01-01 21:41:31 -05:00
import response from "@server/lib/response";
2025-06-04 12:02:07 -04:00
import HttpCode from "@server/types/HttpCode";
import createHttpError from "http-errors";
import logger from "@server/logger";
2025-01-01 21:41:31 -05:00
import config from "@server/lib/config";
2025-06-04 12:02:07 -04:00
import { getUniqueExitNodeEndpointName } from "../../db/names";
2025-01-01 21:41:31 -05:00
import { findNextAvailableCidr } from "@server/lib/ip";
2025-06-04 12:02:07 -04:00
import { fromError } from "zod-validation-error";
import { getAllowedIps } from "../target/helpers";
2024-10-26 12:02:21 -04:00
// Define Zod schema for request validation
const getConfigSchema = z.object({
publicKey: z.string(),
2025-06-04 12:02:07 -04:00
reachableAt: z.string().optional()
2024-10-26 12:02:21 -04:00
});
2024-09-28 12:35:07 -04:00
2024-10-26 12:02:21 -04:00
export type GetConfigResponse = {
listenPort: number;
ipAddress: string;
peers: {
publicKey: string | null;
allowedIps: string[];
}[];
2025-06-04 12:02:07 -04:00
};
2024-10-26 12:02:21 -04:00
2025-06-04 12:02:07 -04:00
export async function getConfig(
req: Request,
res: Response,
next: NextFunction
): Promise<any> {
2024-09-28 17:10:03 -04:00
try {
2024-10-26 12:02:21 -04:00
// Validate request parameters
2024-10-26 17:02:11 -04:00
const parsedParams = getConfigSchema.safeParse(req.body);
2024-10-26 12:02:21 -04:00
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
2025-01-01 21:41:31 -05:00
fromError(parsedParams.error).toString()
2024-10-26 12:02:21 -04:00
)
);
}
const { publicKey, reachableAt } = parsedParams.data;
2024-10-26 12:02:21 -04:00
if (!publicKey) {
2025-06-04 12:02:07 -04:00
return next(
createHttpError(HttpCode.BAD_REQUEST, "publicKey is required")
);
2024-09-28 17:10:03 -04:00
}
2024-09-28 12:35:07 -04:00
2024-09-28 17:10:03 -04:00
// Fetch exit node
2025-06-04 12:02:07 -04:00
let exitNodeQuery = await db
.select()
.from(exitNodes)
.where(eq(exitNodes.publicKey, publicKey));
2024-10-26 17:02:11 -04:00
let exitNode;
if (exitNodeQuery.length === 0) {
2024-10-26 12:02:21 -04:00
const address = await getNextAvailableSubnet();
// TODO: eventually we will want to get the next available port so that we can multiple exit nodes
// const listenPort = await getNextAvailablePort();
const listenPort = config.getRawConfig().gerbil.start_port;
2024-11-24 11:05:47 -05:00
let subEndpoint = "";
if (config.getRawConfig().gerbil.use_subdomain) {
2024-11-24 11:05:47 -05:00
subEndpoint = await getUniqueExitNodeEndpointName();
}
2024-10-26 12:02:21 -04:00
// create a new exit node
2025-06-04 12:02:07 -04:00
exitNode = await db
.insert(exitNodes)
.values({
publicKey,
endpoint: `${subEndpoint}${subEndpoint != "" ? "." : ""}${config.getRawConfig().gerbil.base_endpoint}`,
address,
listenPort,
reachableAt,
name: `Exit Node ${publicKey.slice(0, 8)}`
})
.returning()
.execute();
logger.info(
`Created new exit node ${exitNode[0].name} with address ${exitNode[0].address} and port ${exitNode[0].listenPort}`
);
2024-10-26 17:02:11 -04:00
} else {
exitNode = exitNodeQuery;
2024-10-26 12:02:21 -04:00
}
if (!exitNode) {
2025-06-04 12:02:07 -04:00
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"Failed to create exit node"
)
);
2024-09-28 15:21:13 -04:00
}
2025-06-04 12:02:07 -04:00
const sitesRes = await db
.select()
.from(sites)
.where(eq(sites.exitNodeId, exitNode[0].exitNodeId));
2024-09-28 17:10:03 -04:00
2025-06-04 12:02:07 -04:00
const peers = await Promise.all(
sitesRes.map(async (site) => {
return {
publicKey: site.pubKey,
allowedIps: await getAllowedIps(site.siteId)
};
})
);
2024-09-28 17:10:03 -04:00
const configResponse: GetConfigResponse = {
2024-10-26 12:02:21 -04:00
listenPort: exitNode[0].listenPort || 51820,
ipAddress: exitNode[0].address,
2025-06-04 12:02:07 -04:00
peers
2024-09-28 17:10:03 -04:00
};
2024-10-26 17:02:11 -04:00
logger.debug("Sending config: ", configResponse);
2024-10-26 12:02:21 -04:00
2024-10-26 17:02:11 -04:00
return res.status(HttpCode.OK).send(configResponse);
2024-09-28 17:10:03 -04:00
} catch (error) {
2024-10-26 17:02:11 -04:00
logger.error(error);
2025-06-04 12:02:07 -04:00
return next(
createHttpError(
HttpCode.INTERNAL_SERVER_ERROR,
"An error occurred..."
)
);
2024-09-28 12:42:38 -04:00
}
2024-10-26 12:02:21 -04:00
}
async function getNextAvailableSubnet(): Promise<string> {
// Get all existing subnets from routes table
2025-06-04 12:02:07 -04:00
const existingAddresses = await db
.select({
address: exitNodes.address
})
.from(exitNodes);
const addresses = existingAddresses.map((a) => a.address);
let subnet = findNextAvailableCidr(
addresses,
config.getRawConfig().gerbil.block_size,
config.getRawConfig().gerbil.subnet_group
);
if (!subnet) {
2025-06-04 12:02:07 -04:00
throw new Error("No available subnets remaining in space");
}
2024-10-26 17:02:11 -04:00
// replace the last octet with 1
2025-06-04 12:02:07 -04:00
subnet =
subnet.split(".").slice(0, 3).join(".") +
".1" +
"/" +
subnet.split("/")[1];
return subnet;
}
async function getNextAvailablePort(): Promise<number> {
// Get all existing ports from exitNodes table
2025-06-04 12:02:07 -04:00
const existingPorts = await db
.select({
listenPort: exitNodes.listenPort
})
.from(exitNodes);
// Find the first available port between 1024 and 65535
let nextPort = config.getRawConfig().gerbil.start_port;
for (const port of existingPorts) {
if (port.listenPort > nextPort) {
break;
}
nextPort++;
if (nextPort > 65535) {
2025-06-04 12:02:07 -04:00
throw new Error("No available ports remaining in space");
2024-10-26 12:02:21 -04:00
}
}
2024-09-28 15:21:13 -04:00
return nextPort;
2025-01-01 21:41:31 -05:00
}