Add news ticker at the bottom of the client

Central feed (/api/store/news on the store server: manual items via
STORE_ADMIN_TOKEN, plus the latest release and newest store design for
30 days) and a per-gateway /api/news with NEWS_TICKER, NEWS_TICKER_CENTRAL
and NEWS_TICKER_MESSAGES so self-hosters can turn it off or add their own.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
MoepchiandClaude Opus 5.5 committed 2026-10-22 18:38:00 +00:00
1 parent aa324274a4
commit 632e77ccc8
12 files changed
+359

No files matched your search

+5
View File
@@ -210,9 +210,14 @@ All optional; add them under `environment:` in your compose override next to `PO
| `CONNECT_RATE_LIMIT` | `30` | Server connects per client IP per minute. Each one starts a new TeamSpeak session, so this stops anyone from flooding a server through your gateway. `0` disables it. |
| `TRUST_PROXY` | off | Only when the gateway is reachable **solely** through a proxy/tunnel, so per-IP limits see the real client instead of the proxy: `cloudflare` (Cloudflare Tunnel or proxy) uses `CF-Connecting-IP`; `1` (your own nginx/Caddy/Traefik) uses the last `X-Forwarded-For` entry, the one your proxy appended. Don't set it on a directly exposed gateway - clients could then fake their IP. |
| `TELEMETRY` | on | Set to `0` to turn off the anonymous usage ping (see below). |
| `NEWS_TICKER` | on | Set to `0` to hide the news ticker at the bottom of the client. |
| `NEWS_TICKER_CENTRAL` | on | Set to `0` to drop the official WebSpeak3 news (releases, new store designs, announcements) and only show your own messages. |
| `NEWS_TICKER_MESSAGES` | – | Your own ticker messages, separated by `\|`, e.g. `Maintenance tonight at 10pm \| Welcome!` |
> **Anonymous usage ping:** when the gateway starts and then once a day, it sends a random instance ID (made up on first start, stored in `instance-id` in the working directory, used for nothing else) and its version number to `gateway.webspeak3.de`. That's the only way to tell whether anyone self-hosts WebSpeak3 at all, and how many instances still run an old version, e.g. after a security fix. Nothing else is sent: no hostnames, no TeamSpeak servers, no users, no settings. The receiving side doesn't store IP addresses. The startup log says when it's on. Turn it off with `TELEMETRY=0`.
> **News ticker:** like the native TS3 client, a small scrolling line at the bottom shows news. Your users' browsers load the official news straight from `gateway.webspeak3.de`, the same way the Design Store works. Your own messages come from `NEWS_TICKER_MESSAGES`. Users can hide the ticker with ✕ until something new comes in.
> **Trust model:** the gateway speaks the TeamSpeak protocol on the user's behalf, so whoever runs it necessarily handles their identity key, server/channel passwords and privilege keys (they're kept out of process listings, but the operator can still see them). Only use gateways you trust, and serve them over HTTPS/WSS (`TLS_CERT`/`TLS_KEY` or a TLS-terminating proxy) - plain HTTP exposes all of that on the wire. File uploads are limited to 24 MiB, downloads to 25 MiB.
> **Stored in the browser:** identities (including their private keys), favorites with any passwords you typed into them, and settings live in the browser's `localStorage`, unencrypted - the same way the native client keeps them in its settings files. Anyone with access to your browser profile can read them; leave favorite password fields empty on shared machines and export identities you care about. Server banners load directly from the host the server admin configured; turn them off under Options → Application if you don't want that host to see your IP.
+5
View File
@@ -8,6 +8,7 @@ import { fileURLToPath } from "node:url";
import { WebSocketServer, type WebSocket } from "ws";
import { Ts3Connection, type ServerType, type Ts3ConnectOptions } from "./ts3/connection.js";
import { handleStore } from "./store.js";
import { handleNewsConfig } from "./news.js";
import { logFeedback, logConnectionEvent } from "./activity-log.js";
import { clientIp, createRateLimiter } from "./net.js";
import "./telemetry.js";
@@ -479,6 +480,10 @@ const requestHandler = (req: IncomingMessage, res: ServerResponse) => {
await handleFeedback(req, res);
return;
}
if (requestUrl.pathname === "/api/news") {
handleNewsConfig(res);
return;
}
if (requestUrl.pathname === "/api/broadcast") {
await handleBroadcast(req, res);
return;
+150
View File
@@ -0,0 +1,150 @@
// --- News ticker -----------------------------------------------------------
//
// Two halves:
// * handleNewsFeed - the central feed every client shows by default. Served
// by store-server.ts at /api/store/news, so it rides the existing
// /api/store tunnel route. Manual items live in NEWS_DATA_FILE and are
// managed with STORE_ADMIN_TOKEN (the stats panel); the latest release and
// the newest store design are added automatically.
// * handleNewsConfig - every gateway's /api/news. Tells its own client
// whether to show the ticker at all (NEWS_TICKER=0 turns it off), whether
// to include the central feed (NEWS_TICKER_CENTRAL=0 drops it), and the
// instance's own messages (NEWS_TICKER_MESSAGES, separated by "|").
//
// Like store.ts, this file has zero private modifications.
import type { IncomingMessage, ServerResponse } from "node:http";
import { readFile, rename, writeFile } from "node:fs/promises";
import { randomUUID } from "node:crypto";
import { isAdminRequest, latestPublicTheme } from "./store.js";
type NewsItem =
| { id: string; kind: "text"; text: string; url?: string; at: string }
| { id: string; kind: "release"; version: string; url: string; at: string }
| { id: string; kind: "theme"; name: string; author: string; at: string };
type TextItem = Extract<NewsItem, { kind: "text" }>;
const NEWS_DATA_FILE = process.env.NEWS_DATA_FILE;
const GITHUB_REPO = process.env.GITHUB_REPO ?? "WebSpeak3/webspeak3";
const MAX_ITEMS = 20;
const MAX_TEXT = 300;
const AUTO_MAX_AGE_MS = 30 * 24 * 60 * 60 * 1000;
let cache: TextItem[] | null = null;
async function load(): Promise<TextItem[]> {
if (cache) return cache;
if (!NEWS_DATA_FILE) return (cache = []);
try {
cache = JSON.parse(await readFile(NEWS_DATA_FILE, "utf-8")) as TextItem[];
} catch (err) {
if ((err as NodeJS.ErrnoException).code !== "ENOENT") throw err;
cache = [];
}
return cache;
}
async function save(items: TextItem[]) {
const tmp = `${NEWS_DATA_FILE}.tmp`;
await writeFile(tmp, JSON.stringify(items), "utf-8");
await rename(tmp, NEWS_DATA_FILE!);
cache = items;
}
// Unauthenticated GitHub API allows 60 requests/hour; one per hour is plenty.
let release: { item: NewsItem | null; fetchedAt: number } = { item: null, fetchedAt: 0 };
async function latestRelease(): Promise<NewsItem | null> {
if (Date.now() - release.fetchedAt < 60 * 60 * 1000) return release.item;
release.fetchedAt = Date.now();
try {
const res = await fetch(`https://api.github.com/repos/${GITHUB_REPO}/releases?per_page=1`, {
headers: { Accept: "application/vnd.github+json", "User-Agent": "webspeak3-store" },
});
if (!res.ok) return release.item;
const [r] = (await res.json()) as { tag_name: string; html_url: string; published_at: string }[];
release.item = r ? { id: `release-${r.tag_name}`, kind: "release", version: r.tag_name, url: r.html_url, at: r.published_at } : null;
} catch (err) {
console.error("[news] Release lookup failed:", err);
}
return release.item;
}
function isRecent(item: NewsItem | null | undefined): item is NewsItem {
return item != null && Date.now() - Date.parse(item.at) < AUTO_MAX_AGE_MS;
}
function json(res: ServerResponse, status: number, body: unknown) {
res.writeHead(status, { "Content-Type": "application/json" });
res.end(JSON.stringify(body));
}
async function readBody(req: IncomingMessage): Promise<Record<string, unknown> | null> {
let raw = "";
for await (const chunk of req) {
raw += chunk;
if (raw.length > 5_000) return null;
}
try {
const parsed = JSON.parse(raw) as unknown;
return parsed && typeof parsed === "object" ? (parsed as Record<string, unknown>) : null;
} catch {
return null;
}
}
export async function handleNewsFeed(req: IncomingMessage, res: ServerResponse, pathname: string) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
res.setHeader("Access-Control-Allow-Headers", "Content-Type, Authorization");
if (req.method === "OPTIONS") {
res.writeHead(204);
res.end();
return;
}
if (pathname === "/api/store/news") {
const theme = await latestPublicTheme();
const auto = [
await latestRelease(),
theme && ({ id: `theme-${theme.id}`, kind: "theme", name: theme.name, author: theme.author, at: theme.createdAt } as NewsItem),
].filter(isRecent);
res.setHeader("Cache-Control", "public, max-age=300");
json(res, 200, { items: [...(await load()), ...auto] });
return;
}
// /api/store/news/admin: GET lists, POST {action:"add",text,url?} or {action:"delete",id}.
if (!NEWS_DATA_FILE) return json(res, 404, { error: "not_found" });
if (!isAdminRequest(req)) return json(res, 401, { error: "unauthorized" });
if (req.method === "GET") return json(res, 200, { items: await load() });
if (req.method !== "POST") return json(res, 405, { error: "method_not_allowed" });
const body = await readBody(req);
const items = [...(await load())];
if (body?.action === "delete" && typeof body.id === "string") {
await save(items.filter((i) => i.id !== body.id));
return json(res, 200, { ok: true });
}
if (body?.action === "add" && typeof body.text === "string" && body.text.trim()) {
const url = typeof body.url === "string" && /^https:\/\/\S+$/.test(body.url.trim()) ? body.url.trim() : undefined;
if (items.length >= MAX_ITEMS) return json(res, 400, { error: "too_many_items" });
items.push({ id: randomUUID(), kind: "text", text: body.text.trim().slice(0, MAX_TEXT), url, at: new Date().toISOString() });
await save(items);
return json(res, 200, { ok: true });
}
json(res, 400, { error: "bad_request" });
}
const NEWS_TICKER = process.env.NEWS_TICKER !== "0";
const NEWS_TICKER_CENTRAL = process.env.NEWS_TICKER_CENTRAL !== "0";
const LOCAL_ITEMS: NewsItem[] = (process.env.NEWS_TICKER_MESSAGES ?? "")
.split("|")
.map((text) => text.trim().slice(0, MAX_TEXT))
.filter(Boolean)
.map((text, i) => ({ id: `local-${i}-${text}`, kind: "text", text, at: "" }));
export function handleNewsConfig(res: ServerResponse) {
res.setHeader("Access-Control-Allow-Origin", "*");
res.setHeader("Cache-Control", "public, max-age=300");
json(res, 200, NEWS_TICKER ? { enabled: true, central: NEWS_TICKER_CENTRAL, items: LOCAL_ITEMS } : { enabled: false });
}
+11
View File
@@ -7,6 +7,7 @@
import { createServer } from "node:http";
import { handleStore } from "./store.js";
import { handlePing } from "./ping.js";
import { handleNewsFeed } from "./news.js";
const PORT = Number(process.env.PORT ?? 8080);
@@ -28,6 +29,16 @@ createServer((req, res) => {
});
return;
}
if (pathname === "/api/store/news" || pathname === "/api/store/news/admin") {
handleNewsFeed(req, res, pathname).catch((err) => {
console.error("[news] Request failed:", err);
if (!res.headersSent) {
res.writeHead(500, { "Content-Type": "application/json" });
res.end(JSON.stringify({ error: "internal" }));
}
});
return;
}
if (pathname === "/api/ping" || pathname === "/api/ping/stats") {
handlePing(req, res, pathname).catch((err) => {
console.error("[ping] Request failed:", err);
+5
View File
@@ -147,6 +147,11 @@ function isPublic(theme: StoreTheme): boolean {
return theme.status === "approved" && isSafeThemeCss(theme.css);
}
/** Newest public design, for the news ticker (news.ts). */
export async function latestPublicTheme(): Promise<StoreTheme | undefined> {
return (await loadStoreThemes()).filter(isPublic).sort((a, b) => b.createdAt.localeCompare(a.createdAt))[0];
}
// Same in-memory-per-IP approach as FEEDBACK_RATE_LIMIT in index.ts; kept as a
// separate map since the two endpoints are independent.
const STORE_RATE_LIMIT = 5;
+64
View File
@@ -2605,6 +2605,70 @@
font-size: 11px;
}
.ts-news-ticker {
flex-shrink: 0;
display: flex;
align-items: center;
gap: 0.5rem;
border-top: 1px solid var(--border-soft);
background: var(--log-bg);
color: var(--log-text);
padding: 0.15rem 0.6rem;
font-size: 11px;
}
.ts-news-label {
font-weight: 600;
flex-shrink: 0;
}
.ts-news-track {
flex: 1;
overflow: hidden;
white-space: nowrap;
}
.ts-news-scroll {
display: inline-block;
animation: ts-news-scroll linear infinite;
}
.ts-news-ticker:hover .ts-news-scroll {
animation-play-state: paused;
}
.ts-news-item {
padding-right: 3rem;
}
.ts-news-item a {
color: inherit;
}
.ts-news-close {
flex-shrink: 0;
background: none;
border: none;
color: inherit;
cursor: pointer;
padding: 0 0.2rem;
}
@keyframes ts-news-scroll {
from {
transform: translateX(0);
}
to {
transform: translateX(-50%);
}
}
@media (prefers-reduced-motion: reduce) {
.ts-news-scroll {
animation: none;
}
}
.ts-log-info {
color: var(--log-text);
}
+104
View File
@@ -188,6 +188,14 @@ const FEEDBACK_URL = import.meta.env.DEV
? `${import.meta.env.VITE_GATEWAY_URL.replace(/\/$/, "").replace(/^ws(s?):\/\//, "http$1://")}/api/feedback`
: `${window.location.protocol}//${window.location.host}/api/feedback`;
// News ticker: the instance's own gateway says whether it's on and adds its
// own messages (gateway/src/news.ts); the central feed is fetched directly,
// like the store. The demo has no gateway and only shows the central feed.
const NEWS_CONFIG_URL = DEMO_MODE ? null : FEEDBACK_URL.replace(/\/api\/feedback$/, "/api/news");
const NEWS_FEED_URL = import.meta.env.DEV
? "http://localhost:8080/api/store/news"
: import.meta.env.VITE_NEWS_URL || "https://gateway.webspeak3.de/api/store/news";
// Unlike GATEWAY_URL/FEEDBACK_URL above, the design store is NOT per-instance:
// it's a single, centrally curated catalog run on the maintainer's own VPS
// (see gateway/src/store.ts), so every build - official and self-hosted
@@ -2580,6 +2588,101 @@ function FeedbackFab({ onOpen, stacked }: { onOpen: () => void; stacked: boolean
}
/** Small donation pill, pinned to the bottom right corner. */
type NewsItem =
| { id: string; kind: "text"; text: string; url?: string }
| { id: string; kind: "release"; version: string; url: string }
| { id: string; kind: "theme"; name: string; author: string };
const NEWS_DISMISSED_STORAGE_KEY = "webspeak3.newsTicker.dismissed";
// Like the scrolling news line at the bottom of the native TS3 client.
// Dismissing hides the current set of items until a new one shows up.
function NewsTicker() {
const t = useT();
const [items, setItems] = useState<NewsItem[]>([]);
const [dismissed, setDismissed] = useState(() => {
try {
return localStorage.getItem(NEWS_DISMISSED_STORAGE_KEY) ?? "";
} catch {
return "";
}
});
useEffect(() => {
const getJson = async (url: string) => {
const res = await fetch(url);
if (!res.ok) throw new Error(String(res.status));
return res.json();
};
const load = async () => {
// A gateway older than the ticker answers 404: treat it as the default.
const config = (NEWS_CONFIG_URL ? await getJson(NEWS_CONFIG_URL).catch(() => null) : null) ?? {
enabled: true,
central: true,
items: [],
};
if (!config.enabled) return setItems([]);
const central = config.central ? ((await getJson(NEWS_FEED_URL).catch(() => null))?.items ?? []) : [];
setItems([...config.items, ...central]);
};
void load();
const timer = window.setInterval(() => void load(), 15 * 60 * 1000);
return () => window.clearInterval(timer);
}, []);
const key = items.map((i) => i.id).join(",");
if (!items.length || key === dismissed) return null;
const label = (item: NewsItem) =>
item.kind === "release"
? t("news.release", { version: item.version })
: item.kind === "theme"
? t("news.theme", { name: item.name, author: item.author })
: item.text;
const entries = items.map((item) => {
const url = item.kind === "theme" ? undefined : item.url;
return (
<span key={item.id} className="ts-news-item">
{url ? (
<a href={url} target="_blank" rel="noopener noreferrer">
{label(item)}
</a>
) : (
label(item)
)}
</span>
);
});
return (
<div className="ts-news-ticker">
<span className="ts-news-label">{t("news.label")}</span>
<div className="ts-news-track">
{/* Rendered twice so the -50% scroll loops seamlessly. */}
<div className="ts-news-scroll" style={{ animationDuration: `${Math.max(20, items.length * 12)}s` }}>
{entries}
<span aria-hidden="true">{entries}</span>
</div>
</div>
<button
className="ts-news-close"
title={t("dialog.close")}
aria-label={t("dialog.close")}
onClick={() => {
setDismissed(key);
try {
localStorage.setItem(NEWS_DISMISSED_STORAGE_KEY, key);
} catch {
// ignore
}
}}
>
✕
</button>
</div>
);
}
function DonateFab() {
const t = useT();
if (!DONATE_URL) return null;
@@ -12323,6 +12426,7 @@ function AppInner() {
);
})}
</div>
<NewsTicker />
</div>
);
}
+3
View File
@@ -42,6 +42,9 @@
"donate.title": "Podpořit WebSpeak3 na Ko-fi",
"pwa.updateAvailable": "Je k dispozici nová verze",
"pwa.reload": "Načíst znovu",
"news.label": "Novinky",
"news.release": "Vyšel WebSpeak3 {version}",
"news.theme": "Nový vzhled v obchodě: „{name}“ od {author}",
"feedback.dialog.title": "Zpětná vazba",
"feedback.dialog.intro": "Report bug or share idea to help improve WebSpeak3.",
"feedback.dialog.category": "Kategorie",
+3
View File
@@ -42,6 +42,9 @@
"donate.title": "WebSpeak3 auf Ko-fi unterstützen",
"pwa.updateAvailable": "Neue Version verfügbar",
"pwa.reload": "Neu laden",
"news.label": "News",
"news.release": "WebSpeak3 {version} ist erschienen",
"news.theme": "Neues Design im Store: „{name}“ von {author}",
"feedback.dialog.title": "Feedback",
"feedback.dialog.intro": "Melde einen Fehler oder teile eine Idee zur Weiterentwicklung von WebSpeak3 mit.",
"feedback.dialog.category": "Kategorie",
+3
View File
@@ -42,6 +42,9 @@
"donate.title": "Support WebSpeak3 on Ko-fi",
"pwa.updateAvailable": "New version available",
"pwa.reload": "Reload",
"news.label": "News",
"news.release": "WebSpeak3 {version} is out",
"news.theme": "New design in the store: \"{name}\" by {author}",
"feedback.dialog.title": "Feedback",
"feedback.dialog.intro": "Report a bug or share an idea to help improve WebSpeak3.",
"feedback.dialog.category": "Category",
+3
View File
@@ -42,6 +42,9 @@
"donate.title": "حمایت از WebSpeak3 در Ko-fi",
"pwa.updateAvailable": "نسخه جدید موجود است",
"pwa.reload": "بارگذاری مجدد",
"news.label": "اخبار",
"news.release": "WebSpeak3 {version} منتشر شد",
"news.theme": "طرح جدید در فروشگاه: «{name}» از {author}",
"feedback.dialog.title": "بازخورد",
"feedback.dialog.intro": "یک اشکال گزارش بده یا ایده‌ای برای بهبود WebSpeak3 به اشتراک بگذار.",
"feedback.dialog.category": "دسته",
+3
View File
@@ -540,6 +540,9 @@
"donate.title": "在 Ko-fi 上支持 WebSpeak3",
"pwa.updateAvailable": "有新版本可用",
"pwa.reload": "重新加载",
"news.label": "新闻",
"news.release": "WebSpeak3 {version} 已发布",
"news.theme": "商店新设计:“{name}”,作者 {author}",
"feedback.dialog.title": "反馈",
"feedback.dialog.intro": "报告一个问题,或分享改进 WebSpeak3 的想法。",
"feedback.dialog.category": "类别",