2025-02-21 10:55:38 -05:00
|
|
|
import db from '@server/db';
|
|
|
|
import { newts, sites } from '@server/db/schema';
|
|
|
|
import { eq } from 'drizzle-orm';
|
|
|
|
import { sendToClient } from '../ws';
|
2025-02-23 16:49:41 -05:00
|
|
|
import logger from '@server/logger';
|
2025-02-21 10:55:38 -05:00
|
|
|
|
|
|
|
export async function addPeer(siteId: number, peer: {
|
|
|
|
publicKey: string;
|
|
|
|
allowedIps: string[];
|
2025-02-22 11:20:56 -05:00
|
|
|
endpoint: string;
|
2025-02-21 10:55:38 -05:00
|
|
|
}) {
|
|
|
|
|
|
|
|
const [site] = await db.select().from(sites).where(eq(sites.siteId, siteId)).limit(1);
|
|
|
|
if (!site) {
|
|
|
|
throw new Error(`Exit node with ID ${siteId} not found`);
|
|
|
|
}
|
|
|
|
|
|
|
|
// get the newt on the site
|
|
|
|
const [newt] = await db.select().from(newts).where(eq(newts.siteId, siteId)).limit(1);
|
|
|
|
if (!newt) {
|
|
|
|
throw new Error(`Newt not found for site ${siteId}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
sendToClient(newt.newtId, {
|
2025-02-21 12:34:05 -05:00
|
|
|
type: 'newt/wg/peer/add',
|
2025-02-21 10:55:38 -05:00
|
|
|
data: peer
|
|
|
|
});
|
2025-02-23 16:49:41 -05:00
|
|
|
|
|
|
|
logger.info(`Added peer ${peer.publicKey} to newt ${newt.newtId}`);
|
2025-02-21 10:55:38 -05:00
|
|
|
}
|
|
|
|
|
|
|
|
export async function deletePeer(siteId: number, publicKey: string) {
|
|
|
|
const [site] = await db.select().from(sites).where(eq(sites.siteId, siteId)).limit(1);
|
|
|
|
if (!site) {
|
|
|
|
throw new Error(`Exit node with ID ${siteId} not found`);
|
|
|
|
}
|
|
|
|
|
|
|
|
// get the newt on the site
|
|
|
|
const [newt] = await db.select().from(newts).where(eq(newts.siteId, siteId)).limit(1);
|
|
|
|
if (!newt) {
|
|
|
|
throw new Error(`Newt not found for site ${siteId}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
sendToClient(newt.newtId, {
|
2025-02-21 12:34:05 -05:00
|
|
|
type: 'newt/wg/peer/remove',
|
2025-02-21 10:55:38 -05:00
|
|
|
data: {
|
|
|
|
publicKey
|
|
|
|
}
|
|
|
|
});
|
2025-02-23 16:49:41 -05:00
|
|
|
|
|
|
|
logger.info(`Deleted peer ${publicKey} from newt ${newt.newtId}`);
|
2025-03-31 15:45:51 -04:00
|
|
|
}
|
|
|
|
|
|
|
|
export async function updatePeer(siteId: number, publicKey: string, peer: {
|
|
|
|
allowedIps?: string[];
|
|
|
|
endpoint?: string;
|
|
|
|
}) {
|
|
|
|
const [site] = await db.select().from(sites).where(eq(sites.siteId, siteId)).limit(1);
|
|
|
|
if (!site) {
|
|
|
|
throw new Error(`Exit node with ID ${siteId} not found`);
|
|
|
|
}
|
|
|
|
|
|
|
|
// get the newt on the site
|
|
|
|
const [newt] = await db.select().from(newts).where(eq(newts.siteId, siteId)).limit(1);
|
|
|
|
if (!newt) {
|
|
|
|
throw new Error(`Newt not found for site ${siteId}`);
|
|
|
|
}
|
|
|
|
|
|
|
|
sendToClient(newt.newtId, {
|
|
|
|
type: 'newt/wg/peer/update',
|
|
|
|
data: {
|
|
|
|
publicKey,
|
|
|
|
...peer
|
|
|
|
}
|
|
|
|
});
|
|
|
|
|
|
|
|
logger.info(`Updated peer ${publicKey} on newt ${newt.newtId}`);
|
2025-02-21 10:55:38 -05:00
|
|
|
}
|