All files / src middleware.ts

97.84% Statements 136/139
94.32% Branches 133/141
90.9% Functions 10/11
97.77% Lines 132/135

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578                          1x           1x                             13x           1x 1x 1x 1x 1x         84x 82x 81x 75x         6x 69x                   4x 4x                 81x                 1x 95x               95x                                     95x 12x     12x 12x 11x 11x 11x       11x   6x 6x   1x   5x       6x 2x   3x 3x 2x                 1x       5x     11x 11x 4x               1x                       84x 95x 95x   95x 7x 7x       6x 5x     5x 2x                 3x             77x     84x               84x 84x       95x 13x                             13x     13x 13x               2x         2x         2x 2x 1x         2x 2x                             82x 82x   3x             3x 3x                                     79x 3x         79x 79x 1x             79x 79x 79x 79x                 79x                             79x                                                       79x     79x           79x                         12x 8x         4x   67x                   64x   64x       64x       58x 168x   58x 58x                           58x     58x     58x 58x 58x                         79x 95x 7x     79x           79x   79x       95x                 8x     8x         4x 4x 4x 4x 4x       4x 3x                                   79x 64x           79x                 1x 95x 95x 95x 95x 94x   1x                       1x      
import { defineMiddleware } from "astro:middleware";
import { env } from "cloudflare:workers";
import * as Sentry from "@sentry/cloudflare";
import type { APIContext, MiddlewareNext } from "astro";
import { setEnvRobotTag } from "./lib/cache-headers";
import { buildCacheKeyUrl } from "./lib/cache-key";
import { DEFAULT_LOCAL_API_URL } from "./lib/constants";
import { CSP_ALLOWLIST } from "./lib/csp-allowlist";
import { isSyntheticAuditor } from "./lib/gtm-load";
 
// Trace sampling per environment — mirrors the API worker so prod stays cheap
// while dev/preview capture everything. Errors are always captured regardless.
function sentryTracesSampleRate(environment: string): number {
	switch (environment) {
		case "production":
			return 0.1;
		case "preview":
			return 0.5;
		default:
			return 1.0;
	}
}
 
// Deploy-version marker for the edge cache key, so HTML cached by a prior
// deploy is never served by the next one. It is the Worker version ID from the
// `version_metadata` binding (wrangler.jsonc, declared per env: bindings are not
// inherited), which every `wrangler deploy` changes, from CI or by hand.
//
// It used to be `Date.now().toString(36)` at module scope. A deployed Worker's
// clock does not run during module evaluation (global scope, which this lazily
// imported module's top level still counts as), so the marker came out the same
// on every deploy and dev kept serving HTML stored before five redeploys
// (#1125). "local" covers dev servers and tests that run without the binding.
function deployVersion(): string {
	return env.CF_VERSION_METADATA?.id || "local";
}
 
// Pre-joined CSP allowlist tokens. CSP_ALLOWLIST is static config, so the
// space-separated form is computed once at module load instead of on every
// request inside `onRequest`.
const CSP_SCRIPT_SRC = CSP_ALLOWLIST.scriptSrc.join(" ");
const CSP_IMG_SRC = CSP_ALLOWLIST.imgSrc.join(" ");
const CSP_CONNECT_SRC = CSP_ALLOWLIST.connectSrc.join(" ");
const CSP_FRAME_SRC = CSP_ALLOWLIST.frameSrc.join(" ");
const CSP_FORM_ACTION = CSP_ALLOWLIST.formAction.join(" ");
 
// Determine if this request should use the Cloudflare edge cache.
// Only GET requests for HTML pages — not API routes, not static assets.
function isCacheableRequest(method: string, pathname: string): boolean {
	if (method !== "GET") return false;
	if (pathname.startsWith("/api/")) return false;
	if (pathname.startsWith("/_astro/")) return false;
	if (
		/\.(js|css|woff2?|ttf|otf|eot|svg|png|jpg|jpeg|gif|webp|ico|xml|txt|json)$/.test(
			pathname,
		)
	)
		return false;
	return true;
}
 
