GCoordinator/src/server/api/ws-hub.ts

317 lines
8.5 KiB
TypeScript

import type { Duplex } from 'node:stream';
import type { IncomingMessage, Server as HttpServer } from 'node:http';
import { WebSocket, WebSocketServer } from 'ws';
import {
ClientWsFrameSchema,
type ServerWsFrame,
} from '../../shared/ws-protocol.js';
import { SESSION_COOKIE_NAME, type AuthService } from '../security/auth.js';
import { extractCookies } from '../security/guards.js';
import type { VaultService } from '../security/vault.js';
interface WsClientMeta {
ws: WebSocket;
sessionToken: string;
sessionIdHash: string;
channels: Set<string>;
clientSafeMode: boolean;
alive: boolean;
}
export type WsUpgradeHandler = (
req: IncomingMessage,
socket: Duplex,
head: Buffer,
) => void;
export type WsSubscribeListener = (
ctx: {
send: (frame: ServerWsFrame) => void;
sessionIdHash: string;
},
channel: string,
) => void;
export interface WsPtyHandlers {
onInput: (sessionId: string, data: string) => void;
onResize: (sessionId: string, cols: number, rows: number) => void;
}
export interface WsAiHandlers {
onCancel: (chatId: string) => void;
}
export class WsHub {
private readonly wss = new WebSocketServer({ noServer: true });
private readonly clients = new Set<WsClientMeta>();
private readonly pingTimer: NodeJS.Timeout;
private readonly upgradeHandlers: Array<{ prefix: string; handler: WsUpgradeHandler }> = [];
private readonly subscribeListeners = new Set<WsSubscribeListener>();
private ptyHandlers: WsPtyHandlers | null = null;
private aiHandlers: WsAiHandlers | null = null;
constructor(
httpServer: HttpServer,
private readonly authService: AuthService,
private readonly vaultService: VaultService,
) {
httpServer.on('upgrade', (req, socket, head) => {
this.handleUpgrade(req, socket, head);
});
this.pingTimer = setInterval(() => {
for (const client of this.clients) {
if (!client.alive) {
client.ws.terminate();
this.clients.delete(client);
continue;
}
client.alive = false;
client.ws.ping();
}
}, 25_000);
this.pingTimer.unref();
}
registerUpgradeHandler(prefix: string, handler: WsUpgradeHandler): void {
this.upgradeHandlers.push({ prefix, handler });
}
onChannelSubscribe(listener: WsSubscribeListener): () => void {
this.subscribeListeners.add(listener);
return () => {
this.subscribeListeners.delete(listener);
};
}
attachPtyHandlers(handlers: WsPtyHandlers): void {
this.ptyHandlers = handlers;
}
attachAiHandlers(handlers: WsAiHandlers): void {
this.aiHandlers = handlers;
}
close(): void {
clearInterval(this.pingTimer);
for (const client of this.clients) {
client.ws.close(1001, 'Server shutting down');
}
this.clients.clear();
this.wss.close();
}
handlePanicLock(): void {
const payload = JSON.stringify({ type: 'security:panic-lock' } satisfies ServerWsFrame);
for (const client of this.clients) {
try {
if (client.ws.readyState === WebSocket.OPEN) {
client.ws.send(payload);
}
client.ws.close(4001, 'Panic Lock engaged');
} catch {
// Continue closing remaining sockets
}
}
this.clients.clear();
}
broadcastAll(frame: ServerWsFrame): void {
const text = JSON.stringify(frame);
for (const client of this.clients) {
if (client.ws.readyState === WebSocket.OPEN) {
client.ws.send(text);
}
}
}
broadcastChannel(channel: string, frame: ServerWsFrame): void {
const text = JSON.stringify(frame);
for (const client of this.clients) {
if (
client.ws.readyState === WebSocket.OPEN &&
(client.channels.has(channel) || client.channels.has('*'))
) {
client.ws.send(text);
}
}
}
private handleUpgrade(
req: IncomingMessage,
socket: Duplex,
head: Buffer,
): void {
const urlPath = (req.url ?? '').split('?')[0] ?? '';
for (const entry of this.upgradeHandlers) {
if (urlPath.startsWith(entry.prefix)) {
entry.handler(req, socket, head);
return;
}
}
if (urlPath !== '/ws') {
socket.write('HTTP/1.1 404 Not Found\r\n\r\n');
socket.destroy();
return;
}
// Validate Origin when provided by browsers to block cross-site WS hijacking
const origin = req.headers.origin;
const host = req.headers.host;
if (origin && host) {
try {
const originUrl = new URL(origin);
if (originUrl.host !== host) {
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
return;
}
} catch {
socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
socket.destroy();
return;
}
}
const cookies = extractCookies(req.headers.cookie);
const token = cookies[SESSION_COOKIE_NAME];
const session = this.authService.getSessionByToken(token);
if (!session || !token) {
socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
socket.destroy();
return;
}
this.wss.handleUpgrade(req, socket, head, (ws) => {
const meta: WsClientMeta = {
ws,
sessionToken: token,
sessionIdHash: session.idHash,
channels: new Set(['config', 'alerts']),
clientSafeMode: session.safeMode,
alive: true,
};
this.clients.add(meta);
this.sendFrame(ws, {
type: 'hello',
vaultState: this.vaultService.state,
vaultRuntimeReady: this.vaultService.isRuntimeReady,
safeMode: session.safeMode,
elevatedUntil: session.elevatedUntil,
});
ws.on('pong', () => {
meta.alive = true;
});
ws.on('message', (raw) => {
this.onMessage(meta, raw);
});
ws.on('close', () => {
this.clients.delete(meta);
});
ws.on('error', () => {
this.clients.delete(meta);
});
});
}
private onMessage(meta: WsClientMeta, raw: unknown): void {
let parsedJson: unknown;
try {
const text = typeof raw === 'string' ? raw : Buffer.from(raw as Buffer).toString('utf8');
parsedJson = JSON.parse(text);
} catch {
this.sendFrame(meta.ws, {
type: 'error',
code: 'BAD_JSON',
message: 'Invalid WebSocket JSON frame',
});
return;
}
const result = ClientWsFrameSchema.safeParse(parsedJson);
if (!result.success) {
this.sendFrame(meta.ws, {
type: 'error',
code: 'INVALID_FRAME',
message: 'Unrecognized or malformed WebSocket frame',
});
return;
}
const frame = result.data;
switch (frame.type) {
case 'ping':
this.sendFrame(meta.ws, {
type: 'pong',
ts: frame.ts,
serverTs: Date.now(),
});
break;
case 'sub': {
const ctx = {
send: (outFrame: ServerWsFrame) => this.sendFrame(meta.ws, outFrame),
sessionIdHash: meta.sessionIdHash,
};
for (const ch of frame.channels) {
meta.channels.add(ch);
for (const listener of this.subscribeListeners) {
try {
listener(ctx, ch);
} catch {
// Isolate subscriber replay errors
}
}
}
break;
}
case 'unsub':
for (const ch of frame.channels) {
meta.channels.delete(ch);
}
break;
case 'safe-mode':
meta.clientSafeMode = frame.enabled;
break;
case 'pty:input': {
const latestSession = this.authService.getSessionByToken(meta.sessionToken);
if (!latestSession) {
meta.ws.close(4001, 'Session expired');
return;
}
if (latestSession.safeMode || meta.clientSafeMode) {
this.sendFrame(meta.ws, {
type: 'error',
code: 'SAFE_MODE_ACTIVE',
message: 'Safe / Read-Only Mode blocks terminal input.',
});
return;
}
this.ptyHandlers?.onInput(frame.sessionId, frame.data);
break;
}
case 'pty:resize': {
const latestSession = this.authService.getSessionByToken(meta.sessionToken);
if (!latestSession) {
meta.ws.close(4001, 'Session expired');
return;
}
this.ptyHandlers?.onResize(frame.sessionId, frame.cols, frame.rows);
break;
}
case 'ai:cancel':
this.aiHandlers?.onCancel(frame.chatId);
break;
}
}
private sendFrame(ws: WebSocket, frame: ServerWsFrame): void {
if (ws.readyState === WebSocket.OPEN) {
ws.send(JSON.stringify(frame));
}
}
}