feat(server): add Express REST API, security middleware, and multiplexed WebSocket hub
This commit is contained in:
parent
6520b81d82
commit
9cedd83a07
7 changed files with 1538 additions and 0 deletions
243
src/server/api/ws-hub.ts
Normal file
243
src/server/api/ws-hub.ts
Normal file
|
|
@ -0,0 +1,243 @@
|
|||
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 class WsHub {
|
||||
private readonly wss = new WebSocketServer({ noServer: true });
|
||||
private readonly clients = new Set<WsClientMeta>();
|
||||
private readonly pingTimer: NodeJS.Timeout;
|
||||
|
||||
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();
|
||||
}
|
||||
|
||||
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: import('node:stream').Duplex,
|
||||
head: Buffer,
|
||||
): void {
|
||||
const urlPath = (req.url ?? '').split('?')[0];
|
||||
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,
|
||||
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':
|
||||
for (const ch of frame.channels) {
|
||||
meta.channels.add(ch);
|
||||
}
|
||||
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;
|
||||
}
|
||||
// Phase 3 PTYManager attaches here
|
||||
break;
|
||||
}
|
||||
case 'pty:resize':
|
||||
case 'ai:cancel':
|
||||
// Wired in Phases 3 and 5
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private sendFrame(ws: WebSocket, frame: ServerWsFrame): void {
|
||||
if (ws.readyState === WebSocket.OPEN) {
|
||||
ws.send(JSON.stringify(frame));
|
||||
}
|
||||
}
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue