fix: handle ws upgrade smoothly

This commit is contained in:
Aarnav Tale 2025-03-11 22:39:49 -04:00
parent 134b38ceda
commit 251c16ca48
No known key found for this signature in database
2 changed files with 5 additions and 14 deletions

View File

@ -1,5 +1,6 @@
import { constants, access } from 'node:fs/promises';
import { createServer } from 'node:http';
import { WebSocketServer } from 'ws';
import { hp_getConfig, hp_loadConfig } from '~server/context/loader';
import { listener } from '~server/listener';
import log from '~server/utils/log';
@ -21,18 +22,13 @@ await hp_loadConfig();
const server = createServer(listener);
const context = hp_getConfig();
const ws = initWebsocket(context.server.agent.authkey);
if (ws) {
if (context.server.agent.authkey.length > 0) {
const ws = new WebSocketServer({ server });
initWebsocket(ws, context.server.agent.authkey);
await hp_loadAgentCache(
context.server.agent.ttl,
context.server.agent.cache_path,
);
server.on('upgrade', (req, socket, head) => {
ws.handleUpgrade(req, socket, head, (ws) => {
ws.emit('connection', ws, req);
});
});
}
server.listen(context.server.port, context.server.host, () => {

View File

@ -1,12 +1,7 @@
import WebSocket, { WebSocketServer } from 'ws';
import log from '~server/utils/log';
const server = new WebSocketServer({ noServer: true });
export function initWebsocket(authKey: string) {
if (authKey.length === 0) {
return;
}
export function initWebsocket(server: WebSocketServer, authKey: string) {
log.info('SRVX', 'Starting a WebSocket server for agent connections');
server.on('connection', (ws, req) => {
const tailnetID = req.headers['x-headplane-tailnet-id'];