// Extract a numeric directive (e.g. `s-maxage=600`) from a Cache-Control value.
// Anchored on a directive boundary (start, comma, or whitespace) so a short
// name can't match inside a longer one (e.g. "age" inside "s-maxage").
function cacheControlSeconds(
	cacheControl: string,
	directive: "s-maxage" | "stale-while-revalidate" | "max-age",
): number | undefined {
	const m = cacheControl.match(new RegExp(`(?:^|[,\\s])${directive}=(\\d+)`));
	return m ? Number.parseInt(m[1], 10) : undefined;
}
 
// Non-production X-Robots-Tag. Layout frontmatter can set Astro.response
// headers, but those headers do not survive onto the Response middleware
// returns, so the tag has to be applied here — including on an edge-cache
// HIT, whose stored headers were frozen by whoever filled the cache.
// Lighthouse / HeadlessChrome still bypass, matching setEnvRobotTag.
function applyEnvRobotTag(headers: Headers, request: Request, url: URL): void {
	setEnvRobotTag(
		{ response: { headers } },
		env.ENVIRONMENT,
		request.headers.get("user-agent"),
		request.headers.get("x-lighthouse-audit"),
		url.searchParams.has("_lh"),
	);
}
 
const handleRequest = async (context: APIContext, next: MiddlewareNext) => {
	const url = new URL(context.request.url);
 
	// Purge legacy template-leak URLs. A prior bug let the SearchAction target
	// template `{search_term_string}` reach live URLs (e.g.
	// `/pros?search={search_term_string}`), which Googlebot crawled and indexed.
	// These are never valid. Return 410 Gone (not 404) so Google drops them fast.
	// Matches both the raw token and its percent-encoded form (`%7B…%7D`); we key
	// off the token, not bare braces, so a genuine `?q={foo}` search still works.
	Iif (/%7bsearch_term_string%7d|\{search_term_string\}/i.test(url.search)) {
		return new Response("Gone", {
			status: 410,
			headers: { "Cache-Control": "no-store" },
		});
	}
 
	// Local dev: proxy /cdn-cgi/image/* requests to the actual image URL.
	// Cloudflare Image Resizing only works on their edge, not in wrangler dev.
	// Format: /cdn-cgi/image/params.../https://host/api/images/path
	//     or: /cdn-cgi/image/params.../path (relative)
	//
	// Target URL MUST be validated against env.IMAGE_URL + env.API_URL — the
	// path is attacker-controlled (from page src), so without allowlisting a
	// request to /cdn-cgi/image/w=1/http://169.254.169.254/ would exfiltrate
	// cloud metadata, and /cdn-cgi/image/w=1/http://localhost:7001/api/admin/
	// would proxy internal endpoints. In production CF handles /cdn-cgi/*
	// before the Worker so this code is dev-only, but a misconfigured
	// wrangler route would make it exploitable in prod.
	if (url.pathname.startsWith("/cdn-cgi/image/")) {
		const rest = url.pathname.slice("/cdn-cgi/image/".length);
		// Strip the resize params (everything before the first "/" after params)
		// Params look like: onerror=redirect,width=800,height=500,format=webp/...
		const slashAfterParams = rest.indexOf("/");
		if (slashAfterParams !== -1) {
			const imageTarget = rest.slice(slashAfterParams + 1);
			const allowedImageOrigin = env.IMAGE_URL || "";
			const allowedApiUrl = env.API_URL || DEFAULT_LOCAL_API_URL;
 
			// If it starts with http, it's an absolute URL — fetch only if it
			// matches the configured image host or API host.
			if (imageTarget.startsWith("http")) {
				let targetOrigin: string;
				try {
					targetOrigin = new URL(imageTarget).origin;
				} catch {
					return new Response(null, { status: 400 });
				}
				const allowedOrigins = [
					allowedImageOrigin && new URL(allowedImageOrigin).origin,
					new URL(allowedApiUrl).origin,
				].filter(Boolean) as string[];
				if (!allowedOrigins.includes(targetOrigin)) {
					return new Response(null, { status: 403 });
				}
				try {
					const imgRes = await fetch(imageTarget);
					return new Response(imgRes.body, {
						status: imgRes.status,
						headers: {
							"Content-Type":
								imgRes.headers.get("Content-Type") || "image/jpeg",
							"Cache-Control": "public, max-age=3600",
						},
					});
				} catch {
					return new Response(null, { status: 404 });
				}
			}
			// Relative path — proxy through the local API
			const imgPath = imageTarget.startsWith("/api/images/")
				? imageTarget
				: `/api/images/${imageTarget}`;
			try {
				const imgRes = await fetch(`${allowedApiUrl}${imgPath}`);
				return new Response(imgRes.body, {
					status: imgRes.status,
					headers: {
						"Content-Type": imgRes.headers.get("Content-Type") || "image/jpeg",
						"Cache-Control": "public, max-age=3600",
					},
				});
			} catch {
				return new Response(null, { status: 404 });
			}
		}
	}
 
	// --- SSR session probe ---
	// The marketplace is SSR on every navigation (not SPA). Without this, every
	// hydration island has to fetch /api/homeowner/auth/get-session after hydrate
	// before it can render the logged-in state, causing a visible "logged-out
	// flash" for 0.8-1.7s. We forward the session cookie server-side so the
	// Astro layout can pass `initialUser` to islands and they render correctly
	// on first paint.
	const cookieHeader = context.request.headers.get("cookie") || "";
	const hasSessionCookie = /ho\.session_token=/.test(cookieHeader);
	const apiUrlForSession = env.API_URL || DEFAULT_LOCAL_API_URL;
 
	if (hasSessionCookie) {
		try {
			const sessionRes = await fetch(
				`${apiUrlForSession}/api/homeowner/auth/get-session`,
				{ headers: { cookie: cookieHeader } },
			);
			if (sessionRes.ok) {
				const data = (await sessionRes.json()) as {
					user?: HomeownerLocalUser & { emailVerified?: boolean };
				} | null;
				if (data?.user) {
					context.locals.homeownerUser = {
						id: data.user.id,
						name: data.user.name,
						email: data.user.email,
						image: data.user.image ?? null,
						emailVerified: data.user.emailVerified ?? false,
						phoneNumber: data.user.phoneNumber ?? null,
					};
				} else {
					context.locals.homeownerUser = null;
				}
			}
		} catch {
			// Non-fatal: fall back to client-side probe.
		}
	} else {
		context.locals.homeownerUser = null;
	}
 
	const cacheable = isCacheableRequest(context.request.method, url.pathname);
 
	// --- Edge Cache: check for cached HTML response ---
	// Cloudflare Workers don't use the CDN cache layer automatically.
	// We explicitly use the Cache API to cache SSR responses at the edge PoP.
	// Skip entirely when a session cookie is present — otherwise one user's
	// personalized HTML (e.g. UserMenu with their name) could be served to
	// another user or to anonymous traffic.
	const hasCache = typeof caches !== "undefined";
	const edgeCacheable = cacheable && !hasSessionCookie;
	let cache: Cache | undefined;
	let cacheKey: Request | undefined;
 
	if (edgeCacheable && hasCache) {
		cache = (caches as unknown as { default: Cache }).default;
		// buildCacheKeyUrl strips tracking/click-ID params (utm_*, fbclid, brid, …)
		// and sorts the rest, so paid-ad clicks — each carrying a unique fbclid +
		// utm_* — collapse onto ONE entry instead of each becoming a live SSR→API
		// miss (prod 503 storm 2026-06-20). It also appends deployVersion() so each
		// deploy starts with a clean edge cache namespace; old entries for the prior
		// version naturally expire via s-maxage and never get served.
		//
		// Construct the cache key with ONLY method + normalized URL. Forwarding
		// `context.request.headers` verbatim fragmented the cache by
		// Accept-Encoding / Accept / User-Agent, driving the hit rate toward
		// zero for anonymous traffic (each browser-family + locale combination
		// got its own cache entry). It also included the Cookie header in the
		// key — Cloudflare strips it in practice, but relying on undocumented
		// behavior is fragile, and tests under miniflare would not strip.
		cacheKey = new Request(buildCacheKeyUrl(url.toString(), deployVersion()), {
			method: "GET",
		});
		const cached = await cache.match(cacheKey);
		if (cached) {
			// Responses returned from the Web Cache API have IMMUTABLE headers.
			// If we return this object directly, anything downstream that tries
			// to add/modify headers (Astro's RenderContext, the Cloudflare
			// adapter, CSP middleware, etc.) throws:
			//   TypeError: Can't modify immutable headers.
			// Wrap the body in a fresh Response with a mutable Headers copy so
			// downstream code can modify headers normally.
			const hitHeaders = new Headers(cached.headers);
			// Observability: an unambiguous marker that this Worker served the
			// copy from caches.default. The CF-Cache-Status: HIT and Age that a
			// match also carries come from the Cache API, not from a CDN tier in
			// front of the Worker (a custom-domain Worker has none) (#1125).
			hitHeaders.set("X-Edge-Cache", "HIT");
			// Every entry was stored with max-age=0 (see the caching branch
			// below), but a match hands it back with the zone's Browser Cache TTL
			// instead (dev: max-age=14400), letting a browser hold this HTML for
			// 4 h across a deploy. Put the 0 back.
			const hitCacheControl = hitHeaders.get("Cache-Control");
			if (hitCacheControl) {
				hitHeaders.set(
					"Cache-Control",
					hitCacheControl.replace(/(^|[,\s])max-age=\d+/, "$1max-age=0"),
				);
			}
			applyEnvRobotTag(hitHeaders, context.request, url);
			return new Response(cached.body, {
				status: cached.status,
				statusText: cached.statusText,
				headers: hitHeaders,
			});
		}
	}
 
	// SSR error boundary. An unhandled throw in a page's frontmatter (e.g. a
	// dereference of API data that violated its type contract) otherwise
	// bubbles to the Cloudflare adapter, which returns a bare `text/plain` 503
	// with no body we control and no log we retain — invisible to debugging.
	// Catch it here so the stack is logged (visible in `wrangler tail` /
	// Logpush) and the visitor gets a real, non-cached 500 page instead.
	let response: Response;
	try {
		response = await next();
	} catch (err) {
		console.error(
			"SSR render error:",
			url.pathname,
			err instanceof Error ? (err.stack ?? err.message) : err,
		);
		// Report to Sentry. No-op unless this request is running inside
		// wrapRequestHandler (i.e. a DSN is configured and we're not local).
		Sentry.captureException(err);
		return new Response(
			'<!doctype html><meta charset=utf-8><title>Something went wrong</title><body style="font-family:system-ui;max-width:32rem;margin:4rem auto;padding:0 1rem;text-align:center"><h1>Something went wrong</h1><p>We hit an unexpected error loading this page. Please try again.</p><p><a href="/">Back to home</a></p>',
			{
				status: 500,
				headers: {
					"Content-Type": "text/html; charset=utf-8",
					"Cache-Control": "no-store",
				},
			},
		);
	}
 
	// A render for a Lighthouse / headless audit leaves GTM out
	// (GoogleTagManager.astro). The edge cache is keyed on the URL alone, so a
	// stored copy would then be served to every real visitor for up to a day:
	// no GA4 page view, and whatsapp_click pushed to a dataLayer nothing reads.
	// On dev, /how-it-works was served without GTM 3 times out of 3 (#1086 QA).
	// Opting out here makes the caching branch below keep it, and skips the
	// edge write, for both the Worker cache and Cloudflare's CDN.
	if (isSyntheticAuditor(context.request.headers.get("user-agent"), url)) {
		response.headers.set("Cache-Control", "private, no-store");
	}
 
	// Early Hints: Cloudflare converts Link headers to 103 Early Hints automatically
	// This tells the browser to preconnect to the image domain before the HTML arrives
	const imageUrl = env.IMAGE_URL;
	if (imageUrl) {
		response.headers.append(
			"Link",
			`<${imageUrl}>; rel=preconnect; crossorigin`,
		);
	}
 
	// Add security headers
	response.headers.set("X-Content-Type-Options", "nosniff");
	response.headers.set("X-Frame-Options", "SAMEORIGIN");
	response.headers.set("X-XSS-Protection", "1; mode=block");
	response.headers.set("Referrer-Policy", "strict-origin-when-cross-origin");
 
	// CSP allows connections to all decorrocket.com subdomains (api, api-preview, etc.),
	// the runtime-configured API origin (env.API_URL — required for Conductor workspaces
	// where the API runs on a non-default port like 7021/8021), and the canonical
	// localhost fallback. The wildcard subdomains cover prod/preview; env.API_URL
	// covers any runtime port; the literal fallbacks cover edge cases where env is
	// not yet bound (e.g. early-error responses). See:
	// https://github.com/withastro/astro/issues/11555
	const allowedOrigins = [
		"https://*.decorrocket.com", // All production/preview subdomains
		"https://*.interioring.com", // All production subdomains (new brand)
		env.API_URL, // Runtime API origin (Conductor port slot, e.g. http://localhost:7021)
		DEFAULT_LOCAL_API_URL, // Canonical localhost fallback (legacy port 7001)
		"http://localhost:8887", // Worktree API development
	]
		.filter(Boolean)
		.join(" ");
 
	// Content Security Policy for marketplace pages
	// More permissive than API since we need to load styles, scripts, and images.
	// Third-party vendor origins (GTM, GA4, Ads, etc.) live in CSP_ALLOWLIST
	// (./lib/csp-allowlist.ts) — append new vendor URLs there, not here. The
	// joined forms (`CSP_SCRIPT_SRC` etc.) are pre-computed at module load.
	const csp = [
		"default-src 'self'",
		// Allow inline styles for Tailwind/Astro
		"style-src 'self' 'unsafe-inline'",
		// Allow inline scripts for Astro hydration + Cloudflare Web Analytics (auto-injected via observability)
		`script-src 'self' 'unsafe-inline' https://static.cloudflareinsights.com ${CSP_SCRIPT_SRC}`,
		// Allow images from self, API (for R2 images), and data URIs
		`img-src 'self' data: blob: https: ${allowedOrigins} ${CSP_IMG_SRC}`,
		// Allow fonts from self (self-hosted via fontsource)
		"font-src 'self'",
		// Allow connections to API, WhatsApp, Cloudflare Analytics beacon, and third-party analytics
		`connect-src 'self' https://wa.me https://cloudflareinsights.com https://*.ingest.us.sentry.io ${allowedOrigins} ${CSP_CONNECT_SRC}`,
		// Our own forms, plus the vendors that submit a form to transmit an
		// event (the Meta Pixel does this when it cannot use a beacon)
		`form-action 'self' ${CSP_FORM_ACTION}`,
		// Allow framing only by self
		"frame-ancestors 'self'",
		// Allow YouTube embeds + third-party tag manager iframes
		`frame-src 'self' https://www.youtube-nocookie.com https://www.youtube.com ${CSP_FRAME_SRC}`,
		// Contentsquare session replay serializes the DOM in a blob: web worker;
		// without these it falls back to default-src 'self' and is blocked
		"worker-src 'self' blob:",
		"child-src 'self' blob:",
		// Block object embeds
		"object-src 'none'",
		// Base URI restriction
		"base-uri 'self'",
	].join("; ");
	response.headers.set("Content-Security-Policy", csp);
 
	// Permissions Policy (formerly Feature Policy)
	response.headers.set(
		"Permissions-Policy",
		"camera=(), microphone=(), geolocation=()",
	);
 
	// Add caching headers
	if (
		url.pathname.startsWith("/_astro/") ||
		url.pathname.match(
			/\.(js|css|woff2?|ttf|otf|eot|svg|png|jpg|jpeg|gif|webp|ico)$/,
		)
	) {
		// Static assets with fingerprinted filenames — cache forever when the
		// asset actually exists. For 4xx/5xx (typically a stale HTML reference
		// to an old hash from a prior deploy, e.g. `/_astro/client.OLD.js`),
		// use short no-store caching so the browser re-fetches the HTML on
		// next nav and picks up the current asset hashes. Without this guard,
		// a 1-year immutable cache pins the 404 in the browser and the user
		// sees a broken site until they hard-refresh.
		if (response.status >= 200 && response.status < 400) {
			response.headers.set(
				"Cache-Control",
				"public, max-age=31536000, immutable",
			);
		} else {
			response.headers.set("Cache-Control", "no-store, max-age=0");
		}
	} else if (
		context.request.method === "GET" &&
		!url.pathname.startsWith("/api/")
	) {
		// Respect an explicit cache opt-out the page already set (e.g. the
		// homepage when it rendered an empty state, or a personalized/dynamic
		// page) — never promote it to a public, edge-cacheable header. Without
		// this guard the default branch below would overwrite a no-store /
		// no-cache / private directive and the edge could pin an empty render
		// or, worse, a private response.
		const pageCacheControl = response.headers.get("Cache-Control");
		const pageOptedOut =
			pageCacheControl != null &&
			(pageCacheControl.includes("no-store") ||
				pageCacheControl.includes("no-cache") ||
				pageCacheControl.includes("private"));
		if (!pageOptedOut) {
			// Per-path edge-TTL floor: listings revalidate faster (new pros/
			// projects appear) than detail/static pages. These are the minimum
			// edge lifetimes; a page may raise them (see below).
			const isListing = ["/pros", "/projects", "/rooms"].some(
				(p) => url.pathname === p || url.pathname === `${p}/`,
			);
			const floorSMaxage = isListing ? 1800 : 900;
			const floorSwr = isListing ? 3600 : 1800;
			// A page can declare a LONGER edge TTL via setCacheHeaders (e.g.
			// `static`/`blog-post`/`faq-hub` = 1 day, `city-hub`/`calculator` =
			// 1 hour). Previously this branch unconditionally overwrote those
			// presets, capping every page at the floor and discarding the
			// page's intent — rarely-changing pages got the same 15-min edge
			// life as the homepage. Honor whichever is larger so static content
			// gets a high edge hit rate; never drop below the per-path floor.
			//
			// `max-age` is always 0: a browser must never hold HTML that
			// references fingerprinted `/_astro/*` assets from a prior deploy
			// (broken hydration until the browser cache expires). The shared
			// edge copy is deploy-safe because the cache key is namespaced by
			// deployVersion().
			const pageSMaxage = pageCacheControl
				? cacheControlSeconds(pageCacheControl, "s-maxage")
				: undefined;
			const pageSwr = pageCacheControl
				? cacheControlSeconds(pageCacheControl, "stale-while-revalidate")
				: undefined;
			const sMaxage = Math.max(floorSMaxage, pageSMaxage ?? 0);
			const swr = Math.max(floorSwr, pageSwr ?? 0);
			response.headers.set(
				"Cache-Control",
				`public, max-age=0, s-maxage=${sMaxage}, stale-while-revalidate=${swr}`,
			);
		}
	}
 
	// Prevent downstream/CDN caching of personalized pages. /account/* is
	// always opted out — even without a session cookie — so the bfcache
	// can't restore a stale signed-in render after sign-out (issue #462).
	// The cookie-based branch still covers other personalized surfaces
	// (e.g. /projects with the user's avatar in UserMenu).
	const isAccountPath =
		url.pathname === "/account" || url.pathname.startsWith("/account/");
	if (hasSessionCookie || isAccountPath) {
		response.headers.set("Cache-Control", "private, no-store");
	}
 
	applyEnvRobotTag(response.headers, context.request, url);
 
	// --- Edge Cache: store successful HTML responses ---
	// Skip the write when the final Cache-Control opts out of shared caching —
	// no-store (empty homepage render), no-cache, or private (personalized
	// pages) — so the edge never pins a render that explicitly opted out.
	const responseCacheControl = response.headers.get("Cache-Control");
	const responseOptedOut =
		responseCacheControl != null &&
		(responseCacheControl.includes("no-store") ||
			responseCacheControl.includes("no-cache") ||
			responseCacheControl.includes("private"));
	if (
		edgeCacheable &&
		cache &&
		cacheKey &&
		response.status === 200 &&
		!responseOptedOut
	) {
		// Astro 6 + @astrojs/cloudflare 13 expose the ExecutionContext
		// as `Astro.locals.cfContext` (replacing the old runtime.ctx).
		const waitUntil = context.locals?.cfContext?.waitUntil?.bind(
			context.locals.cfContext,
		);
		if (waitUntil) {
			// Store only a complete render. A visitor who navigates away mid-stream
			// cancels the SSR stream, and the clone then ends early; caching that
			// would serve a truncated page (no menu, no closing scripts) to every
			// visitor at the PoP for s-maxage. HTML must end in </html>.
			const edgeCache = cache;
			const key = cacheKey;
			const copy = response.clone();
			const isHtml = (copy.headers.get("Content-Type") ?? "").includes("text/html");
			waitUntil(
				copy
					.text()
					.then((body) => {
						if (isHtml && !/<\/html>\s*$/i.test(body)) return;
						return edgeCache.put(
							key,
							new Response(body, {
								status: copy.status,
								statusText: copy.statusText,
								headers: copy.headers,
							}),
						);
					})
					.catch(() => {}),
			);
		}
	}
 
	// Observability for the Worker edge cache (a HIT returns earlier with
	// X-Edge-Cache: HIT). MISS = freshly rendered and eligible to populate the
	// cache; BYPASS = not edge-cached this request (session cookie present, or
	// the page opted out via no-store/no-cache/private).
	if (cacheable) {
		response.headers.set(
			"X-Edge-Cache",
			edgeCacheable && !responseOptedOut ? "MISS" : "BYPASS",
		);
	}
 
	return response;
};
 
// Wrap the request in Sentry on Cloudflare Workers so unhandled SSR exceptions
// (and traces) are captured per-request and flushed via the Worker execution
// context. wrapRequestHandler needs that context to flush, so when it's absent
// — or no DSN is set, or we're local — run the handler unwrapped (Sentry then
// no-ops). DSN comes from the per-env `SENTRY_DSN` binding so each app reports
// to its own project.
export const onRequest = defineMiddleware((context, next) => {
	const dsn = env.SENTRY_DSN;
	const environment = env.ENVIRONMENT || "local";
	const cfContext = context.locals?.cfContext;
	if (!dsn || environment === "local" || !cfContext) {
		return handleRequest(context, next);
	}
	return Sentry.wrapRequestHandler(
		{
			options: {
				dsn,
				environment,
				tracesSampleRate: sentryTracesSampleRate(environment),
			},
			request: context.request,
			context: cfContext as unknown as Parameters<
				typeof Sentry.wrapRequestHandler
			>[0]["context"],
		},
		() => handleRequest(context, next),
	);
});