mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-20 18:57:17 +03:00
fix(site): security headers, Workers Logs and launch fixes (#62222)
This commit is contained in:
@@ -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.
|
||||
|
||||
@@ -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 },
|
||||
},
|
||||
}
|
||||
})
|
||||
|
||||
@@ -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.
|
||||
#
|
||||
|
||||
@@ -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 = [
|
||||
|
||||
@@ -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<ChangelogView> => {
|
||||
"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<Changelo
|
||||
*/
|
||||
export async function changelogEntryJson(tag: string) {
|
||||
const result = await loadChangelog(feedWait).catch((): ChangelogData => ({ 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": "*",
|
||||
},
|
||||
},
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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<typeof createMiddleware>[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))
|
||||
|
||||
@@ -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=()",
|
||||
}
|
||||
@@ -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]
|
||||
|
||||
@@ -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={
|
||||
<>
|
||||
<Show when={current().ok}>
|
||||
<HttpStatusCode code={404} />
|
||||
</Show>
|
||||
<HttpStatusCode code={entryStatus(current())} />
|
||||
<Title>{i18n.t("changelog.title")}</Title>
|
||||
<section data-component="hero">
|
||||
<PageTitle title={i18n.t("changelog.hero.title")} />
|
||||
|
||||
@@ -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/<tag> and /changelog/<tag>.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)
|
||||
})
|
||||
})
|
||||
@@ -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<string, RegExp> = {
|
||||
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")
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user