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

144 lines
4.7 KiB
TypeScript
Raw Normal View History

2024-09-28 12:35:07 -04:00
import { Request, Response, NextFunction } from 'express';
2024-10-26 12:02:21 -04:00
import { z } from 'zod';
import { sites, resources, targets, exitNodes, routes } from '@server/db/schema';
import { db } from '@server/db';
import { eq } from 'drizzle-orm';
import response from "@server/utils/response";
2024-10-06 18:05:20 -04:00
import HttpCode from '@server/types/HttpCode';
import createHttpError from 'http-errors';
2024-10-26 12:02:21 -04:00
import logger from '@server/logger';
import stoi from '@server/utils/stoi';
// Define Zod schema for request validation
const getConfigSchema = z.object({
publicKey: z.string(),
});
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[];
}[];
}
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
const parsedParams = getConfigSchema.safeParse(req.query);
if (!parsedParams.success) {
return next(
createHttpError(
HttpCode.BAD_REQUEST,
parsedParams.error.errors.map(e => e.message).join(', ')
)
);
}
const { publicKey } = parsedParams.data;
if (!publicKey) {
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
2024-10-26 12:02:21 -04:00
let exitNode = await db.select().from(exitNodes).where(eq(exitNodes.publicKey, publicKey));
2024-09-28 12:35:07 -04:00
2024-09-28 17:10:03 -04:00
if (!exitNode) {
2024-10-26 12:02:21 -04:00
const address = await getNextAvailableSubnet();
// create a new exit node
exitNode = await db.insert(exitNodes).values({
publicKey,
address,
listenPort: 51820,
name: `Exit Node ${publicKey.slice(0, 8)}`,
}).returning().execute();
// create a route
await db.insert(routes).values({
exitNodeId: exitNode[0].exitNodeId,
subnet: address,
}).returning().execute();
}
if (!exitNode) {
return next(createHttpError(HttpCode.INTERNAL_SERVER_ERROR, "Failed to create exit node"));
2024-09-28 15:21:13 -04:00
}
2024-09-28 17:10:03 -04:00
// Fetch sites for this exit node
const sitesRes = await db.query.sites.findMany({
2024-10-26 12:02:21 -04:00
where: eq(sites.exitNode, exitNode[0].exitNodeId),
2024-09-28 17:10:03 -04:00
});
const peers = await Promise.all(sitesRes.map(async (site) => {
// Fetch resources for this site
const resourcesRes = await db.query.resources.findMany({
where: eq(resources.siteId, site.siteId),
});
// Fetch targets for all resources of this site
const targetIps = await Promise.all(resourcesRes.map(async (resource) => {
const targetsRes = await db.query.targets.findMany({
where: eq(targets.resourceId, resource.resourceId),
});
return targetsRes.map(target => `${target.ip}/32`);
}));
return {
publicKey: site.pubKey,
allowedIps: targetIps.flat(),
};
}));
2024-10-26 12:02:21 -04:00
const config: GetConfigResponse = {
listenPort: exitNode[0].listenPort || 51820,
ipAddress: exitNode[0].address,
2024-09-28 17:10:03 -04:00
peers,
};
2024-10-26 12:02:21 -04:00
return response(res, {
data: config,
success: true,
error: false,
message: "Configuration retrieved successfully",
status: HttpCode.OK,
});
2024-09-28 17:10:03 -04:00
} catch (error) {
2024-10-26 12:02:21 -04:00
logger.error('Error from getConfig:', error);
2024-10-06 18:05:20 -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
const existingRoutes = await db.select({
subnet: routes.subnet
}).from(routes)
.innerJoin(exitNodes, eq(routes.exitNodeId, exitNodes.exitNodeId));
// Filter for only /16 subnets and extract the second octet
const usedSecondOctets = new Set(
existingRoutes
.map(route => route.subnet)
.filter(subnet => subnet.endsWith('/16'))
.filter(subnet => subnet.startsWith('10.'))
.map(subnet => {
const parts = subnet.split('.');
return parseInt(parts[1]);
})
);
// Find the first available number between 0 and 255
let nextOctet = 0;
while (usedSecondOctets.has(nextOctet)) {
nextOctet++;
if (nextOctet > 255) {
throw new Error('No available /16 subnets remaining in 10.0.0.0/8 space');
}
}
2024-09-28 15:21:13 -04:00
2024-10-26 12:02:21 -04:00
return `10.${nextOctet}.0.0/16`;
2024-09-28 17:10:03 -04:00
}