mirror of
https://github.com/EchoSixHIYA/WebSpeak-client-for-TeamSpeak.git
synced 2026-12-03 03:52:50 +08:00
fix(acceleration-relay): report socket errors instead of throwing into the void
The relay's socket error listener ended with `throw error`. A listener that throws escapes EventEmitter.emit, so it became an uncaught exception that terminated the whole process. Because the throw also aborts the remaining listeners, it prevented the startup promise from ever settling when the socket failed to bind. - extract an idempotent shutdown() used by both close() and error handling - reject the startup promise when the failure happens before listening, so a failed bind behaves like any other rejected startup rather than a process crash - tear the relay down and report via a new onError callback once it is running - release the socket and sweep interval on a synchronous bind failure, which never emits error at all - add 3 regression tests covering bind failure, a surviving relay after a failed sibling startup, and idempotent close - register the new test file in the npm test list so CI actually runs it Verified: tsc --noEmit is clean and the 3 new tests pass. Before the fix the same bind failure terminated the process with an uncaught EADDRINUSE instead of rejecting the startup promise.
This commit is contained in:
1 parent
62af82f253
commit
feb50d29c1
3 files changed
+148
-20
No files matched your search
@@ -0,0 +1,98 @@
|
||||
import assert from "node:assert/strict";
|
||||
import test from "node:test";
|
||||
import { createHmac } from "node:crypto";
|
||||
import { createSocket, type Socket } from "node:dgram";
|
||||
import { createAccelerationRelayServer } from "./acceleration-relay.js";
|
||||
|
||||
const TOKEN = "test-acceleration-relay-token";
|
||||
const MAGIC = Buffer.from("WSAT");
|
||||
const HEADER_SIZE = 34;
|
||||
const enum FrameType { OPEN = 1, OPEN_OK = 2, OPEN_ERR = 3 }
|
||||
|
||||
function encodeFrame(type: FrameType, sessionId: number, payload: Buffer): Buffer {
|
||||
const frame = Buffer.alloc(HEADER_SIZE + payload.length);
|
||||
MAGIC.copy(frame, 0);
|
||||
frame[4] = 1;
|
||||
frame[5] = type;
|
||||
frame.writeUInt32BE(sessionId >>> 0, 8);
|
||||
frame.writeUInt32BE(1, 12);
|
||||
frame.writeUInt16BE(payload.length, 16);
|
||||
createHmac("sha256", Buffer.from(TOKEN, "utf8"))
|
||||
.update(frame.subarray(0, 18)).update(payload)
|
||||
.digest().subarray(0, 16).copy(frame, 18);
|
||||
payload.copy(frame, HEADER_SIZE);
|
||||
return frame;
|
||||
}
|
||||
|
||||
function decodeFrame(packet: Buffer): { type: number; sessionId: number; payload: Buffer } | null {
|
||||
if (packet.length < HEADER_SIZE || !packet.subarray(0, 4).equals(MAGIC) || packet[4] !== 1) return null;
|
||||
const length = packet.readUInt16BE(16);
|
||||
if (packet.length !== HEADER_SIZE + length) return null;
|
||||
return { type: packet[5]!, sessionId: packet.readUInt32BE(8), payload: packet.subarray(HEADER_SIZE) };
|
||||
}
|
||||
|
||||
|
||||
/** Send one OPEN and resolve with the relay's first reply. */
|
||||
function openTarget(server: { host: string; port: number }, targetHost: string, targetPort = 9987): Promise<{ type: number; code?: string }> {
|
||||
const client = createSocket("udp4");
|
||||
const sessionId = 0x5a5a0001;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = setTimeout(() => {
|
||||
client.close();
|
||||
reject(new Error("The relay did not answer the OPEN frame"));
|
||||
}, 3_000);
|
||||
client.on("message", (packet) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || frame.sessionId !== sessionId) return;
|
||||
clearTimeout(timer);
|
||||
let code: string | undefined;
|
||||
try { code = (JSON.parse(frame.payload.toString("utf8")) as { code?: string }).code; } catch { code = undefined; }
|
||||
client.close();
|
||||
resolve({ type: frame.type, code });
|
||||
});
|
||||
const payload = Buffer.from(JSON.stringify({ targetHost, targetPort }), "utf8");
|
||||
client.send(encodeFrame(FrameType.OPEN, sessionId, payload), server.port, server.host);
|
||||
});
|
||||
}
|
||||
|
||||
async function startRelay(options: { allowPrivate?: boolean } = {}) {
|
||||
return await createAccelerationRelayServer({ host: "127.0.0.1", port: 0, token: TOKEN, ...options });
|
||||
}
|
||||
|
||||
test("a bind failure rejects startup instead of throwing out of the error listener", async () => {
|
||||
// Regression: the socket error listener ended with `throw error`, which escaped
|
||||
// EventEmitter.emit, became an uncaught exception, and killed the process. It
|
||||
// also aborted the remaining listeners, so this call never settled at all.
|
||||
const server = await startRelay({});
|
||||
try {
|
||||
await assert.rejects(
|
||||
() => createAccelerationRelayServer({ host: "127.0.0.1", port: server.port, token: TOKEN }),
|
||||
(error: NodeJS.ErrnoException) => error.code === "EADDRINUSE",
|
||||
);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("a failed startup leaves the surviving relay serving traffic", async () => {
|
||||
// The thrown error used to take the whole process down with it; the relay that
|
||||
// did bind must stay usable.
|
||||
const server = await startRelay({});
|
||||
try {
|
||||
await assert.rejects(() => createAccelerationRelayServer({ host: "127.0.0.1", port: server.port, token: TOKEN }));
|
||||
const reply = await openTarget(server, "8.8.8.8");
|
||||
assert.equal(reply.type, FrameType.OPEN_OK);
|
||||
} finally {
|
||||
server.close();
|
||||
}
|
||||
});
|
||||
|
||||
test("closing a relay is idempotent after a failed sibling startup", async () => {
|
||||
const server = await startRelay({});
|
||||
// A failed startup already tore its own socket down, so nothing leaks and the
|
||||
// surviving relay still closes cleanly when close() runs more than once.
|
||||
const failed = await createAccelerationRelayServer({ host: "127.0.0.1", port: server.port, token: TOKEN }).catch(() => null);
|
||||
assert.equal(failed, null);
|
||||
server.close();
|
||||
server.close();
|
||||
});
|
||||
@@ -165,17 +165,22 @@ export async function createAccelerationRelayServer({
|
||||
token,
|
||||
allowPrivate = false,
|
||||
idleTimeoutMs = 30_000,
|
||||
onError = (error) => { console.error(`[acceleration-relay] socket error: ${error.message}`); },
|
||||
}: {
|
||||
host?: string;
|
||||
port?: number;
|
||||
token: string;
|
||||
allowPrivate?: boolean;
|
||||
idleTimeoutMs?: number;
|
||||
onError?: (error: Error) => void;
|
||||
}): Promise<{ host: string; port: number; close(): void }> {
|
||||
if (!token || token.length < 16) throw new Error("Acceleration relay token must contain at least 16 characters");
|
||||
const socket = createSocket(isIP(host) === 6 ? "udp6" : "udp4");
|
||||
const sessions = new Map<number, RelaySession>();
|
||||
let closed = false;
|
||||
let started = false;
|
||||
let sweep: ReturnType<typeof setInterval> | null = null;
|
||||
let rejectStartup: ((error: Error) => void) | null = null;
|
||||
|
||||
const send = (session: RelaySession, type: FrameType, payload: Buffer<ArrayBufferLike> = Buffer.alloc(0)): void => {
|
||||
if (closed) return;
|
||||
@@ -188,6 +193,31 @@ export async function createAccelerationRelayServer({
|
||||
session.targetSocket?.close();
|
||||
};
|
||||
|
||||
const shutdown = (): void => {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
if (sweep) clearInterval(sweep);
|
||||
sweep = null;
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
try { socket.close(); } catch { /* never bound, or already closed */ }
|
||||
};
|
||||
|
||||
// A listener throwing here is an uncaught exception: it escapes EventEmitter.emit
|
||||
// and terminates the whole process, and because the throw aborts the remaining
|
||||
// listeners it also stops the startup promise below from ever settling. Report the
|
||||
// failure instead — a startup error rejects the returned promise, a later one tears
|
||||
// the relay down — so callers can handle it rather than crash.
|
||||
socket.on("error", (error) => {
|
||||
if (!started) {
|
||||
const reject = rejectStartup;
|
||||
rejectStartup = null;
|
||||
shutdown();
|
||||
reject?.(asError(error));
|
||||
return;
|
||||
}
|
||||
shutdown();
|
||||
onError(asError(error));
|
||||
});
|
||||
socket.on("message", (packet, rinfo) => {
|
||||
const frame = decodeFrame(packet);
|
||||
if (!frame || !verifyFrame(frame, token)) return;
|
||||
@@ -203,35 +233,35 @@ export async function createAccelerationRelayServer({
|
||||
else if (frame.type === FrameType.PING) send(session, FrameType.PONG);
|
||||
else if (frame.type === FrameType.CLOSE) { send(session, FrameType.CLOSE); cleanup(session); }
|
||||
});
|
||||
socket.on("error", (error) => {
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
if (!closed) throw error;
|
||||
});
|
||||
|
||||
const sweep = setInterval(() => {
|
||||
sweep = setInterval(() => {
|
||||
const now = Date.now();
|
||||
for (const session of sessions.values()) if (now - session.lastActivity > idleTimeoutMs) cleanup(session);
|
||||
}, Math.max(1000, Math.min(idleTimeoutMs, 5000)));
|
||||
sweep.unref?.();
|
||||
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
const onError = (error: Error) => { socket.off("listening", onListening); reject(error); };
|
||||
const onListening = () => { socket.off("error", onError); resolve(); };
|
||||
socket.once("error", onError);
|
||||
socket.once("listening", onListening);
|
||||
socket.bind({ address: host, port });
|
||||
});
|
||||
try {
|
||||
await new Promise<void>((resolve, reject) => {
|
||||
rejectStartup = reject;
|
||||
socket.once("listening", () => {
|
||||
started = true;
|
||||
rejectStartup = null;
|
||||
resolve();
|
||||
});
|
||||
socket.bind({ address: host, port });
|
||||
});
|
||||
} catch (error) {
|
||||
// A synchronous bind failure (for example an unusable address) never emits
|
||||
// "error", so release the socket and the sweep interval here too.
|
||||
rejectStartup = null;
|
||||
shutdown();
|
||||
throw error;
|
||||
}
|
||||
const address = socket.address();
|
||||
return {
|
||||
host,
|
||||
port: typeof address === "object" ? address.port : port,
|
||||
close(): void {
|
||||
if (closed) return;
|
||||
closed = true;
|
||||
clearInterval(sweep);
|
||||
for (const session of sessions.values()) cleanup(session);
|
||||
socket.close();
|
||||
},
|
||||
close: shutdown,
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user