pi-remote-control/extensions/remote-control/server/upgrade.ts

57 lines
1.6 KiB
TypeScript

/**
* WebSocket upgrade routing — validates auth and dispatches to the
* appropriate handler.
*
* LEGACY: currently routes everything to a single /ws endpoint.
* T-1.5/T-1.6: dispatch to topic/session-specific handlers (stream, input, …).
*/
import type { IncomingMessage } from "node:http";
import type { Server } from "node:http";
import type { Socket } from "node:net";
// Lightweight ws server interface (compatible with the ws package without types)
interface WsServer {
handleUpgrade(
request: IncomingMessage,
socket: Socket,
head: Buffer,
cb: (ws: unknown) => void,
): void;
emit(event: string, ...args: unknown[]): void;
}
/**
* Handle an HTTP upgrade request.
*
* @param _httpServer The HTTP server (reserved for T-1.5/T-1.6 per-session dispatch).
* @param wss The WebSocket server.
* @param request Incoming upgrade request.
* @param socket Raw socket.
* @param head First packet bytes.
* @param isAuthed Whether the request passed authentication.
*/
export function handleUpgrade(
_httpServer: Server,
wss: WsServer,
request: IncomingMessage,
socket: Socket,
head: Buffer,
isAuthed: boolean,
): void {
const url = new URL(request.url ?? "/", "http://localhost");
// T-1.5/T-1.6: inspect url.pathname to dispatch to stream / input / session handlers.
if (url.pathname === "/ws") {
if (!isAuthed) {
socket.write("HTTP/1.1 403 Forbidden\r\n\r\n");
socket.destroy();
return;
}
wss.handleUpgrade(request, socket, head, (ws) => {
wss.emit("connection", ws, request);
});
} else {
socket.destroy();
}
}