From e19ced1bd1905460d9eb4c80ebf19b1ff0e30146 Mon Sep 17 00:00:00 2001 From: Moepchi Date: Sat, 14 Nov 2026 16:50:10 +0000 Subject: [PATCH] Optional Cloudflare Turnstile bot check before connecting With TURNSTILE_SITE_KEY and TURNSTILE_SECRET set, the gateway answers a connect without a valid pass with "turnstileRequired". The browser solves the (usually invisible) check and resends the connect with the token; the gateway verifies it and hands out a pass bound to the client IP for 12 h, so reconnects and new tabs skip the check. Off by default. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU --- README.md | 1 + gateway/src/index.ts | 18 +++++- gateway/src/turnstile.ts | 49 +++++++++++++++++ web/src/App.css | 9 +++ web/src/App.tsx | 110 +++++++++++++++++++++++++++++++++---- web/src/locales/cs-CZ.json | 1 + web/src/locales/de.json | 1 + web/src/locales/en.json | 1 + web/src/locales/fa.json | 1 + web/src/locales/ru.json | 1 + web/src/locales/zh-CN.json | 1 + 11 files changed, 182 insertions(+), 11 deletions(-) create mode 100644 gateway/src/turnstile.ts diff --git a/README.md b/README.md index 304bb46..611b21d 100644 --- a/README.md +++ b/README.md @@ -243,6 +243,7 @@ All optional; add them under `environment:` in your compose override next to `PO | `TURN_URLS` | unset | Comma-separated TURN URLs (e.g. `turn:turn.example.com:3478`) offered to browsers for screen streams, for viewers or publishers behind NATs where direct P2P fails. Pair with `TURN_SECRET` (coturn's `use-auth-secret`; each browser gets its own credential valid for 24 h) or with static `TURN_USERNAME` / `TURN_CREDENTIAL`, which every visitor can read. | | `ALLOWED_ORIGINS` | unset (any origin) | Comma-separated list of web origins allowed to open `/ws` (e.g. `https://client.example.com`). Stops other websites from silently using your gateway as their relay. | | `MAX_CONNECTIONS_PER_IP` / `MAX_CONNECTIONS` | `10` / `60` | Concurrent `/ws` connections per client IP and in total (each can hold a live TeamSpeak session). `0` disables a limit. | +| `TURNSTILE_SITE_KEY` / `TURNSTILE_SECRET` | *(unset)* | Optional [Cloudflare Turnstile](https://developers.cloudflare.com/turnstile/) bot check before connecting. With both set, a browser solves the (usually invisible) check once and gets a pass bound to its IP for 12 h. Keeps scripts from opening TeamSpeak connections through your gateway. | | `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). | diff --git a/gateway/src/index.ts b/gateway/src/index.ts index d461df0..be41260 100644 --- a/gateway/src/index.ts +++ b/gateway/src/index.ts @@ -11,6 +11,7 @@ import { handleStore } from "./store.js"; import { handleNewsConfig } from "./news.js"; import { logFeedback, logConnectionEvent } from "./activity-log.js"; import { clientIp, createRateLimiter } from "./net.js"; +import { TURNSTILE_ENABLED, TURNSTILE_SITE_KEY, isValidPass, issuePass, verifyToken } from "./turnstile.js"; import "./telemetry.js"; // TeamSpeak 2 support is experimental and opt-in (ENABLE_TS2=1). @@ -490,7 +491,7 @@ const requestHandler = (req: IncomingMessage, res: ServerResponse) => { // Same list as the "hello" message, readable before any connect // (the connect dialog offers TeamSpeak 2 only when it is enabled). res.writeHead(200, { "Content-Type": "application/json", "Access-Control-Allow-Origin": "*", "Cache-Control": "public, max-age=300" }); - res.end(JSON.stringify({ features: GATEWAY_FEATURES })); + res.end(JSON.stringify({ features: GATEWAY_FEATURES, ...(TURNSTILE_ENABLED ? { turnstileSiteKey: TURNSTILE_SITE_KEY } : {}) })); return; } if (requestUrl.pathname === "/api/news") { @@ -755,6 +756,21 @@ wss.on("connection", (socket: WebSocket, req: IncomingMessage) => { ); break; } + if (TURNSTILE_ENABLED && !isValidPass(msg.turnstilePass, ip)) { + // No (valid) pass yet: ask the browser to solve the check, it + // resends this connect with the token. + if (msg.turnstileToken === undefined) { + socket.send(JSON.stringify({ type: "turnstileRequired" })); + break; + } + if (!(await verifyToken(msg.turnstileToken, ip))) { + socket.send( + JSON.stringify({ type: "error", code: "turnstile_failed", message: "Bot check failed. Please try again." }), + ); + break; + } + 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) { diff --git a/gateway/src/turnstile.ts b/gateway/src/turnstile.ts new file mode 100644 index 0000000..c9d71cf --- /dev/null +++ b/gateway/src/turnstile.ts @@ -0,0 +1,49 @@ +// Optional Cloudflare Turnstile bot check before a "connect". Off unless both +// TURNSTILE_SITE_KEY and TURNSTILE_SECRET are set. A solved check earns a +// signed pass (bound to the client IP, valid PASS_TTL_MS) that later connects +// and silent reconnects present instead, so a real user sees the check at +// most once in that window. +import { createHmac, timingSafeEqual } from "node:crypto"; + +export const TURNSTILE_SITE_KEY = process.env.TURNSTILE_SITE_KEY ?? ""; +const SECRET = process.env.TURNSTILE_SECRET ?? ""; +export const TURNSTILE_ENABLED = TURNSTILE_SITE_KEY !== "" && SECRET !== ""; + +const PASS_TTL_MS = 12 * 60 * 60 * 1000; +// Derived from the secret, so passes survive a gateway restart. +const PASS_KEY = createHmac("sha256", SECRET).update("webspeak3-turnstile-pass").digest(); + +const sign = (ip: string, expires: number) => + createHmac("sha256", PASS_KEY).update(`${ip}|${expires}`).digest("base64url"); + +export function issuePass(ip: string): string { + const expires = Date.now() + PASS_TTL_MS; + return `${expires}.${sign(ip, expires)}`; +} + +export function isValidPass(pass: unknown, ip: string): boolean { + if (typeof pass !== "string") return false; + const [exp, mac] = pass.split("."); + const expires = Number(exp); + if (!Number.isFinite(expires) || expires < Date.now() || !mac) return false; + const expected = Buffer.from(sign(ip, expires)); + const given = Buffer.from(mac); + return given.length === expected.length && timingSafeEqual(given, expected); +} + +export async function verifyToken(token: unknown, ip: string): Promise { + if (typeof token !== "string" || token.length === 0 || token.length > 2048) return false; + try { + const res = await fetch("https://challenges.cloudflare.com/turnstile/v0/siteverify", { + method: "POST", + body: new URLSearchParams({ secret: SECRET, response: token, remoteip: ip }), + signal: AbortSignal.timeout(10_000), + }); + const data = (await res.json()) as { success?: boolean; "error-codes"?: string[] }; + if (!data.success) console.warn(`[turnstile] rejected: ${(data["error-codes"] ?? []).join(",")}`); + return data.success === true; + } catch (err) { + console.warn(`[turnstile] siteverify failed: ${err}`); + return false; + } +} diff --git a/web/src/App.css b/web/src/App.css index cdba1f9..6e01a6d 100644 --- a/web/src/App.css +++ b/web/src/App.css @@ -5915,3 +5915,12 @@ input.ts-identities-uid { .ts-app.ts-mobile.ts-design-ide .ts-tree-panel { max-height: none; } + +/* Cloudflare Turnstile: empty unless Cloudflare wants an interaction. */ +.ts-turnstile { + position: fixed; + left: 50%; + top: 50%; + transform: translate(-50%, -50%); + z-index: 10000; +} diff --git a/web/src/App.tsx b/web/src/App.tsx index 41d0b3f..f832d1c 100644 --- a/web/src/App.tsx +++ b/web/src/App.tsx @@ -401,14 +401,73 @@ function loadServerType(): ServerType { // The gateway's feature list, readable before connecting. TeamSpeak 2 is // opt-in per gateway (ENABLE_TS2), so the connect dialog only offers it then. const FEATURES_URL = DEMO_MODE ? null : FEEDBACK_URL.replace(/\/api\/feedback$/, "/api/features"); -let gatewayFeaturesPromise: Promise | null = null; +type GatewayInfo = { features?: unknown; turnstileSiteKey?: unknown }; +let gatewayInfoPromise: Promise | null = null; +function fetchGatewayInfo(): Promise { + if (!FEATURES_URL) return Promise.resolve({}); + gatewayInfoPromise ??= fetch(FEATURES_URL) + .then((r) => (r.ok ? r.json() : {})) + .catch(() => ({})); + return gatewayInfoPromise; +} function fetchGatewayFeatures(): Promise { - if (!FEATURES_URL) return Promise.resolve([]); - gatewayFeaturesPromise ??= fetch(FEATURES_URL) - .then((r) => (r.ok ? r.json() : { features: [] })) - .then((d) => (Array.isArray(d.features) ? d.features : [])) - .catch(() => []); - return gatewayFeaturesPromise; + return fetchGatewayInfo().then((d) => (Array.isArray(d.features) ? d.features : [])); +} + +// Cloudflare Turnstile bot check, only when the gateway asks for it +// ("turnstileRequired"). Invisible for most visitors; the widget only shows +// up when Cloudflare wants an interaction. The gateway then hands out a pass +// (kept here) so later connects and reconnects skip the check. +const TURNSTILE_PASS_KEY = "ws3.turnstilePass"; +type TurnstileApi = { + render: (el: HTMLElement, opts: Record) => string; + remove: (id: string) => void; +}; +let turnstileScript: Promise | null = null; +function loadTurnstile(): Promise { + turnstileScript ??= new Promise((resolve, reject) => { + const s = document.createElement("script"); + s.src = "https://challenges.cloudflare.com/turnstile/v0/api.js?render=explicit"; + s.async = true; + s.onload = () => { + const api = (window as unknown as { turnstile?: TurnstileApi }).turnstile; + if (api) resolve(api); + else reject(new Error("turnstile missing")); + }; + s.onerror = () => { + turnstileScript = null; + reject(new Error("turnstile blocked")); + }; + document.head.appendChild(s); + }); + return turnstileScript; +} +async function getTurnstileToken(): Promise { + const { turnstileSiteKey } = await fetchGatewayInfo(); + if (typeof turnstileSiteKey !== "string") return ""; + try { + const api = await loadTurnstile(); + const box = document.createElement("div"); + box.className = "ts-turnstile"; + document.body.appendChild(box); + return await new Promise((resolve) => { + let id = ""; + const done = (token: string) => { + if (id) api.remove(id); + box.remove(); + resolve(token); + }; + id = api.render(box, { + sitekey: turnstileSiteKey, + appearance: "interaction-only", + callback: done, + "error-callback": () => done(""), + "timeout-callback": () => done(""), + }); + }); + } catch { + return ""; + } } /** Everything needed to (re)open a gateway connection for one session, kept @@ -9987,10 +10046,17 @@ function AppInner() { const connectFavoriteId = params.favoriteId; const connectIdentityBlob = identities.find((i) => i.id === connectIdentityId)?.blob ?? undefined; - const onopen = () => { - logClient("info", "Connection", `Connecting to ${connectHost}…`); + const sendConnect = (extra: Record = {}) => { + let turnstilePass: string | undefined; + try { + turnstilePass = localStorage.getItem(TURNSTILE_PASS_KEY) ?? undefined; + } catch { + /* storage blocked */ + } socket.send( JSON.stringify({ + ...extra, + turnstilePass, type: "connect", host: connectHost, nickname: connectNickname, @@ -10005,6 +10071,10 @@ function AppInner() { }) ); }; + const onopen = () => { + logClient("info", "Connection", `Connecting to ${connectHost}…`); + sendConnect(); + }; // Downloads arrive in pieces (see the connector's TRANSFER_CHUNK_BYTES), // keyed by channel + path; every piece but the last is a whole number of @@ -10044,6 +10114,20 @@ function AppInner() { setTurnServers(Array.isArray(data.iceServers) ? data.iceServers : []); return; } + if (data.type === "turnstileRequired") { + void getTurnstileToken().then((turnstileToken) => { + if (socket.readyState === WebSocket.OPEN) sendConnect({ turnstileToken }); + }); + return; + } + if (data.type === "turnstilePass") { + try { + localStorage.setItem(TURNSTILE_PASS_KEY, String(data.pass)); + } catch { + /* storage blocked: the check just runs again next time */ + } + return; + } // Inactive tab: update parked snapshot only (no audio playback). if (sessionId !== activeSessionIdRef.current) { @@ -10424,7 +10508,13 @@ function AppInner() { appendLog({ text: data.message, kind: "error" }); } else { setConnecting(false); - setConnectError(data.code === "gateway_full" ? t("connectError.gatewayFull") : data.message); + setConnectError( + data.code === "gateway_full" + ? t("connectError.gatewayFull") + : data.code === "turnstile_failed" + ? t("connectError.botCheck") + : data.message + ); updateTabMeta(sessionId, { connecting: false, connected: false }); } break; diff --git a/web/src/locales/cs-CZ.json b/web/src/locales/cs-CZ.json index dba514d..9a46e1b 100644 --- a/web/src/locales/cs-CZ.json +++ b/web/src/locales/cs-CZ.json @@ -718,6 +718,7 @@ "serverContext.disconnect": "Odpojit", "connectError.dismiss": "Zavřít", "connectError.gatewayFull": "Brána je právě plná. Zkus to za pár minut znovu – nebo si WebSpeak3 hostuj sám: github.com/WebSpeak3/webspeak3", + "connectError.botCheck": "Kontrola proti botům selhala. Obnov stránku a zkus to znovu. Blokátory reklam nebo skriptů mohou kontrole bránit.", "dialog.close": "Zavřít", "sounds.title": "Zvuky", "sounds.subtitle": "Nastavit zvuková upozornění na události", diff --git a/web/src/locales/de.json b/web/src/locales/de.json index d473782..fd78b68 100644 --- a/web/src/locales/de.json +++ b/web/src/locales/de.json @@ -718,6 +718,7 @@ "serverContext.disconnect": "Verbindung trennen", "connectError.dismiss": "Schließen", "connectError.gatewayFull": "Das Gateway ist gerade voll. Versuch es in ein paar Minuten nochmal – oder hoste WebSpeak3 selbst: github.com/WebSpeak3/webspeak3", + "connectError.botCheck": "Bot-Prüfung fehlgeschlagen. Bitte lade die Seite neu und versuch es noch mal. Werbe- oder Skriptblocker können die Prüfung stören.", "dialog.close": "Schließen", "sounds.title": "Sounds", "sounds.subtitle": "Sound-Benachrichtigungen für Ereignisse festlegen", diff --git a/web/src/locales/en.json b/web/src/locales/en.json index ab9d590..8649ef9 100644 --- a/web/src/locales/en.json +++ b/web/src/locales/en.json @@ -718,6 +718,7 @@ "serverContext.disconnect": "Disconnect", "connectError.dismiss": "Dismiss", "connectError.gatewayFull": "The gateway is full right now. Try again in a few minutes – or host WebSpeak3 yourself: github.com/WebSpeak3/webspeak3", + "connectError.botCheck": "Bot check failed. Please reload the page and try again. Ad or script blockers can get in the way of the check.", "dialog.close": "Close", "sounds.title": "Sounds", "sounds.subtitle": "Configure sound notifications for events", diff --git a/web/src/locales/fa.json b/web/src/locales/fa.json index 73d54c4..49fdd8a 100644 --- a/web/src/locales/fa.json +++ b/web/src/locales/fa.json @@ -717,6 +717,7 @@ "serverContext.disconnect": "قطع اتصال", "connectError.dismiss": "رد کردن", "connectError.gatewayFull": "گیت‌وی در حال حاضر پر است. چند دقیقه دیگر دوباره امتحان کنید – یا WebSpeak3 را خودتان میزبانی کنید: github.com/WebSpeak3/webspeak3", + "connectError.botCheck": "بررسی ضد ربات ناموفق بود. لطفاً صفحه را دوباره بارگذاری کنید و دوباره امتحان کنید. مسدودکننده‌های تبلیغات یا اسکریپت ممکن است مانع بررسی شوند.", "dialog.close": "بستن", "sounds.title": "صداها", "sounds.subtitle": "پیکربندی اعلان‌های صوتی برای رویدادها", diff --git a/web/src/locales/ru.json b/web/src/locales/ru.json index 1ea34e6..8fef7de 100644 --- a/web/src/locales/ru.json +++ b/web/src/locales/ru.json @@ -718,6 +718,7 @@ "serverContext.disconnect": "Отключиться", "connectError.dismiss": "Закрыть", "connectError.gatewayFull": "Шлюз сейчас переполнен. Попробуйте через несколько минут – или разверните WebSpeak3 у себя: github.com/WebSpeak3/webspeak3", + "connectError.botCheck": "Проверка на бота не пройдена. Обновите страницу и попробуйте снова. Блокировщики рекламы или скриптов могут мешать проверке.", "dialog.close": "Закрыть", "sounds.title": "Звуки", "sounds.subtitle": "Настройка звуковых уведомлений о событиях", diff --git a/web/src/locales/zh-CN.json b/web/src/locales/zh-CN.json index c1cede9..7a54835 100644 --- a/web/src/locales/zh-CN.json +++ b/web/src/locales/zh-CN.json @@ -559,6 +559,7 @@ "serverContext.disconnect": "断开连接", "connectError.dismiss": "关闭", "connectError.gatewayFull": "网关当前已满。请几分钟后再试,或自行部署 WebSpeak3:github.com/WebSpeak3/webspeak3", + "connectError.botCheck": "人机验证失败。请刷新页面后重试。广告或脚本拦截器可能会干扰验证。", "dialog.close": "关闭", "sounds.title": "声音", "sounds.subtitle": "配置事件提示音",