diff --git a/.prettierignore b/.prettierignore index a28d1b7..bbc7174 100644 --- a/.prettierignore +++ b/.prettierignore @@ -3,6 +3,7 @@ # Except these files & folders !/src +!/functions !/public/**/*.ts !/public/**/*.js !/.github diff --git a/AGENTS.md b/AGENTS.md index 2a0b934..770923c 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -37,6 +37,7 @@ Personal blog ("Developer Musings") built on AstroPaper v7.1.0: Astro 7, TypeScr | `src/` | Site source: content, components, layouts, pages, utils (see `src/AGENTS.md`) | | `tests/` | Vitest unit tests; need `dist/` (see `tests/AGENTS.md`) | | `e2e/` | Playwright tests (see `e2e/AGENTS.md`) | +| `functions/` | Cloudflare Pages Functions: Turnstile gate in front of the whole site (see `functions/AGENTS.md`) | | `public/` | Static files served as-is, documented in "Static files" below (no `AGENTS.md` inside) | | `old-posts/` | Unused upstream AstroPaper demo posts (see `old-posts/AGENTS.md`) | | `.github/` | CI workflow (see `.github/AGENTS.md`) | @@ -88,6 +89,7 @@ The four PNGs in `20221008/` and `20221010/` are Git LFS objects (`.gitattribute | `src/assets/icons/socials/{youtube,reddit,mastodon}.svg` | ours | Icons upstream lacks | | `AGENTS.md`, `src/**/AGENTS.md`, `old-posts/**`, `tests/**`, `e2e/**`, `.github/AGENTS.md`, `.github/workflows/AGENTS.md` | ours | Docs and tests | | `public/_redirects` | ours | `/posts/1(/)` 301 | +| `functions/**`, `tests/functions/**` | ours | Turnstile edge gate (Pages Functions), ported from the bio repo | | `src/pages/index.astro` | upstream, hero changed | Hero `h1` "Musings of A Developer" and our intro paragraph replace upstream's demo greeting, description and README link | | `public/On the topic of tools, their versions & automated installations.png` | ours | Old OG URL kept alive | | `public/favicon.svg`, `public/favicon-old.svg`, `public/astropaper-og.jpg`, `public/assets/**` | ours | Site assets | diff --git a/CHANGELOG.md b/CHANGELOG.md index e17c725..134dfe5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,27 @@ +## 2026-11-12 21:40 + +| Check | Status | Details | +|-------|--------|---------| +| Lint | ✓ PASS | 0 errors | +| Build | ✓ PASS | 27 pages built, 5 pages indexed (Pagefind) | +| Unit Tests | ✓ PASS | 71 tests passed | +| E2E Tests | ✓ PASS | 96 tests passed | +| Lighthouse | ✓ PASS | 99.8% performance (avg) | + +### Lighthouse Performance (local build) + +| Page | Scores (3 runs) | +|------|-----------------| +| / (index) | 100%, 100%, 100% | +| /about | 99%, 99%, 99% | +| /posts | 100%, 100%, 100% | +| /archives (soft 404, not linked) | 100%, 100%, 100% | +| /404 | 100%, 100%, 100% | + +**Diagnostics:** The local build runs without the gate: Pages Functions only run on Cloudflare. Live site not measured. + +Changes: Gate the whole site behind Cloudflare Turnstile, ported from the bio repo. `functions/_middleware.ts` serves a challenge page (401, `noindex`) without a valid `blog_session` cookie; `functions/api/verify-turnstile.ts` verifies the token and sets the HMAC-signed cookie (24 h). Feeds, sitemaps, robots.txt, favicons and OG images stay public; `PREVIEW=true` opens preview deployments; a missing secret fails closed. 21 new unit tests in `tests/functions/turnstile.test.ts`. + ## 2026-11-12 16:47 | Check | Status | Details | diff --git a/CLAUDE.md b/CLAUDE.md index f03cecb..fc10142 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -100,7 +100,7 @@ The URL slug is the file name: `src/content/posts/foo.md` → `/posts/foo/`. Fil bun run clean # Start fresh like CI (removes dist/ and public/pagefind/) bun run lint # 1. Linting (0 errors) bun run build # 2. Build (must run before unit tests!) -bun run test:run # 3. Unit tests (50+ tests, requires dist/) +bun run test:run # 3. Unit tests (71+ tests, requires dist/) bun run test:e2e # 4. E2E tests (96+ tests) bun run lighthouse # 5. Lighthouse CI (85%+ performance) ``` @@ -194,6 +194,16 @@ Content collections use the new Content Layer API: - **Output directory:** `dist` - **Node.js version:** read from `.nvmrc`. Cloudflare Pages does not read `mise.toml`, so `.nvmrc` must equal the `node` pin in `mise.toml`; CI fails if they differ - **Bun version:** Cloudflare Pages takes it only from the `BUN_VERSION` environment variable in the Pages project settings; keep it equal to the `bun` pin in `mise.toml` +- **Pages project:** `blog` (subdomain `blog-7qk.pages.dev`). Manage it with the `cloudflare` CLI, and ask the user before every `cloudflare` command + +### Bot Protection (Cloudflare Turnstile) + +The production site is gated at the edge, as in the bio repo: no page is served until Cloudflare Turnstile has been passed. +- `functions/_middleware.ts` checks every request for the `blog_session` cookie. Without it, page loads get a self-contained challenge page (401, `noindex`) and other requests a bare 401. Public without the cookie: `/api/*`, `/rss.xml`, sitemaps, `/robots.txt`, favicons and OG images. +- The challenge page posts the token to `functions/api/verify-turnstile.ts`, which verifies it with Cloudflare siteverify and sets `blog_session` (HMAC-signed with `TURNSTILE_SECRET_KEY`, `HttpOnly; Secure; SameSite=Lax`, 24 h). The page reloads into the requested URL. +- Environment variables (Pages project settings): `TURNSTILE_SITE_KEY` and `TURNSTILE_SECRET_KEY` for Production; `PREVIEW=true` for Preview, which leaves preview deployments open. +- Trade-off the user accepted: search engines and link-preview bots cannot read post pages. +- Local dev, `astro preview`, e2e and Lighthouse run without the gate (Functions only run on Cloudflare). Unit tests: `tests/functions/turnstile.test.ts`. ## Static Assets diff --git a/functions/AGENTS.md b/functions/AGENTS.md new file mode 100644 index 0000000..294afac --- /dev/null +++ b/functions/AGENTS.md @@ -0,0 +1,36 @@ + + + +# functions + +## Purpose + +Cloudflare Pages Functions that gate the whole blog behind Cloudflare Turnstile, ported from the bio repo. Not part of AstroPaper; Pages picks up this directory from the repo root and builds it automatically. Astro, `astro preview`, Playwright and Lighthouse never run these files. + +## Key Files + +| File | Description | +| ------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `_middleware.ts` | Runs on every request. Without a valid `blog_session` cookie, page loads get a self-contained Turnstile page (401, `noindex`) and other requests get a bare 401. Public without a cookie: `/api/*`, `/rss.xml`, both sitemaps, `/robots.txt`, favicons, `/og.png`, `/astropaper-og.jpg`, `/posts//index.png` and the pre-v7 OG PNG. `PREVIEW=true` passes everything. A missing secret fails closed (500). | +| `api/verify-turnstile.ts` | `POST /api/verify-turnstile` with `{ token }`: verifies via Cloudflare siteverify and sets `blog_session=.` (`HttpOnly; Secure; SameSite=Lax`, 24 h), signed with `TURNSTILE_SECRET_KEY`. Exports the cookie helpers the middleware uses. | + +## For AI Agents + +### Working In This Directory + +- Environment variables come from the Cloudflare Pages project `blog` settings, not `.env`: `TURNSTILE_SITE_KEY` (public, injected into the challenge page), `TURNSTILE_SECRET_KEY` (secret: verification and cookie signing), `PREVIEW=true` in the Preview environment only. +- Never commit, log or echo the secret. +- The gate hides post HTML from search engines and link-preview bots (the user chose this, 2026-11-12). Keep feeds, sitemaps, robots.txt and OG images public. +- Use the `cloudflare` CLI for Pages settings, and ask the user before every `cloudflare` command. + +### Testing Requirements + +`../tests/functions/turnstile.test.ts` covers cookie signing, the public-path list and the middleware branches (`bun run test:run`). After deploy, check production: `curl -sI https://blog.kulkarni.cloud/` returns 401 without the cookie, `/rss.xml` returns 200. + +## Dependencies + +### External + +Cloudflare Pages Functions runtime (Web Crypto, `fetch`); Turnstile siteverify `https://challenges.cloudflare.com/turnstile/v0/siteverify`. + + diff --git a/functions/_middleware.ts b/functions/_middleware.ts new file mode 100644 index 0000000..689c38c --- /dev/null +++ b/functions/_middleware.ts @@ -0,0 +1,118 @@ +/** + * Edge gate for the whole site. No page is served without the session cookie set by + * /api/verify-turnstile. Unauthenticated page loads get a standalone Turnstile page; other + * requests get 401. Feeds, sitemaps, robots.txt and OG images stay public so RSS readers and + * crawlers that fetch them directly keep working. Preview deployments (PREVIEW=true) are open. + */ +import { type Env, hasValidSession } from "./api/verify-turnstile"; + +const PUBLIC_PREFIXES = ["/api/"]; +const PUBLIC_PATHS = new Set([ + "/rss.xml", + "/sitemap-index.xml", + "/sitemap-0.xml", + "/robots.txt", + "/favicon.svg", + "/favicon.ico", + "/og.png", + "/astropaper-og.jpg", + "/On the topic of tools, their versions & automated installations.png", +]); +const PUBLIC_PATTERNS = [/^\/posts\/[^/]+\/index\.png$/]; + +export function isPublicPath(pathname: string): boolean { + let path = pathname; + try { + path = decodeURIComponent(pathname); + } catch { + // Malformed escapes are never public. + } + return ( + PUBLIC_PATHS.has(path) || + PUBLIC_PREFIXES.some(p => path.startsWith(p)) || + PUBLIC_PATTERNS.some(re => re.test(path)) + ); +} + +export async function onRequest(context: { + request: Request; + env: Env; + next: () => Promise; +}) { + const { request, env, next } = context; + const { pathname } = new URL(request.url); + + if (env.PREVIEW === "true") return next(); + if (isPublicPath(pathname)) return next(); + if (!env.TURNSTILE_SECRET_KEY) + return new Response("Server configuration error", { status: 500 }); + if (await hasValidSession(request, env.TURNSTILE_SECRET_KEY)) return next(); + + const wantsPage = (request.headers.get("Accept") ?? "").includes("text/html"); + if (!wantsPage) return new Response("Verification required", { status: 401 }); + return new Response(gatePage(env.TURNSTILE_SITE_KEY ?? ""), { + status: 401, + headers: { + "Content-Type": "text/html; charset=utf-8", + "Cache-Control": "no-store", + }, + }); +} + +// Self-contained: system monospace, no site assets, so it needs nothing else to be public. +// On success the verify endpoint sets the cookie and a reload serves the requested URL. +const gatePage = (siteKey: string) => ` + + + + + + Developer Musings + + + + +
+
+

