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>
114 lines
3.9 KiB
TypeScript
114 lines
3.9 KiB
TypeScript
/**
|
|
* The gate cookie: proof that this browser passed Turnstile recently.
|
|
*
|
|
* Format: `v1.<expiresAt>.<uaHash>.<signature>`
|
|
*
|
|
* - `expiresAt` — Unix seconds; checked on every request.
|
|
* - `uaHash` — first 16 base64url chars of SHA-256(User-Agent). Binds the
|
|
* cookie to the browser that solved the challenge, so a
|
|
* cookie lifted into a scraper with a different UA is dead.
|
|
* A browser update changes the UA and simply re-shows the
|
|
* gate, which is cheap.
|
|
* - signature — HMAC-SHA256 over `v1.<expiresAt>.<uaHash>`.
|
|
*
|
|
* The HMAC key is derived from the Turnstile secret (HMAC(secret, label)), so
|
|
* the deployment needs no second secret, and rotating the Turnstile secret
|
|
* invalidates every outstanding gate cookie as a side effect.
|
|
*/
|
|
|
|
const encoder = new TextEncoder();
|
|
const KEY_LABEL = "ytg-gate-v1";
|
|
|
|
function toBase64Url(bytes: Uint8Array): string {
|
|
let binary = "";
|
|
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
}
|
|
|
|
function fromBase64Url(text: string): Uint8Array<ArrayBuffer> | null {
|
|
if (!/^[A-Za-z0-9_-]+$/.test(text)) return null;
|
|
const padded = text.replace(/-/g, "+").replace(/_/g, "/") + "===".slice((text.length + 3) % 4);
|
|
try {
|
|
const binary = atob(padded);
|
|
const out = new Uint8Array(binary.length);
|
|
for (let i = 0; i < binary.length; i++) out[i] = binary.charCodeAt(i);
|
|
return out;
|
|
} catch {
|
|
return null;
|
|
}
|
|
}
|
|
|
|
const keyCache = new Map<string, Promise<CryptoKey>>();
|
|
|
|
/** The HMAC key for gate cookies, derived once per secret per isolate. */
|
|
export function deriveGateKey(secret: string): Promise<CryptoKey> {
|
|
let key = keyCache.get(secret);
|
|
if (!key) {
|
|
key = (async () => {
|
|
const master = await crypto.subtle.importKey(
|
|
"raw",
|
|
encoder.encode(secret),
|
|
{ name: "HMAC", hash: "SHA-256" },
|
|
false,
|
|
["sign"],
|
|
);
|
|
const derived = await crypto.subtle.sign("HMAC", master, encoder.encode(KEY_LABEL));
|
|
return crypto.subtle.importKey("raw", derived, { name: "HMAC", hash: "SHA-256" }, false, [
|
|
"sign",
|
|
"verify",
|
|
]);
|
|
})();
|
|
keyCache.set(secret, key);
|
|
}
|
|
return key;
|
|
}
|
|
|
|
export async function userAgentHash(userAgent: string): Promise<string> {
|
|
const digest = await crypto.subtle.digest("SHA-256", encoder.encode(userAgent));
|
|
return toBase64Url(new Uint8Array(digest)).slice(0, 16);
|
|
}
|
|
|
|
export async function signGateToken(
|
|
key: CryptoKey,
|
|
expiresAt: number,
|
|
uaHash: string,
|
|
): Promise<string> {
|
|
const payload = `v1.${expiresAt}.${uaHash}`;
|
|
const signature = await crypto.subtle.sign("HMAC", key, encoder.encode(payload));
|
|
return `${payload}.${toBase64Url(new Uint8Array(signature))}`;
|
|
}
|
|
|
|
/** True only for an unexpired, untampered token minted for this User-Agent. */
|
|
export async function verifyGateToken(
|
|
key: CryptoKey,
|
|
token: string,
|
|
nowSeconds: number,
|
|
uaHash: string,
|
|
): Promise<boolean> {
|
|
const parts = token.split(".");
|
|
if (parts.length !== 4) return false;
|
|
const [version, expiresRaw, tokenUa, signatureRaw] = parts as [string, string, string, string];
|
|
if (version !== "v1" || !/^\d{1,12}$/.test(expiresRaw)) return false;
|
|
if (Number(expiresRaw) <= nowSeconds) return false;
|
|
if (tokenUa !== uaHash) return false;
|
|
const signature = fromBase64Url(signatureRaw);
|
|
if (!signature) return false;
|
|
return crypto.subtle.verify(
|
|
"HMAC",
|
|
key,
|
|
signature,
|
|
encoder.encode(`${version}.${expiresRaw}.${tokenUa}`),
|
|
);
|
|
}
|
|
|
|
/** Read one cookie out of a `Cookie` request header. */
|
|
export function readCookie(header: string | null, name: string): string | null {
|
|
if (!header) return null;
|
|
for (const part of header.split(";")) {
|
|
const eq = part.indexOf("=");
|
|
if (eq < 0) continue;
|
|
if (part.slice(0, eq).trim() === name) return part.slice(eq + 1).trim();
|
|
}
|
|
return null;
|
|
}
|