Files
youtube-generator/tests/worker/turnstile.test.ts
T
poli0981andClaude Opus 5.5 5ced6b4a86 feat(web): Turnstile gate, in-site legal pages and clean URLs on ytgenerator.stream
A Worker (worker/) now sits in front of the static build, configured from the
same wrangler.jsonc. Cloudflare builds and deploys it; nothing in GitHub
Actions does.

Gate
- First visit shows a branded check page (8 languages, Accept-Language) with
  Cloudflare Turnstile. The token is verified server-side against
  TURNSTILE_SECRET: success, hostname, action "enter", age <= 300 s. Only
  Cloudflare's own test-key results skip the hostname/action check, so
  `npm run cf:dev` works with the published test keys.
- Pass -> `__Host-ytg_gate` (HttpOnly, Secure, SameSite=Lax, 24 h): an HMAC
  over expiry + a user-agent hash, keyed from the Turnstile secret, so no
  second secret exists and a cookie copied into a scraper is useless.
- The page reloads in place instead of redirecting, so there is no `next`
  parameter to open-redirect with; /__gate/status lets the page tell a
  cookie-blocking browser what is wrong instead of looping; after one
  failure it waits for a click rather than resubmitting.
- Missing secret = deployment mistake: the site stays up without the gate and
  the Worker logs it, instead of locking every visitor out.
- The agree box on the gate records `ytg_terms`, which the app reads on boot
  so web visitors meet one blocking screen, not two.

Headers and static files
- worker/headers.ts sets CSP (nonce + strict-dynamic on the gate, no script
  at all on legal pages), nosniff, Referrer-Policy, Permissions-Policy, COOP,
  CORP, X-Frame-Options on everything the Worker returns; _headers covers
  the files served directly; a test keeps the two baselines identical.
- `not_found_handling: "404-page"` (a static 404.html) instead of the SPA
  fallback, which would have handed index.html past the gate for any
  excluded path. The Worker serves the shell itself by fetching "/" - not
  "/index.html", which html_handling would 307 back to the home page.
- security.txt (RFC 9116) is generated per build so Expires stays ~6 months
  ahead; the Web Analytics beacon is injected into the web build only.
- theme-init.js applies the saved theme before first paint (no inline script).

Legal in-site
- build-plugins/legal-docs.ts renders TERMS, PRIVACY, DISCLAIMER (+ vi),
  LICENSE, THIRD_PARTY_NOTICES, SECURITY, NOTICE and CODE_OF_CONDUCT at build
  time into static /legal pages (public, before the gate) and a lazy
  `virtual:legal-docs` module for the in-app Legal Center, which works
  offline on desktop and Android and never leaves the webview.
- PRIVACY, TERMS and SECURITY rewritten for Cloudflare hosting, Turnstile,
  Web Analytics and the two cookies; contacts moved to the poli0981.dev
  aliases (privacy@, legal@, dmca@, copyright@, security@, code@).
- CURRENT_TERMS_VERSION 1 -> 2: the Privacy Policy changed materially.

App
- Web uses BrowserRouter (real paths; analytics can count them), Tauri keeps
  HashRouter; old /#/x bookmarks are rewritten to /x before the router reads
  them. Consent is a layout route; /legal sits outside it.
- <html lang> follows the UI language; a stale chunk after a deploy triggers
  one reload instead of an error page.

.gitattributes pins LF everywhere so Windows checkouts stop failing Prettier.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-09-30 19:26:40 +07:00

131 lines
4.3 KiB
TypeScript

