diff --git a/gateway/src/index.ts b/gateway/src/index.ts index 7c0d08f..3aeb5e8 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -708,6 +708,11 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => { // One browser WebSocket ↔ one Rust connector. Multi-join in the UI opens // multiple /ws connections in parallel (one per server tab). let connection: Ts3Connection | undefined; + // Message handlers are async and run concurrently, so a connect can still be + // awaiting when a newer connect or the close arrives. Only the newest + // connect on an open socket may spawn a connector, else one leaks. + let closed = false; + let connectGen = 0; // Full: accept and say so, since a browser can't read why an upgrade was refused. if (maxConnections() > 0 && wss.clients.size > maxConnections()) { @@ -791,17 +796,16 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => { } socket.send(JSON.stringify({ type: "turnstilePass", pass: issuePass(ip) })); } - // Replacing a connection on the same socket: tear down the previous - // connector so we don't leak processes. - if (connection) { - try { - await connection.disconnect(); - } catch { - /* ignore */ - } - liveConnections.delete(connection); - connection = undefined; + // Replacing a connection on the same socket: take the previous one + // out before awaiting its teardown, so no other handler sees it. + const gen = ++connectGen; + const prev = connection; + connection = undefined; + if (prev) { + liveConnections.delete(prev); + await prev.disconnect().catch(() => {}); } + if (closed || gen !== connectGen) break; const options: Ts3ConnectOptions = { host: msg.host, nickname: msg.nickname, @@ -1095,9 +1099,13 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => { break; } case "disconnect": { - await connection?.disconnect(msg.message ?? ""); - if (connection) liveConnections.delete(connection); + // Same as above: detach first, a connect may arrive while this awaits. + const current = connection; connection = undefined; + if (current) { + liveConnections.delete(current); + await current.disconnect(msg.message ?? ""); + } break; } default: @@ -1113,7 +1121,11 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => { if (remaining > 0) connectionsPerIp.set(ip, remaining); else connectionsPerIp.delete(ip); heartbeats.delete(socket); - if (connection) liveConnections.delete(connection); - connection?.disconnect(); + closed = true; + if (connection) { + liveConnections.delete(connection); + void connection.disconnect().catch(() => {}); + connection = undefined; + } }); }); diff --git a/gateway/test/connector-orphans.test.mjs b/gateway/test/connector-orphans.test.mjs new file mode 100644 index 0000000..daa676d --- /dev/null +++ b/gateway/test/connector-orphans.test.mjs @@ -0,0 +1,61 @@ +// Connect/close races on one WebSocket must not leave connector processes +// behind. Uses a fake connector that records its PID and lives until its +// stdin closes (like the real one), against the built gateway. +import { test } from "node:test"; +import assert from "node:assert/strict"; +import { spawn } from "node:child_process"; +import { chmodSync, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { createServer } from "node:net"; +import { tmpdir } from "node:os"; +import path from "node:path"; + +const INDEX = path.resolve(import.meta.dirname, "../dist/index.js"); +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); +const alive = (pid) => { try { process.kill(pid, 0); return true; } catch { return false; } }; +const freePort = () => new Promise((ok) => { + const s = createServer().listen(0, () => { const p = s.address().port; s.close(() => ok(p)); }); +}); + +test("no connector outlives its WebSocket", { timeout: 60_000 }, async () => { + const dir = mkdtempSync(path.join(tmpdir(), "ws3-orphans-")); + const pids = path.join(dir, "pids"); + const fake = path.join(dir, "fake-connector.sh"); + writeFileSync(fake, `#!/bin/sh\necho $$ >> '${pids}'\ncat > /dev/null\nsleep 1\n`); + chmodSync(fake, 0o755); + const port = await freePort(); + const gw = spawn(process.execPath, [INDEX], { + cwd: dir, + env: { PATH: process.env.PATH, PORT: String(port), WEB_STATIC: "0", TELEMETRY: "0", CONNECTOR_BIN: fake }, + stdio: "ignore", + }); + const recorded = () => (existsSync(pids) ? readFileSync(pids, "utf8").split("\n").filter(Boolean).map(Number) : []); + try { + for (let i = 0; i < 50; i++) { try { await fetch(`http://127.0.0.1:${port}/api/features`); break; } catch { await wait(100); } } + const connect = JSON.stringify({ type: "connect", host: "example.invalid", nickname: "dummy" }); + const open = async () => { + const ws = new WebSocket(`ws://127.0.0.1:${port}/ws`); + await new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = fail; }); + return ws; + }; + + // connect, connect while the first connector shuts down, close + let ws = await open(); + ws.send(connect); await wait(300); + ws.send(connect); await wait(100); + ws.close(); + // connect, then two connects back to back, close later + ws = await open(); + ws.send(connect); await wait(300); + ws.send(connect); ws.send(connect); + await wait(4000); + ws.close(); + + await wait(4000); + assert.ok(recorded().length >= 2, "fake connector was spawned"); + assert.deepEqual(recorded().filter(alive), [], "connector processes left behind"); + } finally { + for (const pid of recorded()) if (alive(pid)) process.kill(pid, "SIGKILL"); + await new Promise((ok) => { gw.once("exit", ok); gw.kill("SIGTERM"); }); + rmSync(dir, { recursive: true, force: true }); + } +});