Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

# Except these files & folders
!/src
!/functions
!/public/**/*.ts
!/public/**/*.js
!/.github
Expand Down
2 changes: 2 additions & 0 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`) |
Expand Down Expand Up @@ -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 |
Expand Down
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -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 |
Expand Down
12 changes: 11 additions & 1 deletion CLAUDE.md
Original file line number Diff line number Diff line change
Expand Up @@ -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)
```
Expand Down Expand Up @@ -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

Expand Down
36 changes: 36 additions & 0 deletions functions/AGENTS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
<!-- Parent: ../AGENTS.md -->
<!-- Generated: 2026-11-12 | Updated: 2026-11-12 -->

# 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/<slug>/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=<expiry>.<HMAC-SHA256>` (`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`.

<!-- MANUAL: Any manually added notes below this line are preserved on regeneration -->
118 changes: 118 additions & 0 deletions functions/_middleware.ts
Original file line number Diff line number Diff line change
@@ -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<Response>;
}) {
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) => `<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="robots" content="noindex">
<title>Developer Musings</title>
<style>
:root { color-scheme: light dark; --bg: #fdfdfd; --text: #282728; --dim: #6b7280; --accent: #006cac; --border: #ece9e9; }
@media (prefers-color-scheme: dark) { :root { --bg: #212737; --text: #eaedf3; --dim: #afb9ca; --accent: #ff6b01; --border: #ab4b08; } }
html, body { height: 100%; margin: 0; background: var(--bg); color: var(--text);
font: 14px/1.6 ui-monospace, Menlo, Consolas, monospace; }
main { min-height: 100%; display: grid; place-items: center; padding: 24px; box-sizing: border-box; }
.frame { border: 1px solid var(--border); padding: 24px 28px; max-width: 420px; width: 100%; }
.dim { color: var(--dim); }
h1 { font-size: 18px; margin: 0 0 4px; }
p { margin: 0 0 16px; }
.cf-turnstile { min-height: 65px; }
.error { color: #e64553; margin-top: 12px; display: none; }
</style>
<script src="https://challenges.cloudflare.com/turnstile/v0/api.js" async defer></script>
</head>
<body>
<main>
<div class="frame">
<h1>Developer Musings</h1>
<p class="dim">One quick check before the blog loads.</p>
${
siteKey
? `<div class="cf-turnstile" data-sitekey="${siteKey}" data-callback="onVerify" data-theme="auto"></div>`
: `<p class="error" style="display:block">Verification is not configured for this deployment.</p>`
}
<p class="error" id="error">Verification failed. Please try again.</p>
<p class="dim" style="margin:16px 0 0;font-size:12px">Protected by Cloudflare Turnstile</p>
</div>
</main>
<script>
async function onVerify(token) {
try {
const res = await fetch('/api/verify-turnstile', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
credentials: 'same-origin',
body: JSON.stringify({ token }),
});
const body = await res.json().catch(() => ({}));
if (res.ok && body.success) { location.reload(); return; }
} catch (_) {}
document.getElementById('error').style.display = 'block';
if (window.turnstile) window.turnstile.reset();
}
</script>
</body>
</html>
`;
126 changes: 126 additions & 0 deletions functions/api/verify-turnstile.ts
Original file line number Diff line number Diff line change
@@ -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<string> {
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<string> {
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<boolean> {
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<string, string> = {}
) =>
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);
}
}
1 change: 1 addition & 0 deletions tests/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
Loading
Loading