import { describe, it, expect, vi } from "vitest";
import { SITEVERIFY_URL } from "../../worker/env";
import { evaluateSiteverify, parseSiteverify, siteverify } from "../../worker/turnstile";
const NOW = Date.parse("2026-09-30T12:00:00Z");
const good = {
success: true,
hostname: "ytgenerator.stream",
action: "enter",
challengeTs: "2026-09-30T11:59:00Z",
errorCodes: [],
testing: false,
};
describe("evaluateSiteverify", () => {
it("accepts a fresh token for this hostname and action", () => {
expect(evaluateSiteverify(good, { hostname: "ytgenerator.stream", nowMs: NOW })).toEqual({
ok: true,
});
});
it.each([
[{ ...good, success: false }, "not-success"],
[{ ...good, hostname: "evil.example" }, "hostname-mismatch"],
[{ ...good, action: "login" }, "action-mismatch"],
[{ ...good, challengeTs: undefined }, "missing-timestamp"],
[{ ...good, challengeTs: "2026-09-30T11:54:00Z" }, "token-too-old"],
] as const)("refuses %o with %s", (result, reason) => {
expect(evaluateSiteverify(result, { hostname: "ytgenerator.stream", nowMs: NOW })).toEqual({
ok: false,
reason,
});
});
});
describe("test keys", () => {
it("accepts Cloudflare's dummy answer only when it is flagged as a test result", () => {
const dummy = parseSiteverify({
success: true,
hostname: "example.com",
challenge_ts: "2026-09-30T11:59:50Z",
"error-codes": [],
metadata: { result_with_testing_key: true },
});
expect(dummy.testing).toBe(true);
expect(evaluateSiteverify(dummy, { hostname: "localhost", nowMs: NOW })).toEqual({ ok: true });
expect(
evaluateSiteverify({ ...dummy, testing: false }, { hostname: "localhost", nowMs: NOW }),
).toEqual({ ok: false, reason: "hostname-mismatch" });
});
it("still refuses a failed or stale test result", () => {
const base = {
success: true,
testing: true,
errorCodes: [],
challengeTs: "2026-09-30T11:00:00Z",
};
expect(evaluateSiteverify(base, { hostname: "x", nowMs: NOW })).toEqual({
ok: false,
reason: "token-too-old",
});
expect(evaluateSiteverify({ ...base, success: false }, { hostname: "x", nowMs: NOW })).toEqual({
ok: false,
reason: "not-success",
});
});
});
describe("parseSiteverify", () => {
it("maps Cloudflare's field names", () => {
expect(
parseSiteverify({
success: true,
hostname: "h",
action: "a",
challenge_ts: "t",
"error-codes": ["x", 1],
}),
).toEqual({
success: true,
hostname: "h",
action: "a",
challengeTs: "t",
errorCodes: ["x"],
testing: false,
});
});
it("never treats a malformed body as success", () => {
expect(parseSiteverify(null).success).toBe(false);
expect(parseSiteverify("yes").success).toBe(false);
expect(parseSiteverify({ success: "true" }).success).toBe(false);
});
});
describe("siteverify", () => {
it("posts secret, token, remote IP and idempotency key", async () => {
const fetchMock = vi.fn(async () => Response.json({ success: true }));
await siteverify(fetchMock as unknown as typeof fetch, {
secret: "s3cret",
token: "tok",
remoteIp: "203.0.113.9",
idempotencyKey: "idem",
});
const [url, init] = fetchMock.mock.calls[0] as unknown as [string, RequestInit];
expect(url).toBe(SITEVERIFY_URL);
expect(init.method).toBe("POST");
const body = init.body as URLSearchParams;
expect(body.get("secret")).toBe("s3cret");
expect(body.get("response")).toBe("tok");
expect(body.get("remoteip")).toBe("203.0.113.9");
expect(body.get("idempotency_key")).toBe("idem");
});
it("turns HTTP and network failures into a refusal instead of throwing", async () => {
const httpError = vi.fn(async () => new Response("down", { status: 503 }));
const networkError = vi.fn(async () => {
throw new TypeError("fetch failed");
});
const params = { secret: "s", token: "t", remoteIp: null, idempotencyKey: "i" };
await expect(siteverify(httpError as unknown as typeof fetch, params)).resolves.toMatchObject({
success: false,
errorCodes: ["http-503"],
});
await expect(
siteverify(networkError as unknown as typeof fetch, params),
).resolves.toMatchObject({ success: false, errorCodes: ["network-error"] });
});
});