headplane/server/utils/ws.ts

61 lines
1.3 KiB
TypeScript
Raw Normal View History

2025-02-19 18:09:42 -05:00
import WebSocket, { WebSocketServer } from 'ws';
import log from '~server/utils/log';
2025-01-17 08:33:22 +00:00
const server = new WebSocketServer({ noServer: true });
export function initWebsocket() {
2025-01-18 07:37:03 +00:00
// TODO: Finish this and make public
return;
2025-01-17 08:33:22 +00:00
const key = process.env.LOCAL_AGENT_AUTHKEY;
if (!key) {
return;
}
log.info('CACH', 'Initializing agent WebSocket');
server.on('connection', (ws, req) => {
2025-02-19 18:09:42 -05:00
// biome-ignore lint: this file is not USED
2025-01-17 08:33:22 +00:00
const auth = req.headers['authorization'];
if (auth !== `Bearer ${key}`) {
log.warn('CACH', 'Invalid agent WebSocket connection');
ws.close(1008, 'ERR_INVALID_AUTH');
return;
}
const nodeID = req.headers['x-headplane-ts-node-id'];
if (!nodeID) {
log.warn('CACH', 'Invalid agent WebSocket connection');
ws.close(1008, 'ERR_INVALID_NODE_ID');
return;
}
const pinger = setInterval(() => {
if (ws.readyState !== WebSocket.OPEN) {
clearInterval(pinger);
return;
}
ws.ping();
}, 30000);
ws.on('close', () => {
clearInterval(pinger);
});
ws.on('error', (error) => {
clearInterval(pinger);
log.error('CACH', 'Closing agent WebSocket connection');
log.error('CACH', 'Agent WebSocket error: %s', error);
ws.close(1011, 'ERR_INTERNAL_ERROR');
2025-02-19 18:09:42 -05:00
});
2025-01-17 08:33:22 +00:00
});
return server;
}
export function appContext() {
return {
ws: server,
wsAuthKey: process.env.LOCAL_AGENT_AUTHKEY,
2025-02-19 18:09:42 -05:00
};
2025-01-17 08:33:22 +00:00
}