From fdddc957c8c6c0e8dd521815a9a6566ba27dcbad Mon Sep 17 00:00:00 2001 From: Adam <2363879+adamdotdevin@users.noreply.github.com> Date: Thu, 5 Nov 2026 21:55:39 -0600 Subject: [PATCH] fix(site): security headers, Workers Logs and launch fixes (#62222) --- services/site/AGENTS.md | 2 +- services/site/cloudflare.config.ts | 2 ++ services/site/public/_headers | 2 +- services/site/src/lib/changelog-notes.ts | 15 ++++++++- services/site/src/lib/changelog.ts | 17 ++++++---- services/site/src/lib/docs.ts | 3 +- services/site/src/lib/html-cache.ts | 10 ++++-- services/site/src/lib/security-headers.ts | 17 ++++++++++ services/site/src/middleware.ts | 14 ++++---- services/site/src/routes/changelog/[tag].tsx | 5 ++- services/site/test/changelog-status.test.ts | 30 +++++++++++++++++ services/site/test/security-headers.test.ts | 35 ++++++++++++++++++++ 12 files changed, 129 insertions(+), 23 deletions(-) create mode 100644 services/site/src/lib/security-headers.ts create mode 100644 services/site/test/changelog-status.test.ts create mode 100644 services/site/test/security-headers.test.ts diff --git a/services/site/AGENTS.md b/services/site/AGENTS.md index 5f190158aae..167bbfd7d03 100644 --- a/services/site/AGENTS.md +++ b/services/site/AGENTS.md @@ -5,7 +5,7 @@ Read the design-system rules in `DESIGN.md` (also shown at `/dev/components#rule ## Public pages - When you add, remove or rename a public page, keep `/sitemap.xml`, `llms.txt`, search and the page's `.md` version in sync; run the sitemap test (`bun test test/sitemap.test.ts` from this directory). -- `/sitemap.xml` is the only sitemap in `robots.txt`. It is an index of `sitemapFiles` in `src/lib/sitemap.ts`: this app's `/sitemap-pages.xml`, the docs sitemap `/docs/sitemap.xml`, and the Data and Console sitemaps. +- `/sitemap.xml` is the only sitemap in `robots.txt`. It is an index of `sitemapFiles` in `src/lib/sitemap.ts`: this app's `/sitemap-pages.xml`, the V2 docs sitemap `/v2/sitemap.xml`, and the Data and Console sitemaps. - `/sitemap-pages.xml` (`src/routes/sitemap-pages.xml.ts`) lists every page route automatically. To leave a page out, add it to `sitemapExclusions` in `src/lib/sitemap.ts` with a reason. A route with parameters needs an entry in `dynamicRoutes` there, or an exclusion. - Do not add a static `public/sitemap.xml`, because it would hide the generated one. - The view-source comment's FOR HUMANS rows start with the main nav in the same order; they're generated from the nav data, so update the nav, not the comment. diff --git a/services/site/cloudflare.config.ts b/services/site/cloudflare.config.ts index 7ba8662c41f..5cbf1fe854c 100644 --- a/services/site/cloudflare.config.ts +++ b/services/site/cloudflare.config.ts @@ -34,6 +34,8 @@ export default defineConfig(({ mode }) => { : [], workersDev: false, previewUrls: false, + // Workers Logs: requests, errors and console output, searchable in the Cloudflare dashboard. + observability: { enabled: true }, }, } }) diff --git a/services/site/public/_headers b/services/site/public/_headers index 2f6402e0703..99ad35f8af4 100644 --- a/services/site/public/_headers +++ b/services/site/public/_headers @@ -1,4 +1,4 @@ -# Cache headers for the static files in public/ (Cloudflare Workers static assets; SST uploads +# Cache headers for the static files in public/ (Cloudflare Workers static assets; script/build.ts ships # .output/public/_headers with the assets). Nitro appends its own /_build/assets/* rule (hashed # build files, immutable). Rules must not overlap: Cloudflare joins repeated headers with a comma. # diff --git a/services/site/src/lib/changelog-notes.ts b/services/site/src/lib/changelog-notes.ts index d3d0e45910e..0015be2f6fe 100644 --- a/services/site/src/lib/changelog-notes.ts +++ b/services/site/src/lib/changelog-notes.ts @@ -58,6 +58,8 @@ export type ChangelogView = { /** For one entry: the newer and older entries next to it. */ newer?: { tag: string; title: string } older?: { tag: string; title: string } + /** The releases are a stand-in (the build snapshot or the last good list) because GitHub failed just now. */ + stale?: boolean } /** Entries per changelog page. */ @@ -303,7 +305,7 @@ export function changelogView( } /** The entry that includes the release `tag` (merged entries answer to each of their tags), with its neighbours. */ -export function changelogEntryView(releases: ChangelogRelease[], tag: string): ChangelogView { +export function changelogEntryView(releases: ChangelogRelease[], tag: string, stale?: boolean): ChangelogView { const entries = changelogTimeline(releases) const index = entries.findIndex((item) => item.releases.some((release) => release.tag === tag)) const link = (item?: ChangelogEntry) => item && { tag: item.releases[0].tag, title: item.title } @@ -317,9 +319,20 @@ export function changelogEntryView(releases: ChangelogRelease[], tag: string): C filter: [], newer: index > 0 ? link(entries[index - 1]) : undefined, older: index >= 0 ? link(entries[index + 1]) : undefined, + stale, } } +/** + * The HTTP status of one release's page and JSON. A tag missing from GitHub's own list is a 404; one + * missing from a stand-in list, or with no list at all, is a 503, because it may be a release the + * stand-in doesn't have. + */ +export function entryStatus(view: ChangelogView) { + if (view.entries.length) return 200 + return view.ok && !view.stale ? 404 : 503 +} + /** The `?page=…&area=…` query for a changelog view, without the defaults. */ export function changelogQuery(options: { page?: number; filter?: string[] }) { const params = [ diff --git a/services/site/src/lib/changelog.ts b/services/site/src/lib/changelog.ts index 372288ecc8b..abbb2eb6a40 100644 --- a/services/site/src/lib/changelog.ts +++ b/services/site/src/lib/changelog.ts @@ -5,6 +5,7 @@ import { staleValue } from "~/lib/edge-cache" import { changelogEntryView, changelogView, + entryStatus, parseReleaseNotes, type ChangelogView, type ReleaseNotes, @@ -165,7 +166,7 @@ export const changelogPage = query(async (page: number, filter: string[]): Promi export const changelogEntry = query(async (tag: string): Promise => { "use server" const result = await loadChangelog() - return changelogEntryView(result.releases, tag) + return changelogEntryView(result.releases, tag, result.stale) }, "changelog-entry") /** The newest few entries with notes in one product's areas, for its product page. */ @@ -181,10 +182,9 @@ export const productChangelog = query(async (filter: string[]): Promise ({ ok: false, releases: [] })) - const view = changelogEntryView(result.releases, tag) + const view = changelogEntryView(result.releases, tag, result.stale) const entry = view.entries[0] - // A tag missing from a stale list may just be newer than it: a 404 then, cached for a minute only. - const status = entry ? 200 : result.ok ? 404 : 503 + const status = entryStatus(view) return new Response( JSON.stringify( entry @@ -196,9 +196,12 @@ export async function changelogEntryJson(tag: string) { headers: { "Content-Type": "application/json", "Cache-Control": - entry && !result.stale - ? "public, max-age=60, s-maxage=300, stale-while-revalidate=86400" - : "public, max-age=1, s-maxage=60", + status === 503 + ? "no-store" + : entry && !result.stale + ? "public, max-age=60, s-maxage=300, stale-while-revalidate=86400" + : "public, max-age=1, s-maxage=60", + ...(status === 503 ? { "Retry-After": "60" } : {}), "Access-Control-Allow-Origin": "*", }, }, diff --git a/services/site/src/lib/docs.ts b/services/site/src/lib/docs.ts index 55a6d156562..d92959930a1 100644 --- a/services/site/src/lib/docs.ts +++ b/services/site/src/lib/docs.ts @@ -1,5 +1,4 @@ -// Where the current docs live. The docs Intro is a page of this app; the other docs pages come from -// the separate docs app at the same paths. The old /v2/docs URLs redirect here (see middleware.ts). +// Where the current docs live: the V2 docs app (services/www), which serves /v2* on opencode.ai. export const docsBase = "/v2/docs" /** Where the separate V1 docs app (Starlight, built for /docs/) serves the V1 docs. */ diff --git a/services/site/src/lib/html-cache.ts b/services/site/src/lib/html-cache.ts index 5e95f500059..89e17daf426 100644 --- a/services/site/src/lib/html-cache.ts +++ b/services/site/src/lib/html-cache.ts @@ -21,8 +21,9 @@ import { platformFromUserAgent } from "~/lib/platform" // would get the same HTML, and Vary (which Cloudflare's cache would apply to raw header values) plays // no part. The build id is in the key too, so a deploy starts from an empty cache without a purge. // -// Never cached: a response that sets other cookies, and any status but 200. A render that used a -// stand-in for GitHub's data (lib/edge-cache.ts) is kept fresh for 30 seconds only. +// Never cached: a response that sets other cookies, and any status but 200; a server error (a +// release page while GitHub is down) also tells browsers not to keep it, and to retry in a minute. A render that used a stand-in for GitHub's data (lib/edge-cache.ts) +// is kept fresh for 30 seconds only. type Middleware = ReturnType[number] @@ -86,6 +87,11 @@ export const htmlCache: Middleware = async (event, next) => { const value = await next() if (typeof value !== "string") return value + if (event.res.status && event.res.status >= 500) { + event.res.headers.set("Cache-Control", "no-store") + event.res.headers.set("Retry-After", "60") + return value + } const cookies = event.res.headers.getSetCookie() event.res.headers.set("Cache-Control", cookies.length ? cookiePolicy : browserPolicy) event.res.headers.set("ETag", await etag(value)) diff --git a/services/site/src/lib/security-headers.ts b/services/site/src/lib/security-headers.ts new file mode 100644 index 00000000000..ad6c4f59983 --- /dev/null +++ b/services/site/src/lib/security-headers.ts @@ -0,0 +1,17 @@ +// Headers that protect visitors without changing how a page renders, on every response the site's +// Worker makes after the fixed-URL machine files (lib/meta.ts, whose headers are a contract). The +// static assets don't need them: a page's own response sets its referrer policy and framing, and +// HSTS applies to the whole host. Set in middleware.ts. +// +// - HSTS: the same max-age the Console already sends on this host; no includeSubDomains. +// - Framing: only the site itself, for the device preview (/devices) and the video editor. +// - Permissions: off for powerful features the site never uses. The microphone stays allowed for +// voice mode; test/security-headers.test.ts fails if code starts using a blocked feature. +export const securityHeaders = { + "Strict-Transport-Security": "max-age=31536000", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "strict-origin-when-cross-origin", + "Content-Security-Policy": "frame-ancestors 'self'", + "X-Frame-Options": "SAMEORIGIN", + "Permissions-Policy": "camera=(), geolocation=(), payment=(), usb=()", +} diff --git a/services/site/src/middleware.ts b/services/site/src/middleware.ts index 351c4eaf9c0..1691e9db448 100644 --- a/services/site/src/middleware.ts +++ b/services/site/src/middleware.ts @@ -22,6 +22,7 @@ import { robotsTxt } from "~/lib/robots-txt" import { mediaUrl } from "~/lib/media" import { legacyRedirect } from "~/lib/legacy" import { metaResponse } from "~/lib/meta" +import { securityHeaders } from "~/lib/security-headers" import { v1DocsOrigin } from "~/lib/docs" // The page middleware, then the HTML cache headers and edge cache (lib/html-cache.ts), which see @@ -33,6 +34,8 @@ export default [ // The OAuth client document and the Apple app association, before anything else (lib/meta.ts). const meta = metaResponse(event.request) if (meta) return meta + // Every other response, pages and redirects included (lib/security-headers.ts). + Object.entries(securityHeaders).forEach(([name, value]) => event.response.headers.set(name, value)) event.request = sanitizeServerActionRequest(event.request) @@ -74,9 +77,10 @@ export default [ // /product. The legacy redirects (/go, /zen, /enterprise, /black, /auth, …) are zone rules. const moved = movedPath(url.pathname) if (moved) { - const headers = new Headers({ Location: `${locale ? route(locale, moved) : moved}${url.search}` }) - event.response.headers.getSetCookie().forEach((value) => headers.append("set-cookie", value)) - return new Response(null, { status: 301, headers }) + return new Response(null, { + status: 301, + headers: { Location: `${locale ? route(locale, moved) : moved}${url.search}` }, + }) } if (event.request.method !== "GET" && event.request.method !== "HEAD") return @@ -89,9 +93,7 @@ export default [ const englishOnly = locale !== null && /^\/(changelog|font)(?=$|[/.])/.test(path) const slash = requested.length > 1 && requested.endsWith("/") && !/^\/docs(\/|$)/.test(path) if (english || englishOnly || (slash && findPageMarkdown(path))) { - const headers = new Headers({ Location: `${route(locale ?? "en", path)}${url.search}` }) - event.response.headers.getSetCookie().forEach((value) => headers.append("set-cookie", value)) - return new Response(null, { status: 301, headers }) + return new Response(null, { status: 301, headers: { Location: `${route(locale ?? "en", path)}${url.search}` } }) } // One release as JSON, at a stable URL per version (for the apps' "What's new"). const release = path.match(/^\/changelog\/(v\d[\w.+-]*)\.json$/)?.[1] diff --git a/services/site/src/routes/changelog/[tag].tsx b/services/site/src/routes/changelog/[tag].tsx index a8968a67f77..4f507b27ed7 100644 --- a/services/site/src/routes/changelog/[tag].tsx +++ b/services/site/src/routes/changelog/[tag].tsx @@ -12,6 +12,7 @@ import { useMarkdown } from "~/component/site/use-markdown" import { useI18n } from "~/context/i18n" import { useLanguage } from "~/context/language" import { changelogEntry } from "~/lib/changelog" +import { entryStatus } from "~/lib/changelog-notes" import { changelogEntryPageMarkdown } from "~/lib/changelog-markdown" import { PageTitle } from "~/component/site/sticky-title" @@ -73,9 +74,7 @@ export default function ChangelogRelease() { when={entry()} fallback={ <> - - - + {i18n.t("changelog.title")}
diff --git a/services/site/test/changelog-status.test.ts b/services/site/test/changelog-status.test.ts new file mode 100644 index 00000000000..434fd95099f --- /dev/null +++ b/services/site/test/changelog-status.test.ts @@ -0,0 +1,30 @@ +import { describe, expect, test } from "bun:test" +import type { ChangelogRelease } from "../src/lib/changelog" +import { changelogEntryView, entryStatus, parseReleaseNotes } from "../src/lib/changelog-notes" + +const release: ChangelogRelease = { + tag: "v2.2.5", + name: "v2.2.5", + date: "2026-11-04T12:00:00Z", + url: "https://github.com/anomalyco/opencode/releases/tag/v2.2.5", + highlights: [], + sections: [], + notes: parseReleaseNotes("## Fixes\n- Fixed a crash when the session list was empty"), +} + +// /changelog/ and /changelog/.json answer with this status. +describe("release status", () => { + test("a release in the list is a 200, live or stand-in", () => { + expect(entryStatus(changelogEntryView([release], "v2.2.5"))).toBe(200) + expect(entryStatus(changelogEntryView([release], "v2.2.5", true))).toBe(200) + }) + + test("a tag missing from GitHub's own list is a 404", () => { + expect(entryStatus(changelogEntryView([release], "v0.0.1"))).toBe(404) + }) + + test("a tag missing from a stand-in list, or with no list, is a 503", () => { + expect(entryStatus(changelogEntryView([release], "v1.1.6", true))).toBe(503) + expect(entryStatus(changelogEntryView([], "v1.1.6"))).toBe(503) + }) +}) diff --git a/services/site/test/security-headers.test.ts b/services/site/test/security-headers.test.ts new file mode 100644 index 00000000000..e3f81a9dd9c --- /dev/null +++ b/services/site/test/security-headers.test.ts @@ -0,0 +1,35 @@ +import { describe, expect, test } from "bun:test" +import path from "node:path" +import { Glob } from "bun" +import { securityHeaders } from "../src/lib/security-headers" + +const src = path.join(import.meta.dir, "../src") +const code = ( + await Promise.all( + (await Array.fromAsync(new Glob("**/*.{ts,tsx}").scan({ cwd: src }))).map((file) => + Bun.file(path.join(src, file)).text(), + ), + ) +).join("\n") + +// The code that would need each feature the policy turns off. +const uses: Record = { + camera: /getUserMedia\([^)]*video|allow="[^"]*camera/, + geolocation: /navigator\.geolocation|allow="[^"]*geolocation/, + payment: /PaymentRequest|allow="[^"]*payment/, + usb: /navigator\.usb|allow="[^"]*usb/, + microphone: /getUserMedia\(/, +} + +describe("security headers", () => { + const blocked = securityHeaders["Permissions-Policy"].split(", ").map((rule) => rule.replace(/=\(\)$/, "")) + + test("every feature the policy blocks is one the site never uses", () => { + expect(blocked.filter((feature) => !(feature in uses) || uses[feature].test(code))).toEqual([]) + }) + + test("voice mode keeps the microphone", () => { + expect(uses.microphone.test(code)).toBe(true) + expect(securityHeaders["Permissions-Policy"]).not.toContain("microphone") + }) +})