Files
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

88 lines
3.5 KiB
TypeScript

import { MAX_TOKEN_AGE_SECONDS, SITEVERIFY_URL, TURNSTILE_ACTION } from "./env";
/** The subset of Turnstile's siteverify response the gate relies on. */
export interface SiteverifyResult {
success: boolean;
hostname?: string;
action?: string;
challengeTs?: string;
errorCodes: string[];
/** Cloudflare's dummy test secret answered (local `wrangler dev` only). */
testing: boolean;
}
function asStringArray(value: unknown): string[] {
return Array.isArray(value) ? value.filter((v): v is string => typeof v === "string") : [];
}
/** Narrow siteverify's JSON without trusting its shape. */
export function parseSiteverify(json: unknown): SiteverifyResult {
if (typeof json !== "object" || json === null) {
return { success: false, errorCodes: ["bad-response"], testing: false };
}
const record = json as Record<string, unknown>;
const metadata =
typeof record.metadata === "object" && record.metadata !== null
? (record.metadata as Record<string, unknown>)
: {};
return {
success: record.success === true,
hostname: typeof record.hostname === "string" ? record.hostname : undefined,
action: typeof record.action === "string" ? record.action : undefined,
challengeTs: typeof record.challenge_ts === "string" ? record.challenge_ts : undefined,
errorCodes: asStringArray(record["error-codes"]),
testing: metadata.result_with_testing_key === true,
};
}
/**
* Validate a Turnstile token server-side. Network and HTTP failures resolve to
* `success: false` with an explanatory code rather than throwing, so the
* caller has one path to handle.
*/
export async function siteverify(
fetchImpl: typeof fetch,
params: { secret: string; token: string; remoteIp: string | null; idempotencyKey: string },
): Promise<SiteverifyResult> {
const body = new URLSearchParams({
secret: params.secret,
response: params.token,
idempotency_key: params.idempotencyKey,
});
if (params.remoteIp) body.set("remoteip", params.remoteIp);
try {
const res = await fetchImpl(SITEVERIFY_URL, { method: "POST", body });
if (!res.ok) return { success: false, errorCodes: [`http-${res.status}`], testing: false };
return parseSiteverify(await res.json());
} catch {
return { success: false, errorCodes: ["network-error"], testing: false };
}
}
export type VerdictReason =
"not-success" | "hostname-mismatch" | "action-mismatch" | "token-too-old" | "missing-timestamp";
/**
* The checks Cloudflare recommends on top of `success`: the token was minted
* for this hostname and this action, and it is not older than its 300 s life.
*/
export function evaluateSiteverify(
result: SiteverifyResult,
expected: { hostname: string; nowMs: number },
): { ok: true } | { ok: false; reason: VerdictReason } {
if (!result.success) return { ok: false, reason: "not-success" };
// Cloudflare's published test secret (used by `npm run cf:dev`) answers for
// "example.com" with no action. Only that secret can produce this flag, so a
// production deployment with its real secret is never relaxed.
if (!result.testing) {
if (result.hostname !== expected.hostname) return { ok: false, reason: "hostname-mismatch" };
if (result.action !== TURNSTILE_ACTION) return { ok: false, reason: "action-mismatch" };
}
const solvedAt = result.challengeTs ? Date.parse(result.challengeTs) : Number.NaN;
if (!Number.isFinite(solvedAt)) return { ok: false, reason: "missing-timestamp" };
if (expected.nowMs - solvedAt > MAX_TOKEN_AGE_SECONDS * 1000) {
return { ok: false, reason: "token-too-old" };
}
return { ok: true };
}