fosrl.pangolin/server/routers/olm/handleOlmRelayMessage.ts

97 lines
2.3 KiB
TypeScript
Raw Normal View History

2025-07-18 21:41:58 -07:00
import { db, exitNodes, sites } from "@server/db";
2025-02-23 20:18:03 -05:00
import { MessageHandler } from "../ws";
import { clients, clientSites, Olm } from "@server/db";
2025-07-18 21:41:58 -07:00
import { and, eq } from "drizzle-orm";
2025-03-31 15:45:51 -04:00
import { updatePeer } from "../newt/peers";
2025-02-23 20:18:03 -05:00
import logger from "@server/logger";
export const handleOlmRelayMessage: MessageHandler = async (context) => {
const { message, client: c, sendToClient } = context;
const olm = c as Olm;
logger.info("Handling relay olm message!");
if (!olm) {
logger.warn("Olm not found");
return;
}
if (!olm.clientId) {
logger.warn("Olm has no site!"); // TODO: Maybe we create the site here?
return;
}
const clientId = olm.clientId;
const [client] = await db
.select()
.from(clients)
.where(eq(clients.clientId, clientId))
.limit(1);
if (!client) {
2025-07-18 21:41:58 -07:00
logger.warn("Client not found");
2025-02-23 20:18:03 -05:00
return;
}
// make sure we hand endpoints for both the site and the client and the lastHolePunch is not too old
if (!client.pubKey) {
2025-07-18 21:41:58 -07:00
logger.warn("Client has no endpoint or listen port");
2025-02-23 20:18:03 -05:00
return;
}
2025-04-11 20:52:45 -04:00
const { siteId } = message.data;
2025-02-23 20:18:03 -05:00
2025-07-18 21:41:58 -07:00
// Get the site
const [site] = await db
.select()
.from(sites)
.where(eq(sites.siteId, siteId))
.limit(1);
if (!site || !site.exitNodeId) {
logger.warn("Site not found or has no exit node");
return;
}
// get the site's exit node
const [exitNode] = await db
.select()
.from(exitNodes)
.where(eq(exitNodes.exitNodeId, site.exitNodeId))
.limit(1);
if (!exitNode) {
logger.warn("Exit node not found for site");
return;
}
2025-04-20 14:25:53 -04:00
await db
.update(clientSites)
.set({
isRelayed: true
})
2025-07-18 21:41:58 -07:00
.where(
and(
eq(clientSites.clientId, olm.clientId),
eq(clientSites.siteId, siteId)
)
);
2025-04-20 14:25:53 -04:00
2025-04-11 20:52:45 -04:00
// update the peer on the exit node
await updatePeer(siteId, client.pubKey, {
endpoint: "" // this removes the endpoint
});
2025-02-23 20:18:03 -05:00
2025-07-18 21:41:58 -07:00
sendToClient(olm.olmId, {
type: "olm/wg/peer/relay",
data: {
siteId: siteId,
endpoint: exitNode.endpoint,
publicKey: exitNode.publicKey
}
});
2025-03-31 15:45:51 -04:00
return;
2025-02-23 20:18:03 -05:00
};