2024-09-28 12:35:07 -04:00
|
|
|
import { Request, Response, NextFunction } from 'express';
|
2024-09-28 15:21:13 -04:00
|
|
|
import { DrizzleError, eq } from 'drizzle-orm';
|
2024-09-28 12:42:38 -04:00
|
|
|
import { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3';
|
|
|
|
import { sites, Site } from '../../db/schema';
|
2024-09-28 14:46:36 -04:00
|
|
|
import db from '../../db';
|
2024-09-28 12:35:07 -04:00
|
|
|
|
2024-09-28 12:42:38 -04:00
|
|
|
export const getConfig = async (req: Request, res: Response, next: NextFunction): Promise<void> => {
|
2024-09-28 12:35:07 -04:00
|
|
|
try {
|
2024-09-28 15:21:13 -04:00
|
|
|
const exitNodeId = parseInt(req.query.exitNodeId as string);
|
2024-09-28 12:35:07 -04:00
|
|
|
|
|
|
|
if (!db) {
|
|
|
|
throw new Error('Database is not attached to the request');
|
|
|
|
}
|
|
|
|
|
|
|
|
|
2024-09-28 15:21:13 -04:00
|
|
|
const exitNode = await db.query.exitNodes.findFirst({
|
|
|
|
where: {
|
|
|
|
exitNodeId: eq(exitNodeId)
|
|
|
|
},
|
|
|
|
with: {
|
|
|
|
routes: true,
|
|
|
|
sites: {
|
|
|
|
with: {
|
|
|
|
resources: {
|
|
|
|
with: {
|
|
|
|
targets: true
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
if (!exitNode) {
|
|
|
|
throw new Error('Exit node not found');
|
|
|
|
}
|
|
|
|
|
|
|
|
const config = {
|
|
|
|
privateKey,
|
|
|
|
listenPort,
|
|
|
|
ipAddress: exitNode.address,
|
|
|
|
peers: exitNode.sites.map((site, index) => ({
|
|
|
|
publicKey: site.pubKey,
|
|
|
|
allowedIps: site.resources.flatMap(resource =>
|
|
|
|
resource.targets.map(target => target.ip)
|
|
|
|
)
|
|
|
|
}))
|
|
|
|
};
|
|
|
|
|
|
|
|
res.json(config);
|
2024-09-28 12:35:07 -04:00
|
|
|
} catch (error) {
|
|
|
|
console.error('Error querying database:', error);
|
2024-09-28 12:42:38 -04:00
|
|
|
if (error instanceof DrizzleError) {
|
|
|
|
res.status(500).json({ error: 'Database query error', message: error.message });
|
|
|
|
} else {
|
|
|
|
next(error);
|
|
|
|
}
|
2024-09-28 12:35:07 -04:00
|
|
|
}
|
2024-09-28 15:21:13 -04:00
|
|
|
};
|
|
|
|
|
|
|
|
function calculateSubnet(index: number): string {
|
|
|
|
const baseIp = 10 << 24;
|
|
|
|
const subnetSize = 16;
|
|
|
|
return `${(baseIp | (index * subnetSize)).toString()}/28`;
|
|
|
|
}
|
|
|
|
|