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 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Hu2cuPLqpuKVfd9wWFFakU
This commit is contained in:
MoepchiandClaude Opus 5.5 committed 2026-11-14 16:50:10 +00:00
1 parent 4e04ddb526
commit e19ced1bd1
11 files changed
+182 -11

No files matched your search

+1
View File
@@ -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). |
+17 -1
View File
@@ -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) {
+49
View File
@@ -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<boolean> {
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;
}
}
+9
View File
@@ -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;
}
+100 -10
View File
@@ -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<string[]> | null = null;
type GatewayInfo = { features?: unknown; turnstileSiteKey?: unknown };
let gatewayInfoPromise: Promise<GatewayInfo> | null = null;
function fetchGatewayInfo(): Promise<GatewayInfo> {
if (!FEATURES_URL) return Promise.resolve({});
gatewayInfoPromise ??= fetch(FEATURES_URL)
.then((r) => (r.ok ? r.json() : {}))
.catch(() => ({}));
return gatewayInfoPromise;
}
function fetchGatewayFeatures(): Promise<string[]> {
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, unknown>) => string;
remove: (id: string) => void;
};
let turnstileScript: Promise<TurnstileApi> | null = null;
function loadTurnstile(): Promise<TurnstileApi> {
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<string> {
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<string>((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<string, unknown> = {}) => {
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;
+1
View File
@@ -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",
+1
View File
@@ -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",
+1
View File
@@ -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",
+1
View File
@@ -717,6 +717,7 @@
"serverContext.disconnect": "قطع اتصال",
"connectError.dismiss": "رد کردن",
"connectError.gatewayFull": "گیت‌وی در حال حاضر پر است. چند دقیقه دیگر دوباره امتحان کنید – یا WebSpeak3 را خودتان میزبانی کنید: github.com/WebSpeak3/webspeak3",
"connectError.botCheck": "بررسی ضد ربات ناموفق بود. لطفاً صفحه را دوباره بارگذاری کنید و دوباره امتحان کنید. مسدودکننده‌های تبلیغات یا اسکریپت ممکن است مانع بررسی شوند.",
"dialog.close": "بستن",
"sounds.title": "صداها",
"sounds.subtitle": "پیکربندی اعلان‌های صوتی برای رویدادها",
+1
View File
@@ -718,6 +718,7 @@
"serverContext.disconnect": "Отключиться",
"connectError.dismiss": "Закрыть",
"connectError.gatewayFull": "Шлюз сейчас переполнен. Попробуйте через несколько минут – или разверните WebSpeak3 у себя: github.com/WebSpeak3/webspeak3",
"connectError.botCheck": "Проверка на бота не пройдена. Обновите страницу и попробуйте снова. Блокировщики рекламы или скриптов могут мешать проверке.",
"dialog.close": "Закрыть",
"sounds.title": "Звуки",
"sounds.subtitle": "Настройка звуковых уведомлений о событиях",
+1
View File
@@ -559,6 +559,7 @@
"serverContext.disconnect": "断开连接",
"connectError.dismiss": "关闭",
"connectError.gatewayFull": "网关当前已满。请几分钟后再试,或自行部署 WebSpeak3:github.com/WebSpeak3/webspeak3",
"connectError.botCheck": "人机验证失败。请刷新页面后重试。广告或脚本拦截器可能会干扰验证。",
"dialog.close": "关闭",
"sounds.title": "声音",
"sounds.subtitle": "配置事件提示音",