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
+17
-1
@@ -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) {
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user