Developer Musings

+

One quick check before the blog loads.

+ ${ + siteKey + ? `
` + : `

Verification is not configured for this deployment.

` + } +

Verification failed. Please try again.

+

Protected by Cloudflare Turnstile

+
+
+ + + +`; diff --git a/functions/api/verify-turnstile.ts b/functions/api/verify-turnstile.ts new file mode 100644 index 0000000..67be56a --- /dev/null +++ b/functions/api/verify-turnstile.ts @@ -0,0 +1,126 @@ +/** + * POST /api/verify-turnstile + * + * Verifies a Turnstile token with Cloudflare and, on success, sets the session cookie that + * functions/_middleware.ts requires before it serves any page. The gate page posts here. + * + * Body: { token: string } + */ + +export interface Env { + TURNSTILE_SECRET_KEY: string; + TURNSTILE_SITE_KEY?: string; + PREVIEW?: string; +} + +export const SESSION_COOKIE = "blog_session"; +const SESSION_TTL_S = 24 * 60 * 60; + +const enc = new TextEncoder(); +const toHex = (buf: ArrayBuffer) => + Array.from(new Uint8Array(buf), b => b.toString(16).padStart(2, "0")).join( + "" + ); + +async function hmac(secret: string, message: string): Promise { + const key = await crypto.subtle.importKey( + "raw", + enc.encode(secret), + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"] + ); + return toHex(await crypto.subtle.sign("HMAC", key, enc.encode(message))); +} + +function timingSafeEqual(a: string, b: string): boolean { + if (a.length !== b.length) return false; + let diff = 0; + for (let i = 0; i < a.length; i++) diff |= a.charCodeAt(i) ^ b.charCodeAt(i); + return diff === 0; +} + +// Stateless session: `${expiry}.${hmac(expiry)}`. The Turnstile secret doubles as the signing key, +// so no extra configuration is needed. +export async function signSession( + secret: string, + now = Date.now() +): Promise { + const exp = String(Math.floor(now / 1000) + SESSION_TTL_S); + return `${exp}.${await hmac(secret, exp)}`; +} + +export async function hasValidSession( + request: Request, + secret: string +): Promise { + const match = (request.headers.get("Cookie") ?? "").match( + new RegExp(`(?:^|;\\s*)${SESSION_COOKIE}=(\\d+)\\.([0-9a-f]+)`) + ); + if (!match) return false; + const [, exp, sig] = match; + if (Number(exp) * 1000 < Date.now()) return false; + return timingSafeEqual(sig, await hmac(secret, exp)); +} + +export function sessionCookie(value: string): string { + return `${SESSION_COOKIE}=${value}; Max-Age=${SESSION_TTL_S}; Path=/; HttpOnly; Secure; SameSite=Lax`; +} + +interface TurnstileResponse { + success: boolean; + "error-codes"?: string[]; +} + +const json = ( + body: unknown, + status: number, + headers: Record = {} +) => + new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json", ...headers }, + }); + +export async function onRequestPost(context: { request: Request; env: Env }) { + try { + const { token } = (await context.request.json()) as { token?: string }; + if (!token) + return json({ success: false, error: "No token provided" }, 400); + + const secretKey = context.env.TURNSTILE_SECRET_KEY; + if (!secretKey) { + console.error("TURNSTILE_SECRET_KEY not set in environment variables"); + return json({ success: false, error: "Server configuration error" }, 500); + } + + const verification = await fetch( + "https://challenges.cloudflare.com/turnstile/v0/siteverify", + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ secret: secretKey, response: token }), + } + ); + const result = (await verification.json()) as TurnstileResponse; + + if (!result.success) { + console.error("Turnstile verification failed:", result["error-codes"]); + return json( + { + success: false, + error: "Verification failed", + details: result["error-codes"], + }, + 400 + ); + } + + return json({ success: true }, 200, { + "Set-Cookie": sessionCookie(await signSession(secretKey)), + }); + } catch (error) { + console.error("Error verifying Turnstile token:", error); + return json({ success: false, error: "Internal server error" }, 500); + } +} diff --git a/tests/AGENTS.md b/tests/AGENTS.md index 8ba8132..771fb28 100644 --- a/tests/AGENTS.md +++ b/tests/AGENTS.md @@ -17,6 +17,7 @@ Unit tests need no network: offline, the Google font provider in `astro.config.t | Directory | Purpose | |-----------|---------| | `utils/` | Tests for `src/utils/` (see `utils/AGENTS.md`) | +| `functions/` | `turnstile.test.ts`: session cookie signing, public-path list and middleware branches of `../functions/` | ## For AI Agents diff --git a/tests/functions/turnstile.test.ts b/tests/functions/turnstile.test.ts new file mode 100644 index 0000000..bb329db --- /dev/null +++ b/tests/functions/turnstile.test.ts @@ -0,0 +1,116 @@ +import { describe, it, expect, vi } from "vitest"; +import { isPublicPath, onRequest } from "../../functions/_middleware"; +import { + SESSION_COOKIE, + hasValidSession, + signSession, +} from "../../functions/api/verify-turnstile"; + +const SECRET = "test-secret"; +const req = (path: string, headers: Record = {}) => + new Request(`https://blog.kulkarni.cloud${path}`, { headers }); +const ok = () => Promise.resolve(new Response("site", { status: 200 })); + +describe("session cookie", () => { + it("accepts a freshly signed session", async () => { + const cookie = `${SESSION_COOKIE}=${await signSession(SECRET)}`; + expect(await hasValidSession(req("/", { Cookie: cookie }), SECRET)).toBe( + true + ); + }); + + it("rejects a session signed with another secret", async () => { + const cookie = `${SESSION_COOKIE}=${await signSession("other")}`; + expect(await hasValidSession(req("/", { Cookie: cookie }), SECRET)).toBe( + false + ); + }); + + it("rejects an expired session", async () => { + const twoDaysAgo = Date.now() - 2 * 24 * 60 * 60 * 1000; + const cookie = `${SESSION_COOKIE}=${await signSession(SECRET, twoDaysAgo)}`; + expect(await hasValidSession(req("/", { Cookie: cookie }), SECRET)).toBe( + false + ); + }); +}); + +describe("isPublicPath", () => { + it.each([ + "/rss.xml", + "/sitemap-index.xml", + "/robots.txt", + "/og.png", + "/posts/gradle-tricks/index.png", + "/api/verify-turnstile", + "/On%20the%20topic%20of%20tools,%20their%20versions%20&%20automated%20installations.png", + ])("%s is public", path => expect(isPublicPath(path)).toBe(true)); + + it.each([ + "/", + "/posts/gradle-tricks/", + "/posts/gradle-tricks/index.html", + "/posts/a/b/index.png", + "/search/", + "/%E0%A4%A", + ])("%s is gated", path => expect(isPublicPath(path)).toBe(false)); +}); + +describe("onRequest", () => { + const env = { TURNSTILE_SECRET_KEY: SECRET, TURNSTILE_SITE_KEY: "site-key" }; + + it("serves the challenge page to a browser without a session", async () => { + const next = vi.fn(ok); + const res = await onRequest({ + request: req("/", { Accept: "text/html" }), + env, + next, + }); + expect(res.status).toBe(401); + expect(await res.text()).toContain('data-sitekey="site-key"'); + expect(next).not.toHaveBeenCalled(); + }); + + it("returns a bare 401 for non-page requests without a session", async () => { + const res = await onRequest({ + request: req("/_astro/x.css"), + env, + next: ok, + }); + expect(res.status).toBe(401); + }); + + it("passes through with a valid session", async () => { + const cookie = `${SESSION_COOKIE}=${await signSession(SECRET)}`; + const res = await onRequest({ + request: req("/", { Cookie: cookie, Accept: "text/html" }), + env, + next: ok, + }); + expect(res.status).toBe(200); + }); + + it("passes public paths and preview deployments through", async () => { + expect( + (await onRequest({ request: req("/rss.xml"), env, next: ok })).status + ).toBe(200); + expect( + ( + await onRequest({ + request: req("/"), + env: { ...env, PREVIEW: "true" }, + next: ok, + }) + ).status + ).toBe(200); + }); + + it("fails closed when the secret is missing", async () => { + const res = await onRequest({ + request: req("/"), + env: { TURNSTILE_SECRET_KEY: "" }, + next: ok, + }); + expect(res.status).toBe(500); + }); +});