mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-03 01:42:50 +08:00
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
817aa0f5f6 | ||
|
|
bc6022b45f |
+128
-9
@@ -2,6 +2,7 @@ import { createServer, type IncomingMessage, type ServerResponse } from "node:ht
|
|||||||
import { createServer as createSecureServer } from "node:https";
|
import { createServer as createSecureServer } from "node:https";
|
||||||
import { readFileSync } from "node:fs";
|
import { readFileSync } from "node:fs";
|
||||||
import { readFile, appendFile, rename, stat } from "node:fs/promises";
|
import { readFile, appendFile, rename, stat } from "node:fs/promises";
|
||||||
|
import { timingSafeEqual } from "node:crypto";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { fileURLToPath } from "node:url";
|
import { fileURLToPath } from "node:url";
|
||||||
import { WebSocketServer, type WebSocket } from "ws";
|
import { WebSocketServer, type WebSocket } from "ws";
|
||||||
@@ -85,6 +86,84 @@ const FEEDBACK_LOG_MAX_BYTES = 5 * 1024 * 1024;
|
|||||||
const FEEDBACK_CATEGORIES = new Set(["bug", "idea", "report", "other"]);
|
const FEEDBACK_CATEGORIES = new Set(["bug", "idea", "report", "other"]);
|
||||||
const FEEDBACK_MESSAGE_MAX_LENGTH = 4000;
|
const FEEDBACK_MESSAGE_MAX_LENGTH = 4000;
|
||||||
|
|
||||||
|
// --- Broadcast endpoint ---------------------------------------------------
|
||||||
|
//
|
||||||
|
// Opt-in only, same convention as LOG_CONNECTIONS/FEEDBACK_ENABLED above: lets
|
||||||
|
// the operator push a free-text maintenance notice to every connected browser
|
||||||
|
// tab (reuses the same {type:"notice"} message the SIGTERM handler already
|
||||||
|
// sends, which the frontend renders even without a messageKey). Unset
|
||||||
|
// BROADCAST_TOKEN and the endpoint 404s, same as feedback when disabled.
|
||||||
|
const BROADCAST_TOKEN = process.env.BROADCAST_TOKEN;
|
||||||
|
const BROADCAST_MESSAGE_MAX_LENGTH = 500;
|
||||||
|
|
||||||
|
function isValidBroadcastToken(provided: string): boolean {
|
||||||
|
if (!BROADCAST_TOKEN) return false;
|
||||||
|
const a = Buffer.from(provided);
|
||||||
|
const b = Buffer.from(BROADCAST_TOKEN);
|
||||||
|
return a.length === b.length && timingSafeEqual(a, b);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleBroadcast(req: IncomingMessage, res: ServerResponse) {
|
||||||
|
if (!BROADCAST_TOKEN) {
|
||||||
|
res.writeHead(404, { "Content-Type": "application/json" });
|
||||||
|
res.end(JSON.stringify({ error: "not_found" }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (req.method !== "POST") {
|
||||||
|
res.writeHead(405, { "Content-Type": "application/json" });
|
||||||
|
res.end(JSON.stringify({ error: "method_not_allowed" }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const authHeader = req.headers.authorization ?? "";
|
||||||
|
const token = authHeader.startsWith("Bearer ") ? authHeader.slice("Bearer ".length) : "";
|
||||||
|
if (!isValidBroadcastToken(token)) {
|
||||||
|
res.writeHead(401, { "Content-Type": "application/json" });
|
||||||
|
res.end(JSON.stringify({ error: "unauthorized" }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
let raw = "";
|
||||||
|
for await (const chunk of req) {
|
||||||
|
raw += chunk;
|
||||||
|
if (raw.length > 5_000) {
|
||||||
|
res.writeHead(413, { "Content-Type": "application/json" });
|
||||||
|
res.end(JSON.stringify({ error: "payload_too_large" }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let body: { message?: unknown };
|
||||||
|
try {
|
||||||
|
body = JSON.parse(raw || "{}");
|
||||||
|
} catch {
|
||||||
|
res.writeHead(400, { "Content-Type": "application/json" });
|
||||||
|
res.end(JSON.stringify({ error: "invalid_json" }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const message = typeof body.message === "string" ? body.message.trim().slice(0, BROADCAST_MESSAGE_MAX_LENGTH) : "";
|
||||||
|
if (!message) {
|
||||||
|
res.writeHead(400, { "Content-Type": "application/json" });
|
||||||
|
res.end(JSON.stringify({ error: "message_required" }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = JSON.stringify({ type: "notice", message });
|
||||||
|
let sent = 0;
|
||||||
|
for (const socket of wss.clients) {
|
||||||
|
try {
|
||||||
|
socket.send(payload);
|
||||||
|
sent++;
|
||||||
|
} catch {
|
||||||
|
/* socket already gone */
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res.writeHead(200, { "Content-Type": "application/json" });
|
||||||
|
res.end(JSON.stringify({ ok: true, sent }));
|
||||||
|
}
|
||||||
|
|
||||||
async function rotateFeedbackLogIfNeeded(): Promise<void> {
|
async function rotateFeedbackLogIfNeeded(): Promise<void> {
|
||||||
try {
|
try {
|
||||||
const { size } = await stat(FEEDBACK_LOG_FILE);
|
const { size } = await stat(FEEDBACK_LOG_FILE);
|
||||||
@@ -278,6 +357,10 @@ const requestHandler = (req: IncomingMessage, res: ServerResponse) => {
|
|||||||
await handleFeedback(req, res);
|
await handleFeedback(req, res);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (requestUrl.pathname === "/api/broadcast") {
|
||||||
|
await handleBroadcast(req, res);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
// Container healthcheck target (see Dockerfile). Deliberately its own
|
// Container healthcheck target (see Dockerfile). Deliberately its own
|
||||||
// route rather than "/": with WEB_STATIC=0 every browser-facing path
|
// route rather than "/": with WEB_STATIC=0 every browser-facing path
|
||||||
@@ -345,6 +428,17 @@ interface HeartbeatState {
|
|||||||
|
|
||||||
const heartbeats = new WeakMap<WebSocket, HeartbeatState>();
|
const heartbeats = new WeakMap<WebSocket, HeartbeatState>();
|
||||||
|
|
||||||
|
// Tracked so SIGTERM (below) can tell every live TS3/TeaSpeak session to
|
||||||
|
// disconnect properly before the process exits, instead of leaving the
|
||||||
|
// target server to notice on its own timeout.
|
||||||
|
const liveConnections = new Set<Ts3Connection>();
|
||||||
|
// Set right before that graceful disconnect: suppresses forwarding the
|
||||||
|
// connector's own "disconnected" event to the browser during shutdown, so
|
||||||
|
// the browser sees a raw socket close (which it auto-reconnects from) rather
|
||||||
|
// than an explicit disconnect (which it treats as deliberate and gives up
|
||||||
|
// on) — see the SIGTERM handler.
|
||||||
|
let shuttingDown = false;
|
||||||
|
|
||||||
const heartbeatTimer = setInterval(() => {
|
const heartbeatTimer = setInterval(() => {
|
||||||
for (const socket of wss.clients) {
|
for (const socket of wss.clients) {
|
||||||
const state = heartbeats.get(socket);
|
const state = heartbeats.get(socket);
|
||||||
@@ -365,16 +459,35 @@ wss.on("close", () => clearInterval(heartbeatTimer));
|
|||||||
// browser tab so an active call/stream doesn't just silently drop, then
|
// browser tab so an active call/stream doesn't just silently drop, then
|
||||||
// exit quickly rather than waiting out the grace period doing nothing.
|
// exit quickly rather than waiting out the grace period doing nothing.
|
||||||
process.on("SIGTERM", () => {
|
process.on("SIGTERM", () => {
|
||||||
const payload = JSON.stringify({ type: "notice", messageKey: "restartNotice.body" });
|
void (async () => {
|
||||||
for (const socket of wss.clients) {
|
const payload = JSON.stringify({ type: "notice", messageKey: "restartNotice.body" });
|
||||||
try {
|
for (const socket of wss.clients) {
|
||||||
socket.send(payload);
|
try {
|
||||||
} catch {
|
socket.send(payload);
|
||||||
/* socket already gone */
|
} catch {
|
||||||
|
/* socket already gone */
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
console.log(`[gateway] SIGTERM received, notified ${wss.clients.size} client(s), disconnecting ${liveConnections.size} live session(s)`);
|
||||||
console.log(`[gateway] SIGTERM received, notified ${wss.clients.size} client(s), shutting down`);
|
|
||||||
setTimeout(() => process.exit(0), 500);
|
// Tell every connector to leave its TS3/TeaSpeak server *before* the
|
||||||
|
// process exits. Without this, `docker stop`'s grace period expires and
|
||||||
|
// the container is killed, taking the connector child processes with it
|
||||||
|
// mid-session - the target server only notices via its own timeout
|
||||||
|
// (which can take a while), during which a client's automatic reconnect
|
||||||
|
// (see App.tsx's scheduleReconnect) gets rejected by the server as a
|
||||||
|
// duplicate identity (e.g. "ClientTooManyClonesConnected"). shuttingDown
|
||||||
|
// suppresses forwarding the resulting "disconnected" event to the
|
||||||
|
// browser - the browser must see a raw socket close here, not an
|
||||||
|
// explicit disconnect, or it treats it as deliberate and won't retry.
|
||||||
|
shuttingDown = true;
|
||||||
|
await Promise.race([
|
||||||
|
Promise.all([...liveConnections].map((c) => c.disconnect().catch(() => {}))),
|
||||||
|
new Promise((resolve) => setTimeout(resolve, 5000)),
|
||||||
|
]);
|
||||||
|
console.log(`[gateway] shutting down`);
|
||||||
|
process.exit(0);
|
||||||
|
})();
|
||||||
});
|
});
|
||||||
|
|
||||||
server.listen(PORT, () => {
|
server.listen(PORT, () => {
|
||||||
@@ -414,6 +527,7 @@ wss.on("connection", (socket: WebSocket) => {
|
|||||||
} catch {
|
} catch {
|
||||||
/* ignore */
|
/* ignore */
|
||||||
}
|
}
|
||||||
|
liveConnections.delete(connection);
|
||||||
connection = undefined;
|
connection = undefined;
|
||||||
}
|
}
|
||||||
const options: Ts3ConnectOptions = {
|
const options: Ts3ConnectOptions = {
|
||||||
@@ -427,7 +541,9 @@ wss.on("connection", (socket: WebSocket) => {
|
|||||||
privilegeKey: parsePrivilegeKey(msg),
|
privilegeKey: parsePrivilegeKey(msg),
|
||||||
};
|
};
|
||||||
connection = new Ts3Connection(options);
|
connection = new Ts3Connection(options);
|
||||||
|
liveConnections.add(connection);
|
||||||
connection.onEvent((event) => {
|
connection.onEvent((event) => {
|
||||||
|
if (shuttingDown) return;
|
||||||
if (LOG_CONNECTIONS) {
|
if (LOG_CONNECTIONS) {
|
||||||
if (event.type === "connected") {
|
if (event.type === "connected") {
|
||||||
console.log(
|
console.log(
|
||||||
@@ -694,6 +810,8 @@ wss.on("connection", (socket: WebSocket) => {
|
|||||||
}
|
}
|
||||||
case "disconnect": {
|
case "disconnect": {
|
||||||
await connection?.disconnect(msg.message ?? "");
|
await connection?.disconnect(msg.message ?? "");
|
||||||
|
if (connection) liveConnections.delete(connection);
|
||||||
|
connection = undefined;
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default:
|
default:
|
||||||
@@ -705,6 +823,7 @@ wss.on("connection", (socket: WebSocket) => {
|
|||||||
|
|
||||||
socket.on("close", () => {
|
socket.on("close", () => {
|
||||||
heartbeats.delete(socket);
|
heartbeats.delete(socket);
|
||||||
|
if (connection) liveConnections.delete(connection);
|
||||||
connection?.disconnect();
|
connection?.disconnect();
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
Reference in new issue
Block a user