MCPcopy Create free account
hub / github.com/TraderAlice/OpenAlice / attachWorkspacesWS

Function attachWorkspacesWS

src/webui/workspaces-ws.ts:68–181  ·  view source on GitHub ↗
(httpServer: HttpServer, svc: WorkspaceService)

Source from the content-addressed store, hash-verified

66}
67
68export function attachWorkspacesWS(httpServer: HttpServer, svc: WorkspaceService): AttachedWS {
69 const wss = new WebSocketServer({ noServer: true });
70
71 const onUpgrade = (req: IncomingMessage, socket: import('node:net').Socket, head: Buffer): void => {
72 const url = new URL(req.url ?? '/', `http://${req.headers.host ?? 'localhost'}`);
73 if (url.pathname !== WS_PATH) {
74 // Not ours — leave for other upgrade listeners (none currently in OpenAlice).
75 return;
76 }
77
78 if (svc.isShuttingDown()) {
79 socket.write('HTTP/1.1 503 Service Unavailable\r\n\r\n');
80 socket.destroy();
81 return;
82 }
83
84 if (!isOriginAllowed(req, svc)) {
85 launcherLogger.warn('upgrade.origin_rejected', {
86 origin: req.headers.origin ?? null,
87 host: req.headers.host ?? null,
88 remoteAddress: req.socket.remoteAddress ?? null,
89 });
90 socket.write('HTTP/1.1 403 Forbidden\r\n\r\n');
91 socket.destroy();
92 return;
93 }
94
95 // Auth check — same gate as the HTTP middleware.
96 // Promise needed because session lookup is async (file-backed).
97 isUpgradeAuthorized(req).then((authorized) => {
98 if (!authorized) {
99 launcherLogger.warn('upgrade.auth_rejected', {
100 remoteAddress: req.socket.remoteAddress ?? null,
101 });
102 socket.write('HTTP/1.1 401 Unauthorized\r\n\r\n');
103 socket.destroy();
104 return;
105 }
106 wss.handleUpgrade(req, socket, head, (ws) => {
107 wss.emit('connection', ws, req, url);
108 });
109 }).catch((err) => {
110 launcherLogger.error('upgrade.auth_check_failed', { err });
111 socket.write('HTTP/1.1 500 Internal Server Error\r\n\r\n');
112 socket.destroy();
113 });
114 };
115
116 httpServer.on('upgrade', onUpgrade);
117
118 wss.on('connection', (ws: WebSocket, req: IncomingMessage, url: URL) => {
119 const cols = clampQuery(url.searchParams.get('cols'), 80, 1, 1000);
120 const rows = clampQuery(url.searchParams.get('rows'), 24, 1, 1000);
121 const sinceRaw = url.searchParams.get('since');
122 const since = sinceRaw === null ? undefined : parseSince(sinceRaw);
123 const controllerId = cleanToken(url.searchParams.get('client'), 128);
124 const controllerKind = cleanToken(url.searchParams.get('kind'), 32) ?? 'web';
125 const takeover = url.searchParams.get('takeover') === '1';

Callers 1

startMethod · 0.85

Calls 9

clampQueryFunction · 0.85
parseSinceFunction · 0.85
cleanTokenFunction · 0.85
warnMethod · 0.80
eventMethod · 0.80
attachByIdMethod · 0.80
getMethod · 0.65
closeMethod · 0.65
errorMethod · 0.65

Tested by

no test coverage detected