mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-03 01:42:50 +08:00
Add optional token-authenticated /api/broadcast endpoint
Lets the operator send a free-text maintenance notice to every connected
browser tab via POST /api/broadcast (Bearer BROADCAST_TOKEN). Reuses the
existing {type:"notice"} WebSocket message the frontend already renders
for the SIGTERM restart notice, so no frontend changes are needed. Off
(404) unless BROADCAST_TOKEN is set, same opt-in convention as
FEEDBACK_ENABLED/LOG_CONNECTIONS.
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
1 parent
8d17514774
commit
bc6022b45f
1 file changed
+83
@@ -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
|
||||||
|
|||||||
Reference in new issue
Block a user