feat(worker): verify the web app's Turnstile token at POST /api/human-check
The website is about to ask each browser to pass Cloudflare Turnstile. A
widget token proves nothing until siteverify confirms it, and the secret
that call needs cannot live in the page - so the page posts the token here
and gets a yes or no. That answer is ALL this produces: no cookie, no
session, nothing stored. The pages are prerendered and served without the
Worker, and docs/ToS.md section 9 promises that /api/data/*, /img/* and the
packaged apps are never human-checked, so nothing on the server could or
may require a pass.
- Same-origin only: POST, Origin equal to the request's own, Sec-Fetch-Site
(when sent) same-origin, JSON. No CORS - the apps never run the check.
- The body is read from the stream with a 4 KB cap, because a chunked
request carries no Content-Length; the JSON is parsed locally because a
SyntaxError message would quote the token into the logs.
- siteverify gets the secret, the token and CF-Connecting-IP, with an 8 s
timeout. The action ("enter", shared/human-check.ts, one definition for
both halves) and the hostname must match, except under Cloudflare's
published TEST secrets, whose answers are fixed ("localhost", "test").
- Statuses are chosen for the page, which refuses only on a verdict: 403
when Cloudflare said no; 503 without TURNSTILE_SECRET, so deploy order
never matters, or when a test widget's fixed token meets the real secret
(the site served on a hostname the widget does not know); 502 when
siteverify is unreachable, failing or garbled.
- Never logs the token or the IP; the tests spy on console to hold that.
TURNSTILE_SECRET is declared required in env.d.ts (an optional declaration
would clash with what `wrangler types` emits once .dev.vars defines it) and
checked at runtime. web/.dev.vars.example carries Cloudflare's always-pass
test secret for `wrangler dev`.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cc10ec8c2c
commit
40e83b17dc
7 files changed
+518
-1
No files matched your search
@@ -0,0 +1,11 @@
|
||||
# Local secrets for `wrangler dev` - copy to .dev.vars (gitignored) and edit.
|
||||
# Production secrets are set with `npx wrangler secret put <NAME>` and never
|
||||
# appear in this repository.
|
||||
|
||||
# Cloudflare Turnstile's published ALWAYS-PASS test secret, not a real one.
|
||||
# The web app renders the matching always-pass test widget on any hostname
|
||||
# other than free-steam-games.win, so the human check can be exercised end to
|
||||
# end on localhost. Swap in 2x0000000000000000000000000000000AA (always fails)
|
||||
# or 3x0000000000000000000000000000000AA (token already spent) to see the
|
||||
# refusal path; delete the line to see the "not configured" path.
|
||||
TURNSTILE_SECRET=1x0000000000000000000000000000000AA
|
||||
@@ -0,0 +1,34 @@
|
||||
/**
|
||||
* The web app's Turnstile human check, as both halves see it: the overlay that
|
||||
* renders the widget (src/lib/common/HumanCheck.svelte) and the Worker route
|
||||
* that verifies its token (worker/routes/human-check.ts).
|
||||
*
|
||||
* One definition, because the widget is rendered with an `action` that
|
||||
* siteverify echoes back and the Worker insists on. If the two ever named
|
||||
* different actions, every real visitor would fail the check.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Same-origin only. The web build calls it with a relative URL, and the route
|
||||
* sends no CORS header - the packaged apps never run the check, so nothing
|
||||
* cross-origin has a reason to reach it.
|
||||
*/
|
||||
export const HUMAN_CHECK_PATH = "/api/human-check";
|
||||
|
||||
/** Turnstile allows up to 32 characters of [A-Za-z0-9_-]. */
|
||||
export const HUMAN_CHECK_ACTION = "enter";
|
||||
|
||||
/** How long a pass lasts in the browser before the check runs again. */
|
||||
export const HUMAN_CHECK_TTL_SECONDS = 24 * 60 * 60;
|
||||
|
||||
/**
|
||||
* What the route answers. `ttl` comes with a pass; `codes` with a refusal, and
|
||||
* they are Cloudflare's own error strings (`invalid-input-response`,
|
||||
* `timeout-or-duplicate`, ...), never anything the visitor sent.
|
||||
*/
|
||||
export interface HumanCheckReply {
|
||||
ok?: boolean;
|
||||
ttl?: number;
|
||||
error?: string;
|
||||
codes?: string[];
|
||||
}
|
||||
Vendored
+10
-1
@@ -7,8 +7,9 @@
|
||||
* npx wrangler secret put GH_APP_ID
|
||||
* npx wrangler secret put GH_APP_INSTALLATION_ID
|
||||
* npx wrangler secret put GH_APP_PRIVATE_KEY
|
||||
* npx wrangler secret put TURNSTILE_SECRET
|
||||
*
|
||||
* See docs/ADMIN.md. Never move these into `vars`.
|
||||
* See docs/ADMIN.md and docs/SECURITY_SETUP.md. Never move these into `vars`.
|
||||
*/
|
||||
interface Env {
|
||||
/** Numeric App ID from the GitHub App settings page. */
|
||||
@@ -17,4 +18,12 @@ interface Env {
|
||||
GH_APP_INSTALLATION_ID: string;
|
||||
/** Full .pem contents, including the BEGIN/END lines. */
|
||||
GH_APP_PRIVATE_KEY: string;
|
||||
/**
|
||||
* The Turnstile widget's secret key, for siteverify
|
||||
* (worker/routes/human-check.ts). Typed as always present, but the route
|
||||
* checks it at runtime and answers 503 when it is not: declared optional,
|
||||
* it would clash with the `string` that `wrangler types` emits once a
|
||||
* web/.dev.vars defines it.
|
||||
*/
|
||||
TURNSTILE_SECRET: string;
|
||||
}
|
||||
@@ -132,4 +132,34 @@ describe("the country block", () => {
|
||||
expect((await from("VN")).status).not.toBe(403);
|
||||
expect((await from(null)).status).not.toBe(403);
|
||||
});
|
||||
|
||||
it("covers the human-check route like every other", async () => {
|
||||
expect((await from("CN", "/api/human-check")).status).toBe(403);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the human-check route", () => {
|
||||
// Through the real router: a handler test cannot notice the route being
|
||||
// shadowed by the /api/* 404 or pulled behind the Access block.
|
||||
it("is reached, not the /api/* catch-all", async () => {
|
||||
const res = await worker.fetch(new Request("https://free-steam-games.win/api/human-check"), env, ctx);
|
||||
expect(res.status).toBe(405);
|
||||
expect(res.headers.get("Content-Type")).toContain("application/json");
|
||||
});
|
||||
|
||||
it("is public: an unconfigured Worker answers 503, not an Access refusal", async () => {
|
||||
// makeEnv() carries no TURNSTILE_SECRET, so no siteverify call is made -
|
||||
// the fetch stub above would throw on one.
|
||||
const res = await worker.fetch(
|
||||
new Request("https://free-steam-games.win/api/human-check", {
|
||||
method: "POST",
|
||||
headers: { Origin: "https://free-steam-games.win", "Content-Type": "application/json" },
|
||||
body: JSON.stringify({ token: "x" }),
|
||||
}),
|
||||
env,
|
||||
ctx,
|
||||
);
|
||||
expect(res.status).toBe(503);
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -11,6 +11,8 @@ import { handleData } from "./routes/data";
|
||||
import { handleImg } from "./routes/img";
|
||||
import { handleActivity } from "./routes/activity";
|
||||
import { handleDesktopUpdates } from "./routes/updates";
|
||||
import { handleHumanCheck } from "./routes/human-check";
|
||||
import { HUMAN_CHECK_PATH } from "../shared/human-check";
|
||||
import { jsonError, withSecurityHeaders } from "./lib/http";
|
||||
import { verifyAccessJwt, AccessUnavailableError } from "./lib/access";
|
||||
import { handleAdminApi } from "./routes/admin";
|
||||
@@ -146,6 +148,12 @@ async function route(
|
||||
return handleDesktopUpdates(request, url, ctx);
|
||||
}
|
||||
|
||||
// Public as well: the web app's Turnstile check. Never behind Access, and
|
||||
// never with CORS - it is same-origin by design (routes/human-check.ts).
|
||||
if (pathname === HUMAN_CHECK_PATH) {
|
||||
return handleHumanCheck(request, url, env);
|
||||
}
|
||||
|
||||
// Everything below is admin surface. Authenticate ONCE, here, before any
|
||||
// dispatch — not inside each handler, where the next one added is the one
|
||||
// that forgets. Cloudflare Access also gates these paths at the edge; this
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { handleHumanCheck } from "./human-check";
|
||||
import {
|
||||
HUMAN_CHECK_ACTION,
|
||||
HUMAN_CHECK_PATH,
|
||||
HUMAN_CHECK_TTL_SECONDS,
|
||||
type HumanCheckReply,
|
||||
} from "../../shared/human-check";
|
||||
|
||||
/**
|
||||
* The Turnstile token check. It answers yes or no and nothing else, so what
|
||||
* matters is that each "no" is the right kind of no: 403 only when Cloudflare
|
||||
* (or the action/hostname) refuses, 503/502 when the fault is this site's -
|
||||
* the page lets people through on those - and never a CORS header.
|
||||
*/
|
||||
|
||||
const ORIGIN = "https://free-steam-games.win";
|
||||
const SECRET = "0x-production-secret-under-test";
|
||||
const TOKEN = "0.a-widget-token-under-test";
|
||||
const TEST_TOKEN = "XXXX.DUMMY.TOKEN.XXXX";
|
||||
const IP = "203.0.113.7";
|
||||
|
||||
const envWith = (secret?: string) => ({ TURNSTILE_SECRET: secret }) as unknown as Env;
|
||||
|
||||
interface CallOptions {
|
||||
method?: string;
|
||||
headers?: Record<string, string>;
|
||||
omit?: string[];
|
||||
raw?: string;
|
||||
}
|
||||
|
||||
function call(body: unknown = { token: TOKEN }, opts: CallOptions = {}, env = envWith(SECRET)) {
|
||||
const url = new URL(`${ORIGIN}${HUMAN_CHECK_PATH}`);
|
||||
const headers = new Headers({
|
||||
Origin: ORIGIN,
|
||||
"Sec-Fetch-Site": "same-origin",
|
||||
"Content-Type": "application/json",
|
||||
"CF-Connecting-IP": IP,
|
||||
...opts.headers,
|
||||
});
|
||||
for (const name of opts.omit ?? []) headers.delete(name);
|
||||
const method = opts.method ?? "POST";
|
||||
const hasBody = method !== "GET" && method !== "HEAD";
|
||||
const request = new Request(url, {
|
||||
method,
|
||||
headers,
|
||||
body: hasBody ? (opts.raw ?? JSON.stringify(body)) : undefined,
|
||||
});
|
||||
return handleHumanCheck(request, url, env);
|
||||
}
|
||||
|
||||
const verified = (fields: Record<string, unknown> = {}) =>
|
||||
Response.json({ success: true, hostname: "free-steam-games.win", action: HUMAN_CHECK_ACTION, ...fields });
|
||||
|
||||
let upstream: ReturnType<typeof vi.fn>;
|
||||
|
||||
beforeEach(() => {
|
||||
upstream = vi.fn();
|
||||
vi.stubGlobal("fetch", upstream);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals();
|
||||
vi.restoreAllMocks();
|
||||
});
|
||||
|
||||
describe("what the route refuses before asking Cloudflare", () => {
|
||||
it("answers only POST", async () => {
|
||||
for (const method of ["GET", "HEAD", "PUT"]) {
|
||||
expect((await call(undefined, { method })).status, method).toBe(405);
|
||||
}
|
||||
});
|
||||
|
||||
it("refuses a request with no Origin, a foreign one, or another site's browser", async () => {
|
||||
expect((await call(undefined, { omit: ["Origin"] })).status).toBe(403);
|
||||
expect((await call(undefined, { headers: { Origin: "https://evil.example" } })).status).toBe(403);
|
||||
expect((await call(undefined, { headers: { "Sec-Fetch-Site": "cross-site" } })).status).toBe(403);
|
||||
expect(upstream).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("still accepts a same-origin call that carries no Sec-Fetch-Site", async () => {
|
||||
upstream.mockResolvedValue(verified());
|
||||
expect((await call(undefined, { omit: ["Sec-Fetch-Site"] })).status).toBe(200);
|
||||
});
|
||||
|
||||
it("wants JSON", async () => {
|
||||
expect((await call(undefined, { headers: { "Content-Type": "text/plain" } })).status).toBe(415);
|
||||
});
|
||||
|
||||
it("answers 503, and never calls siteverify, when the secret is not set", async () => {
|
||||
const res = await call(undefined, {}, envWith(undefined));
|
||||
expect(res.status).toBe(503);
|
||||
expect(upstream).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("caps the body by what arrives, not only by what Content-Length claims", async () => {
|
||||
// Node's Request sets no Content-Length for a string body, so this is the
|
||||
// stream path - the one a chunked request would take.
|
||||
const res = await call(undefined, { raw: JSON.stringify({ token: "x".repeat(5000) }) });
|
||||
expect(res.status).toBe(413);
|
||||
expect(upstream).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("refuses bad JSON and anything that is not a 1-2048 character token", async () => {
|
||||
expect((await call(undefined, { raw: "{not json" })).status).toBe(400);
|
||||
for (const body of [{}, { token: "" }, { token: 42 }, { token: "x".repeat(2049) }, null]) {
|
||||
expect((await call(body)).status, JSON.stringify(body)?.slice(0, 40)).toBe(400);
|
||||
}
|
||||
expect(upstream).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
describe("the siteverify call", () => {
|
||||
it("posts the secret, the token and the visitor's IP, with a timeout", async () => {
|
||||
upstream.mockResolvedValue(verified());
|
||||
await call();
|
||||
expect(upstream).toHaveBeenCalledTimes(1);
|
||||
const [target, init] = upstream.mock.calls[0] as [string, RequestInit];
|
||||
expect(target).toBe("https://challenges.cloudflare.com/turnstile/v0/siteverify");
|
||||
expect(init.method).toBe("POST");
|
||||
const form = new URLSearchParams(String(init.body));
|
||||
expect(form.get("secret")).toBe(SECRET);
|
||||
expect(form.get("response")).toBe(TOKEN);
|
||||
expect(form.get("remoteip")).toBe(IP);
|
||||
expect(init.signal).toBeInstanceOf(AbortSignal);
|
||||
});
|
||||
|
||||
it("leaves remoteip out when the edge supplied none", async () => {
|
||||
upstream.mockResolvedValue(verified());
|
||||
await call(undefined, { omit: ["CF-Connecting-IP"] });
|
||||
const [, init] = upstream.mock.calls[0] as [string, RequestInit];
|
||||
expect(new URLSearchParams(String(init.body)).has("remoteip")).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe("the answer", () => {
|
||||
it("passes a verified token for this action and hostname, uncached and without CORS", async () => {
|
||||
upstream.mockResolvedValue(verified());
|
||||
const res = await call();
|
||||
expect(res.status).toBe(200);
|
||||
expect(await res.json()).toEqual({ ok: true, ttl: HUMAN_CHECK_TTL_SECONDS });
|
||||
expect(res.headers.get("Cache-Control")).toBe("no-store");
|
||||
expect(res.headers.get("X-Content-Type-Options")).toBe("nosniff");
|
||||
expect(res.headers.get("X-Frame-Options")).toBe("DENY");
|
||||
expect(res.headers.get("Access-Control-Allow-Origin")).toBeNull();
|
||||
});
|
||||
|
||||
it("refuses what Cloudflare refused, passing on only Cloudflare's own error strings", async () => {
|
||||
upstream.mockResolvedValue(
|
||||
Response.json({ success: false, "error-codes": ["invalid-input-response", 42, "<script>"] }),
|
||||
);
|
||||
const res = await call();
|
||||
expect(res.status).toBe(403);
|
||||
expect(await res.json()).toEqual({ ok: false, error: "rejected", codes: ["invalid-input-response"] });
|
||||
});
|
||||
|
||||
it("refuses a valid token minted for another action or on another hostname", async () => {
|
||||
const codesOf = async (res: Response) => ((await res.json()) as HumanCheckReply).codes;
|
||||
|
||||
upstream.mockResolvedValue(verified({ action: "login" }));
|
||||
const wrongAction = await call();
|
||||
expect(wrongAction.status).toBe(403);
|
||||
expect(await codesOf(wrongAction)).toEqual(["action-mismatch"]);
|
||||
|
||||
upstream.mockResolvedValue(verified({ hostname: "evil.example" }));
|
||||
const wrongHost = await call();
|
||||
expect(wrongHost.status).toBe(403);
|
||||
expect(await codesOf(wrongHost)).toEqual(["hostname-mismatch"]);
|
||||
});
|
||||
|
||||
it("accepts Cloudflare's fixed test answer only under a published test secret", async () => {
|
||||
const dummy = () => Response.json({ success: true, hostname: "localhost", action: "test" });
|
||||
upstream.mockImplementation(async () => dummy());
|
||||
const testSecret = envWith("1x0000000000000000000000000000000AA");
|
||||
expect((await call({ token: TEST_TOKEN }, {}, testSecret)).status).toBe(200);
|
||||
expect((await call()).status).toBe(403);
|
||||
});
|
||||
|
||||
it("treats a test widget's token against the real secret as a setup fault, not a refusal", async () => {
|
||||
// The page uses the test key on any hostname but production; if the real
|
||||
// Worker serves it somewhere else, every visitor would otherwise be refused.
|
||||
const res = await call({ token: TEST_TOKEN });
|
||||
expect(res.status).toBe(503);
|
||||
expect(upstream).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it("answers 502 when siteverify is unreachable, failing or garbled", async () => {
|
||||
upstream.mockRejectedValueOnce(new TypeError("network"));
|
||||
expect((await call()).status).toBe(502);
|
||||
upstream.mockResolvedValueOnce(new Response("oops", { status: 500 }));
|
||||
expect((await call()).status).toBe(502);
|
||||
upstream.mockResolvedValueOnce(new Response("<html>", { status: 200 }));
|
||||
expect((await call()).status).toBe(502);
|
||||
upstream.mockResolvedValueOnce(Response.json(null));
|
||||
expect((await call()).status).toBe(502);
|
||||
});
|
||||
|
||||
it("never logs the token or the visitor's IP", async () => {
|
||||
const logged: unknown[][] = [];
|
||||
for (const level of ["log", "warn", "error", "info"] as const) {
|
||||
vi.spyOn(console, level).mockImplementation((...args: unknown[]) => void logged.push(args));
|
||||
}
|
||||
upstream.mockResolvedValueOnce(Response.json({ success: false, "error-codes": ["timeout-or-duplicate"] }));
|
||||
await call();
|
||||
upstream.mockResolvedValueOnce(verified({ action: "other" }));
|
||||
await call();
|
||||
upstream.mockRejectedValueOnce(new TypeError(`fetch failed for ${TOKEN}`));
|
||||
await call();
|
||||
upstream.mockResolvedValueOnce(new Response("x", { status: 503 }));
|
||||
await call();
|
||||
await call(undefined, {}, envWith(undefined));
|
||||
|
||||
expect(logged.length).toBeGreaterThan(0);
|
||||
const text = JSON.stringify(logged);
|
||||
expect(text).not.toContain(TOKEN);
|
||||
expect(text).not.toContain(IP);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,207 @@
|
||||
/**
|
||||
* POST /api/human-check - verify the web app's Cloudflare Turnstile token.
|
||||
*
|
||||
* The website asks each browser to pass Turnstile once a day, after the terms
|
||||
* are accepted (src/lib/common/HumanCheck.svelte). A widget token proves
|
||||
* nothing until siteverify confirms it, and the secret that call needs cannot
|
||||
* live in the page - so the page posts the token here and gets a yes or no.
|
||||
*
|
||||
* THAT ANSWER IS ALL THIS PRODUCES. No cookie, no session, nothing stored. The
|
||||
* pages are prerendered and served without invoking the Worker, and
|
||||
* docs/ToS.md section 9 promises that /api/data/*, /img/* and the packaged apps
|
||||
* are never human-checked, so there is nothing a server-side pass could unlock.
|
||||
* The check is a door for people using the web app; the WAF rules in
|
||||
* docs/SECURITY_SETUP.md stay the boundary for everything else. Do not start
|
||||
* requiring a pass on the data or image routes - that breaks the promise.
|
||||
*
|
||||
* Same-origin only, and no CORS: the packaged apps never run the check. Beyond
|
||||
* refusing another site's browser there is no CSRF defence to add - a forged
|
||||
* request can learn only whether a token it already holds is valid, and a
|
||||
* token is minted on this site's hostname and spent by the first siteverify.
|
||||
*
|
||||
* Failure statuses are chosen for the page, which lets people through on
|
||||
* anything that is this site's fault rather than theirs:
|
||||
* 403 Cloudflare said no (or the action/hostname are wrong) - a verdict.
|
||||
* 503 TURNSTILE_SECRET is not set, so deploying this before
|
||||
* `wrangler secret put TURNSTILE_SECRET` locks nobody out; or a test
|
||||
* widget's token met the real secret (see TEST_TOKEN).
|
||||
* 502 siteverify was unreachable, slow or garbled.
|
||||
*/
|
||||
import {
|
||||
HUMAN_CHECK_ACTION,
|
||||
HUMAN_CHECK_TTL_SECONDS,
|
||||
type HumanCheckReply,
|
||||
} from "../../shared/human-check";
|
||||
import { jsonError, SECURITY_HEADERS } from "../lib/http";
|
||||
|
||||
const SITEVERIFY = "https://challenges.cloudflare.com/turnstile/v0/siteverify";
|
||||
/** A token is at most 2,048 characters; the JSON around it adds a dozen. */
|
||||
const MAX_BODY_BYTES = 4 * 1024;
|
||||
const MAX_TOKEN_LENGTH = 2048;
|
||||
const SITEVERIFY_TIMEOUT_MS = 8_000;
|
||||
|
||||
/**
|
||||
* Cloudflare's published TEST secrets: always passes, always fails, and
|
||||
* "already spent". Their siteverify answers carry a fixed `hostname:
|
||||
* "localhost"` and `action: "test"` whatever the widget sent, so the two checks
|
||||
* below cannot apply to them. Only `web/.dev.vars` ever holds one of these.
|
||||
*/
|
||||
const TEST_SECRETS = new Set([
|
||||
"1x0000000000000000000000000000000AA",
|
||||
"2x0000000000000000000000000000000AA",
|
||||
"3x0000000000000000000000000000000AA",
|
||||
]);
|
||||
|
||||
/**
|
||||
* What every TEST site key hands out. The page uses a test key on any hostname
|
||||
* but production (src/lib/human-check.ts, siteKeyFor), so this token reaching
|
||||
* a REAL secret means the site is being served somewhere the widget was never
|
||||
* set up for - a configuration fault, answered 503 so the page lets people
|
||||
* through rather than refusing everyone.
|
||||
*/
|
||||
const TEST_TOKEN = "XXXX.DUMMY.TOKEN.XXXX";
|
||||
|
||||
/** What siteverify returns, as far as this route reads it. */
|
||||
interface Siteverify {
|
||||
success?: unknown;
|
||||
"error-codes"?: unknown;
|
||||
hostname?: unknown;
|
||||
action?: unknown;
|
||||
}
|
||||
|
||||
function json(body: HumanCheckReply, status: number): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: {
|
||||
"Content-Type": "application/json; charset=utf-8",
|
||||
"Cache-Control": "no-store",
|
||||
...SECURITY_HEADERS,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* The body as text, or null past `max` bytes. Read from the stream rather than
|
||||
* with request.text(): a chunked body carries no Content-Length, and this is a
|
||||
* public endpoint, so the cap has to hold for what actually arrives.
|
||||
*/
|
||||
async function readCapped(request: Request, max: number): Promise<string | null> {
|
||||
if (Number(request.headers.get("Content-Length") ?? 0) > max) return null;
|
||||
if (!request.body) return "";
|
||||
const reader = request.body.getReader();
|
||||
const parts: Uint8Array[] = [];
|
||||
let size = 0;
|
||||
for (;;) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
size += value.byteLength;
|
||||
if (size > max) {
|
||||
await reader.cancel();
|
||||
return null;
|
||||
}
|
||||
parts.push(value);
|
||||
}
|
||||
const all = new Uint8Array(size);
|
||||
let offset = 0;
|
||||
for (const part of parts) {
|
||||
all.set(part, offset);
|
||||
offset += part.byteLength;
|
||||
}
|
||||
return new TextDecoder().decode(all);
|
||||
}
|
||||
|
||||
/** Cloudflare's error strings only, and only a few: they go back to the page. */
|
||||
function errorCodes(raw: unknown): string[] {
|
||||
if (!Array.isArray(raw)) return [];
|
||||
return raw.filter((c): c is string => typeof c === "string" && /^[a-z0-9-]{1,40}$/.test(c)).slice(0, 5);
|
||||
}
|
||||
|
||||
export async function handleHumanCheck(request: Request, url: URL, env: Env): Promise<Response> {
|
||||
if (request.method !== "POST") return jsonError(405, "method not allowed");
|
||||
|
||||
// Browsers send Origin on every POST, same-origin included, so a missing one
|
||||
// is a script - which has no business here either.
|
||||
const site = request.headers.get("Sec-Fetch-Site");
|
||||
if (request.headers.get("Origin") !== url.origin || (site !== null && site !== "same-origin")) {
|
||||
return jsonError(403, "same-origin requests only");
|
||||
}
|
||||
|
||||
if (!(request.headers.get("Content-Type") ?? "").startsWith("application/json")) {
|
||||
return jsonError(415, "expected application/json");
|
||||
}
|
||||
|
||||
const secret = env.TURNSTILE_SECRET;
|
||||
if (!secret) {
|
||||
console.error("human-check: TURNSTILE_SECRET is not set; the page lets visitors through");
|
||||
return jsonError(503, "human check not configured");
|
||||
}
|
||||
|
||||
const raw = await readCapped(request, MAX_BODY_BYTES);
|
||||
if (raw === null) return jsonError(413, "body too large");
|
||||
|
||||
// Parsed here, not left to the router's catch-all: a SyntaxError message
|
||||
// quotes part of its input, and that input is the token.
|
||||
let token: unknown;
|
||||
try {
|
||||
token = (JSON.parse(raw) as { token?: unknown } | null)?.token;
|
||||
} catch {
|
||||
return jsonError(400, "invalid json");
|
||||
}
|
||||
if (typeof token !== "string" || token.length === 0 || token.length > MAX_TOKEN_LENGTH) {
|
||||
return jsonError(400, `token must be a string of 1-${MAX_TOKEN_LENGTH} characters`);
|
||||
}
|
||||
if (token === TEST_TOKEN && !TEST_SECRETS.has(secret)) {
|
||||
console.error("human-check: a test widget's token reached the real secret; is the site served on another hostname?");
|
||||
return jsonError(503, "test widget against a production secret");
|
||||
}
|
||||
|
||||
const form = new URLSearchParams({ secret, response: token });
|
||||
const ip = request.headers.get("CF-Connecting-IP");
|
||||
if (ip) form.set("remoteip", ip);
|
||||
|
||||
let upstream: Response;
|
||||
try {
|
||||
upstream = await fetch(SITEVERIFY, {
|
||||
method: "POST",
|
||||
body: form,
|
||||
signal: AbortSignal.timeout(SITEVERIFY_TIMEOUT_MS),
|
||||
});
|
||||
} catch (err) {
|
||||
console.warn("human-check: siteverify unreachable", err instanceof Error ? err.name : "error");
|
||||
return jsonError(502, "siteverify unreachable");
|
||||
}
|
||||
if (!upstream.ok) {
|
||||
console.warn("human-check: siteverify error", { status: upstream.status });
|
||||
return jsonError(502, "siteverify error");
|
||||
}
|
||||
let outcome: Siteverify;
|
||||
try {
|
||||
outcome = (await upstream.json()) as Siteverify;
|
||||
} catch {
|
||||
return jsonError(502, "siteverify sent invalid JSON");
|
||||
}
|
||||
if (typeof outcome !== "object" || outcome === null) {
|
||||
return jsonError(502, "siteverify sent an unexpected shape");
|
||||
}
|
||||
|
||||
if (outcome.success !== true) {
|
||||
const codes = errorCodes(outcome["error-codes"]);
|
||||
console.warn("human-check: rejected", { codes });
|
||||
return json({ ok: false, error: "rejected", codes }, 403);
|
||||
}
|
||||
|
||||
// A valid token for a different action, or minted on another hostname the
|
||||
// widget also allows, is still not a pass for this page.
|
||||
if (!TEST_SECRETS.has(secret)) {
|
||||
if (outcome.action !== HUMAN_CHECK_ACTION) {
|
||||
console.warn("human-check: action mismatch");
|
||||
return json({ ok: false, error: "rejected", codes: ["action-mismatch"] }, 403);
|
||||
}
|
||||
if (outcome.hostname !== url.hostname) {
|
||||
console.warn("human-check: hostname mismatch");
|
||||
return json({ ok: false, error: "rejected", codes: ["hostname-mismatch"] }, 403);
|
||||
}
|
||||
}
|
||||
|
||||
return json({ ok: true, ttl: HUMAN_CHECK_TTL_SECONDS }, 200);
|
||||
}
|
||||
Reference in new issue
Block a user