mirror of
https://github.com/fosrl/pangolin.git
synced 2026-03-04 01:36:39 +00:00
Properly generate all wireguard options
This commit is contained in:
@@ -50,6 +50,7 @@ authenticated.get("/site/:siteId", verifySiteAccess, site.getSite);
|
||||
authenticated.get("/site/:siteId/roles", verifySiteAccess, site.listSiteRoles);
|
||||
authenticated.post("/site/:siteId", verifySiteAccess, site.updateSite);
|
||||
authenticated.delete("/site/:siteId", verifySiteAccess, site.deleteSite);
|
||||
authenticated.delete("/site/pickSiteDefaults", site.pickSiteDefaults);
|
||||
|
||||
authenticated.put(
|
||||
"/org/:orgId/site/:siteId/resource",
|
||||
|
||||
@@ -1,14 +1,15 @@
|
||||
import { Request, Response, NextFunction } from 'express';
|
||||
import { z } from 'zod';
|
||||
import { sites, resources, targets, exitNodes, routes } from '@server/db/schema';
|
||||
import { sites, resources, targets, exitNodes } from '@server/db/schema';
|
||||
import { db } from '@server/db';
|
||||
import { eq } from 'drizzle-orm';
|
||||
import response from "@server/utils/response";
|
||||
import HttpCode from '@server/types/HttpCode';
|
||||
import createHttpError from 'http-errors';
|
||||
import logger from '@server/logger';
|
||||
import stoi from '@server/utils/stoi';
|
||||
|
||||
import config from "@server/config";
|
||||
import { getUniqueExitNodeEndpointName } from '@server/db/names';
|
||||
import { findNextAvailableCidr } from "@server/utils/ip";
|
||||
// Define Zod schema for request validation
|
||||
const getConfigSchema = z.object({
|
||||
publicKey: z.string(),
|
||||
@@ -47,19 +48,19 @@ export async function getConfig(req: Request, res: Response, next: NextFunction)
|
||||
|
||||
if (!exitNode) {
|
||||
const address = await getNextAvailableSubnet();
|
||||
const listenPort = await getNextAvailablePort();
|
||||
const subEndpoint = await getUniqueExitNodeEndpointName();
|
||||
|
||||
// create a new exit node
|
||||
exitNode = await db.insert(exitNodes).values({
|
||||
publicKey,
|
||||
endpoint: `${subEndpoint}.${config.gerbil.base_endpoint}`,
|
||||
address,
|
||||
listenPort: 51820,
|
||||
listenPort,
|
||||
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();
|
||||
logger.info(`Created new exit node ${exitNode[0].name} with address ${exitNode[0].address} and port ${exitNode[0].listenPort}`);
|
||||
}
|
||||
|
||||
if (!exitNode) {
|
||||
@@ -68,7 +69,7 @@ export async function getConfig(req: Request, res: Response, next: NextFunction)
|
||||
|
||||
// Fetch sites for this exit node
|
||||
const sitesRes = await db.query.sites.findMany({
|
||||
where: eq(sites.exitNode, exitNode[0].exitNodeId),
|
||||
where: eq(sites.exitNodeId, exitNode[0].exitNodeId),
|
||||
});
|
||||
|
||||
const peers = await Promise.all(sitesRes.map(async (site) => {
|
||||
@@ -91,14 +92,14 @@ export async function getConfig(req: Request, res: Response, next: NextFunction)
|
||||
};
|
||||
}));
|
||||
|
||||
const config: GetConfigResponse = {
|
||||
const configResponse: GetConfigResponse = {
|
||||
listenPort: exitNode[0].listenPort || 51820,
|
||||
ipAddress: exitNode[0].address,
|
||||
peers,
|
||||
};
|
||||
|
||||
return response(res, {
|
||||
data: config,
|
||||
data: configResponse,
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Configuration retrieved successfully",
|
||||
@@ -113,31 +114,35 @@ export async function getConfig(req: Request, res: Response, next: NextFunction)
|
||||
|
||||
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));
|
||||
const existingAddresses = await db.select({
|
||||
address: exitNodes.address,
|
||||
}).from(exitNodes);
|
||||
|
||||
// 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]);
|
||||
})
|
||||
);
|
||||
const addresses = existingAddresses.map(a => a.address);
|
||||
const subnet = findNextAvailableCidr(addresses, config.gerbil.block_size, config.gerbil.subnet_group);
|
||||
if (!subnet) {
|
||||
throw new Error('No available subnets remaining in space');
|
||||
}
|
||||
return subnet;
|
||||
}
|
||||
|
||||
// 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');
|
||||
async function getNextAvailablePort(): Promise<number> {
|
||||
// Get all existing ports from exitNodes table
|
||||
const existingPorts = await db.select({
|
||||
listenPort: exitNodes.listenPort,
|
||||
}).from(exitNodes);
|
||||
|
||||
// Find the first available port between 1024 and 65535
|
||||
let nextPort = config.gerbil.start_port;
|
||||
for (const port of existingPorts) {
|
||||
if (port.listenPort > nextPort) {
|
||||
break;
|
||||
}
|
||||
nextPort++;
|
||||
if (nextPort > 65535) {
|
||||
throw new Error('No available ports remaining in space');
|
||||
}
|
||||
}
|
||||
|
||||
return `10.${nextOctet}.0.0/16`;
|
||||
}
|
||||
return nextPort;
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import fetch from 'node-fetch';
|
||||
import { ActionsEnum, checkUserActionPermission } from '@server/auth/actions';
|
||||
import logger from '@server/logger';
|
||||
import { eq, and } from 'drizzle-orm';
|
||||
import { getUniqueName } from '@server/db/names';
|
||||
import { getUniqueSiteName } from '@server/db/names';
|
||||
|
||||
const API_BASE_URL = "http://localhost:3000";
|
||||
|
||||
@@ -20,9 +20,10 @@ const createSiteParamsSchema = z.object({
|
||||
// Define Zod schema for request body validation
|
||||
const createSiteSchema = z.object({
|
||||
name: z.string().min(1).max(255),
|
||||
exitNodeId: z.number().int().positive(),
|
||||
subdomain: z.string().min(1).max(255).optional(),
|
||||
pubKey: z.string().optional(),
|
||||
subnet: z.string().optional(),
|
||||
pubKey: z.string(),
|
||||
subnet: z.string(),
|
||||
});
|
||||
|
||||
export type CreateSiteResponse = {
|
||||
@@ -48,7 +49,7 @@ export async function createSite(req: Request, res: Response, next: NextFunction
|
||||
);
|
||||
}
|
||||
|
||||
const { name, subdomain, pubKey, subnet } = parsedBody.data;
|
||||
const { name, subdomain, exitNodeId, pubKey, subnet } = parsedBody.data;
|
||||
|
||||
// Validate request params
|
||||
const parsedParams = createSiteParamsSchema.safeParse(req.params);
|
||||
@@ -73,13 +74,12 @@ export async function createSite(req: Request, res: Response, next: NextFunction
|
||||
return next(createHttpError(HttpCode.FORBIDDEN, 'User does not have a role'));
|
||||
}
|
||||
|
||||
const niceId = await getUniqueName(orgId);
|
||||
|
||||
// TODO: pick a subnet
|
||||
const niceId = await getUniqueSiteName(orgId);
|
||||
|
||||
// Create new site in the database
|
||||
const [newSite] = await db.insert(sites).values({
|
||||
orgId,
|
||||
exitNodeId,
|
||||
name,
|
||||
niceId,
|
||||
pubKey,
|
||||
|
||||
@@ -3,4 +3,5 @@ export * from "./createSite";
|
||||
export * from "./deleteSite";
|
||||
export * from "./updateSite";
|
||||
export * from "./listSites";
|
||||
export * from "./listSiteRoles";
|
||||
export * from "./listSiteRoles"
|
||||
export * from "./pickSiteDefaults";
|
||||
105
server/routers/site/pickSiteDefaults.ts
Normal file
105
server/routers/site/pickSiteDefaults.ts
Normal file
@@ -0,0 +1,105 @@
|
||||
import { Request, Response, NextFunction } from "express";
|
||||
import { z } from "zod";
|
||||
import { db } from "@server/db";
|
||||
import { exitNodes, Org, orgs, sites } from "@server/db/schema";
|
||||
import { eq } from "drizzle-orm";
|
||||
import response from "@server/utils/response";
|
||||
import HttpCode from "@server/types/HttpCode";
|
||||
import createHttpError from "http-errors";
|
||||
import { ActionsEnum, checkUserActionPermission } from "@server/auth/actions";
|
||||
import logger from "@server/logger";
|
||||
import { findNextAvailableCidr } from "@server/utils/ip";
|
||||
|
||||
export type PickSiteDefaultsResponse = {
|
||||
exitNodeId: number;
|
||||
address: string;
|
||||
publicKey: string;
|
||||
name: string;
|
||||
listenPort: number;
|
||||
endpoint: string;
|
||||
subnet: string;
|
||||
}
|
||||
|
||||
export async function pickSiteDefaults(
|
||||
req: Request,
|
||||
res: Response,
|
||||
next: NextFunction,
|
||||
): Promise<any> {
|
||||
try {
|
||||
|
||||
// Check if the user has permission to list sites
|
||||
const hasPermission = await checkUserActionPermission(
|
||||
ActionsEnum.createSite,
|
||||
req,
|
||||
);
|
||||
if (!hasPermission) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.FORBIDDEN,
|
||||
"User does not have permission to perform this action",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// TODO: more intelligent way to pick the exit node
|
||||
|
||||
// make sure there is an exit node by counting the exit nodes table
|
||||
const nodes = await db.select().from(exitNodes);
|
||||
if (nodes.length === 0) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.NOT_FOUND,
|
||||
"No exit nodes available",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
// get the first exit node
|
||||
const exitNode = nodes[0];
|
||||
|
||||
// TODO: this probably can be optimized...
|
||||
// list all of the sites on that exit node
|
||||
const sitesQuery = await db.select({
|
||||
subnet: sites.subnet
|
||||
})
|
||||
.from(sites)
|
||||
.where(eq(sites.exitNodeId, exitNode.exitNodeId));
|
||||
|
||||
// TODO: we need to lock this subnet for some time so someone else does not take it
|
||||
const subnets = sitesQuery.map((site) => site.subnet);
|
||||
const newSubnet = findNextAvailableCidr(subnets, 28, exitNode.address);
|
||||
if (!newSubnet) {
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.INTERNAL_SERVER_ERROR,
|
||||
"No available subnets",
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
return response<PickSiteDefaultsResponse>(res, {
|
||||
data: {
|
||||
exitNodeId: exitNode.exitNodeId,
|
||||
address: exitNode.address,
|
||||
publicKey: exitNode.publicKey,
|
||||
name: exitNode.name,
|
||||
listenPort: exitNode.listenPort,
|
||||
endpoint: exitNode.endpoint,
|
||||
subnet: newSubnet,
|
||||
},
|
||||
success: true,
|
||||
error: false,
|
||||
message: "Organization retrieved successfully",
|
||||
status: HttpCode.OK,
|
||||
});
|
||||
} catch (error) {
|
||||
logger.error(error);
|
||||
return next(
|
||||
createHttpError(
|
||||
HttpCode.INTERNAL_SERVER_ERROR,
|
||||
"An error occurred...",
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user