Skip to content

Commit fdddc95

Browse files
authored
fix(site): security headers, Workers Logs and launch fixes (#62222)
1 parent 2658ec0 commit fdddc95

12 files changed

Lines changed: 129 additions & 23 deletions

File tree

‎services/site/AGENTS.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ Read the design-system rules in `DESIGN.md` (also shown at `/dev/components#rule
55
## Public pages
66

77
- 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).
8-
- `/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.
8+
- `/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.
99
- `/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.
1010
- Do not add a static `public/sitemap.xml`, because it would hide the generated one.
1111
- 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.

‎services/site/cloudflare.config.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,8 @@ export default defineConfig(({ mode }) => {
3434
: [],
3535
workersDev: false,
3636
previewUrls: false,
37+
// Workers Logs: requests, errors and console output, searchable in the Cloudflare dashboard.
38+
observability: { enabled: true },
3739
},
3840
}
3941
})

‎services/site/public/_headers‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Cache headers for the static files in public/ (Cloudflare Workers static assets; SST uploads
1+
# Cache headers for the static files in public/ (Cloudflare Workers static assets; script/build.ts ships
22
# .output/public/_headers with the assets). Nitro appends its own /_build/assets/* rule (hashed
33
# build files, immutable). Rules must not overlap: Cloudflare joins repeated headers with a comma.
44
#

‎services/site/src/lib/changelog-notes.ts‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -58,6 +58,8 @@ export type ChangelogView = {
5858
/** For one entry: the newer and older entries next to it. */
5959
newer?: { tag: string; title: string }
6060
older?: { tag: string; title: string }
61+
/** The releases are a stand-in (the build snapshot or the last good list) because GitHub failed just now. */
62+
stale?: boolean
6163
}
6264

6365
/** Entries per changelog page. */
@@ -303,7 +305,7 @@ export function changelogView(
303305
}
304306

305307
/** The entry that includes the release `tag` (merged entries answer to each of their tags), with its neighbours. */
306-
export function changelogEntryView(releases: ChangelogRelease[], tag: string): ChangelogView {
308+
export function changelogEntryView(releases: ChangelogRelease[], tag: string, stale?: boolean): ChangelogView {
307309
const entries = changelogTimeline(releases)
308310
const index = entries.findIndex((item) => item.releases.some((release) => release.tag === tag))
309311
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
317319
filter: [],
318320
newer: index > 0 ? link(entries[index - 1]) : undefined,
319321
older: index >= 0 ? link(entries[index + 1]) : undefined,
322+
stale,
320323
}
321324
}
322325

326+
/**
327+
* The HTTP status of one release's page and JSON. A tag missing from GitHub's own list is a 404; one
328+
* missing from a stand-in list, or with no list at all, is a 503, because it may be a release the
329+
* stand-in doesn't have.
330+
*/
331+
export function entryStatus(view: ChangelogView) {
332+
if (view.entries.length) return 200
333+
return view.ok && !view.stale ? 404 : 503
334+
}
335+
323336
/** The `?page=…&area=…` query for a changelog view, without the defaults. */
324337
export function changelogQuery(options: { page?: number; filter?: string[] }) {
325338
const params = [

‎services/site/src/lib/changelog.ts‎

Lines changed: 10 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import { staleValue } from "~/lib/edge-cache"
55
import {
66
changelogEntryView,
77
changelogView,
8+
entryStatus,
89
parseReleaseNotes,
910
type ChangelogView,
1011
type ReleaseNotes,
@@ -165,7 +166,7 @@ export const changelogPage = query(async (page: number, filter: string[]): Promi
165166
export const changelogEntry = query(async (tag: string): Promise<ChangelogView> => {
166167
"use server"
167168
const result = await loadChangelog()
168-
return changelogEntryView(result.releases, tag)
169+
return changelogEntryView(result.releases, tag, result.stale)
169170
}, "changelog-entry")
170171

171172
/** 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<Changelo
181182
*/
182183
export async function changelogEntryJson(tag: string) {
183184
const result = await loadChangelog(feedWait).catch((): ChangelogData => ({ ok: false, releases: [] }))
184-
const view = changelogEntryView(result.releases, tag)
185+
const view = changelogEntryView(result.releases, tag, result.stale)
185186
const entry = view.entries[0]
186-
// A tag missing from a stale list may just be newer than it: a 404 then, cached for a minute only.
187-
const status = entry ? 200 : result.ok ? 404 : 503
187+
const status = entryStatus(view)
188188
return new Response(
189189
JSON.stringify(
190190
entry
@@ -196,9 +196,12 @@ export async function changelogEntryJson(tag: string) {
196196
headers: {
197197
"Content-Type": "application/json",
198198
"Cache-Control":
199-
entry && !result.stale
200-
? "public, max-age=60, s-maxage=300, stale-while-revalidate=86400"
201-
: "public, max-age=1, s-maxage=60",
199+
status === 503
200+
? "no-store"
201+
: entry && !result.stale
202+
? "public, max-age=60, s-maxage=300, stale-while-revalidate=86400"
203+
: "public, max-age=1, s-maxage=60",
204+
...(status === 503 ? { "Retry-After": "60" } : {}),
202205
"Access-Control-Allow-Origin": "*",
203206
},
204207
},

‎services/site/src/lib/docs.ts‎

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
1-
// Where the current docs live. The docs Intro is a page of this app; the other docs pages come from
2-
// the separate docs app at the same paths. The old /v2/docs URLs redirect here (see middleware.ts).
1+
// Where the current docs live: the V2 docs app (services/www), which serves /v2* on opencode.ai.
32
export const docsBase = "/v2/docs"
43

54
/** Where the separate V1 docs app (Starlight, built for /docs/) serves the V1 docs. */

‎services/site/src/lib/html-cache.ts‎

Lines changed: 8 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,8 +21,9 @@ import { platformFromUserAgent } from "~/lib/platform"
2121
// would get the same HTML, and Vary (which Cloudflare's cache would apply to raw header values) plays
2222
// no part. The build id is in the key too, so a deploy starts from an empty cache without a purge.
2323
//
24-
// Never cached: a response that sets other cookies, and any status but 200. A render that used a
25-
// stand-in for GitHub's data (lib/edge-cache.ts) is kept fresh for 30 seconds only.
24+
// Never cached: a response that sets other cookies, and any status but 200; a server error (a
25+
// 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)
26+
// is kept fresh for 30 seconds only.
2627

2728
type Middleware = ReturnType<typeof createMiddleware>[number]
2829

@@ -86,6 +87,11 @@ export const htmlCache: Middleware = async (event, next) => {
8687

8788
const value = await next()
8889
if (typeof value !== "string") return value
90+
if (event.res.status && event.res.status >= 500) {
91+
event.res.headers.set("Cache-Control", "no-store")
92+
event.res.headers.set("Retry-After", "60")
93+
return value
94+
}
8995
const cookies = event.res.headers.getSetCookie()
9096
event.res.headers.set("Cache-Control", cookies.length ? cookiePolicy : browserPolicy)
9197
event.res.headers.set("ETag", await etag(value))
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
// Headers that protect visitors without changing how a page renders, on every response the site's
2+
// Worker makes after the fixed-URL machine files (lib/meta.ts, whose headers are a contract). The
3+
// static assets don't need them: a page's own response sets its referrer policy and framing, and
4+
// HSTS applies to the whole host. Set in middleware.ts.
5+
//
6+
// - HSTS: the same max-age the Console already sends on this host; no includeSubDomains.
7+
// - Framing: only the site itself, for the device preview (/devices) and the video editor.
8+
// - Permissions: off for powerful features the site never uses. The microphone stays allowed for
9+
// voice mode; test/security-headers.test.ts fails if code starts using a blocked feature.
10+
export const securityHeaders = {
11+
"Strict-Transport-Security": "max-age=31536000",
12+
"X-Content-Type-Options": "nosniff",
13+
"Referrer-Policy": "strict-origin-when-cross-origin",
14+
"Content-Security-Policy": "frame-ancestors 'self'",
15+
"X-Frame-Options": "SAMEORIGIN",
16+
"Permissions-Policy": "camera=(), geolocation=(), payment=(), usb=()",
17+
}

‎services/site/src/middleware.ts‎

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,7 @@ import { robotsTxt } from "~/lib/robots-txt"
2222
import { mediaUrl } from "~/lib/media"
2323
import { legacyRedirect } from "~/lib/legacy"
2424
import { metaResponse } from "~/lib/meta"
25+
import { securityHeaders } from "~/lib/security-headers"
2526
import { v1DocsOrigin } from "~/lib/docs"
2627

2728
// The page middleware, then the HTML cache headers and edge cache (lib/html-cache.ts), which see
@@ -33,6 +34,8 @@ export default [
3334
// The OAuth client document and the Apple app association, before anything else (lib/meta.ts).
3435
const meta = metaResponse(event.request)
3536
if (meta) return meta
37+
// Every other response, pages and redirects included (lib/security-headers.ts).
38+
Object.entries(securityHeaders).forEach(([name, value]) => event.response.headers.set(name, value))
3639

3740
event.request = sanitizeServerActionRequest(event.request)
3841

@@ -74,9 +77,10 @@ export default [
7477
// /product. The legacy redirects (/go, /zen, /enterprise, /black, /auth, …) are zone rules.
7578
const moved = movedPath(url.pathname)
7679
if (moved) {
77-
const headers = new Headers({ Location: `${locale ? route(locale, moved) : moved}${url.search}` })
78-
event.response.headers.getSetCookie().forEach((value) => headers.append("set-cookie", value))
79-
return new Response(null, { status: 301, headers })
80+
return new Response(null, {
81+
status: 301,
82+
headers: { Location: `${locale ? route(locale, moved) : moved}${url.search}` },
83+
})
8084
}
8185

8286
if (event.request.method !== "GET" && event.request.method !== "HEAD") return
@@ -89,9 +93,7 @@ export default [
8993
const englishOnly = locale !== null && /^\/(changelog|font)(?=$|[/.])/.test(path)
9094
const slash = requested.length > 1 && requested.endsWith("/") && !/^\/docs(\/|$)/.test(path)
9195
if (english || englishOnly || (slash && findPageMarkdown(path))) {
92-
const headers = new Headers({ Location: `${route(locale ?? "en", path)}${url.search}` })
93-
event.response.headers.getSetCookie().forEach((value) => headers.append("set-cookie", value))
94-
return new Response(null, { status: 301, headers })
96+
return new Response(null, { status: 301, headers: { Location: `${route(locale ?? "en", path)}${url.search}` } })
9597
}
9698
// One release as JSON, at a stable URL per version (for the apps' "What's new").
9799
const release = path.match(/^\/changelog\/(v\d[\w.+-]*)\.json$/)?.[1]

‎services/site/src/routes/changelog/[tag].tsx‎

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import { useMarkdown } from "~/component/site/use-markdown"
1212
import { useI18n } from "~/context/i18n"
1313
import { useLanguage } from "~/context/language"
1414
import { changelogEntry } from "~/lib/changelog"
15+
import { entryStatus } from "~/lib/changelog-notes"
1516
import { changelogEntryPageMarkdown } from "~/lib/changelog-markdown"
1617
import { PageTitle } from "~/component/site/sticky-title"
1718

@@ -73,9 +74,7 @@ export default function ChangelogRelease() {
7374
when={entry()}
7475
fallback={
7576
<>
76-
<Show when={current().ok}>
77-
<HttpStatusCode code={404} />
78-
</Show>
77+
<HttpStatusCode code={entryStatus(current())} />
7978
<Title>{i18n.t("changelog.title")}</Title>
8079
<section data-component="hero">
8180
<PageTitle title={i18n.t("changelog.hero.title")} />

0 commit comments

Comments
 (0)