mirror of
https://github.com/Moepchi/webspeak3.git
synced 2026-12-01 00:42:49 +08:00
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:
1 parent
4e04ddb526
commit
e19ced1bd1
11 files changed
+182
-11
No files matched your search
@@ -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
@@ -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;
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -717,6 +717,7 @@
|
||||
"serverContext.disconnect": "قطع اتصال",
|
||||
"connectError.dismiss": "رد کردن",
|
||||
"connectError.gatewayFull": "گیتوی در حال حاضر پر است. چند دقیقه دیگر دوباره امتحان کنید – یا WebSpeak3 را خودتان میزبانی کنید: github.com/WebSpeak3/webspeak3",
|
||||
"connectError.botCheck": "بررسی ضد ربات ناموفق بود. لطفاً صفحه را دوباره بارگذاری کنید و دوباره امتحان کنید. مسدودکنندههای تبلیغات یا اسکریپت ممکن است مانع بررسی شوند.",
|
||||
"dialog.close": "بستن",
|
||||
"sounds.title": "صداها",
|
||||
"sounds.subtitle": "پیکربندی اعلانهای صوتی برای رویدادها",
|
||||
|
||||
@@ -718,6 +718,7 @@
|
||||
"serverContext.disconnect": "Отключиться",
|
||||
"connectError.dismiss": "Закрыть",
|
||||
"connectError.gatewayFull": "Шлюз сейчас переполнен. Попробуйте через несколько минут – или разверните WebSpeak3 у себя: github.com/WebSpeak3/webspeak3",
|
||||
"connectError.botCheck": "Проверка на бота не пройдена. Обновите страницу и попробуйте снова. Блокировщики рекламы или скриптов могут мешать проверке.",
|
||||
"dialog.close": "Закрыть",
|
||||
"sounds.title": "Звуки",
|
||||
"sounds.subtitle": "Настройка звуковых уведомлений о событиях",
|
||||
|
||||
@@ -559,6 +559,7 @@
|
||||
"serverContext.disconnect": "断开连接",
|
||||
"connectError.dismiss": "关闭",
|
||||
"connectError.gatewayFull": "网关当前已满。请几分钟后再试,或自行部署 WebSpeak3:github.com/WebSpeak3/webspeak3",
|
||||
"connectError.botCheck": "人机验证失败。请刷新页面后重试。广告或脚本拦截器可能会干扰验证。",
|
||||
"dialog.close": "关闭",
|
||||
"sounds.title": "声音",
|
||||
"sounds.subtitle": "配置事件提示音",
|
||||
|
||||
Reference in new issue
Block a user