/** * cotton-site: the static pages (/, /privacy, /terms, the 404) served from * the asset layer, plus the three things only a Worker can answer: the 308 * from the legacy hosts, the Mac app's update feed and download * (`/mac/appcast.xml`, `/mac/download/…`, forwarded to the serving Mac) and * the Mac CI runner binary (`/mac/runner/…`, out of R2). */ import { MAC_COTTON_FEED_HEADERS, MAC_COTTON_PREFIX, MAC_COTTON_ZIP_HEADERS, macCottonKey } from "../shared/macCotton.ts"; import { downloadPathForEnclosure, isMacLatestPath, latestRelease, MAC_DOWNLOAD_CACHE_CONTROL, MAC_DOWNLOAD_CONTENT_TYPE, MAC_DOWNLOAD_PREFIX, MAC_LATEST_CACHE_CONTROL, macDownloadKey, } from "../shared/macDownloads.ts"; import { MAC_RUNNER_CACHE_CONTROL, MAC_RUNNER_CONTENT_TYPE, MAC_RUNNER_PREFIX, macRunnerKey, } from "../shared/macRunner.ts"; import { isMacAppcastPath, MAC_APPCAST_HEADERS, MAC_APPCAST_PATH, } from "../shared/macUpdates.ts"; import { readConfig, type Env } from "./env.ts"; import { withSiteHeaders } from "./headers.ts"; /** * Hostnames that permanently forward to the canonical origin. The Worker * stays attached to cotton.tinmen.ai so every link shared before the move * keeps resolving — but it answers with a 308 so the address bar, the * unfurlers, and the search index all converge on cottondb.com. www is the * same story. */ /** The old internal page of test links, retired 23 Nov 2026: it answers a redirect to the home page's list of apps. */ export const OLD_APP_LINKS = "/apps-5dc0fd79cb"; const LEGACY_HOSTS = new Set(["cotton.tinmen.ai", "www.cottondb.com"]); export default { async fetch(request: Request, env: Env): Promise { const url = new URL(request.url); // Every answer leaves through one door, so the security headers // are never a per-route afterthought (src/worker/headers.ts). return withSiteHeaders(await route(request, env, url)); }, } satisfies ExportedHandler; async function route(request: Request, env: Env, url: URL): Promise { if (LEGACY_HOSTS.has(url.hostname)) { const { publicOrigin } = readConfig(env); return Response.redirect(`${publicOrigin}${url.pathname}${url.search}`, 308); } // The Mac app's update feed, answered by the SERVING MAC off its release // records (`MAC_FEED_ORIGIN`). Anything but an XML 200 from there is a // plain-text refusal here, because an updater handed HTML reports "could // not check for updates" while the site looks healthy. See // `src/shared/macUpdates.ts`. if (isMacAppcastPath(url.pathname)) { const xml = await servedAppcast(env); if (xml.ok === false) return plain(xml.why, xml.status, { "Cache-Control": "no-store" }); return new Response(xml.text, { status: 200, headers: MAC_APPCAST_HEADERS }); } // The Mac app's DOWNLOAD — the zip itself, streamed from the serving Mac, // which reads it off the release record. See `src/shared/macDownloads.ts`. if (url.pathname.startsWith(MAC_DOWNLOAD_PREFIX)) { return macDownload(request, env, url); } // Cotton for the Mac: its update feed and builds, out of the same bucket (`src/shared/macCotton.ts`). if (url.pathname.startsWith(MAC_COTTON_PREFIX)) { return macCotton(request, env, url); } // The Mac's CI RUNNER binary, out of the same bucket. Forgejo publishes no // darwin build, so CottonDB builds one from the tag and serves it here — // `src/shared/macRunner.ts`, and the recipe in // the procedure “Hold a repository's bytes in Cotton, and move its origin off the git host”. if (url.pathname.startsWith(MAC_RUNNER_PREFIX)) { return macRunner(request, env, url); } // The first site's About page: its words now live on the plain privacy page, /yours (the second design, 23 Nov // 2026). A link shared before then still lands somewhere true. if (url.pathname === "/about" || url.pathname === "/about/") return Response.redirect(new URL("/yours", url).toString(), 301); // The old internal page of test links (a hand-written file, not kept up to date, retired 23 Nov 2026): the home page's list of apps carries // each app's links now, from apps.json. A 302, so the address can be given another use without a browser holding on. if (url.pathname === OLD_APP_LINKS || url.pathname === `${OLD_APP_LINKS}.html`) return Response.redirect(new URL("/#get", url).toString(), 302); // A Circle invitation (`/c/#`, made by the Cotton phone app): one page for every code, which names // nobody. The phone app opens the same link itself (universal link / app link); the secret after `#` never comes here // (and is never in a referrer). if (/^\/c\/[a-z0-9]+\/?$/i.test(url.pathname)) { const page = await env.ASSETS.fetch(new Request(new URL("/invite", url).toString(), request)); return new Response(page.body, { status: page.ok ? 200 : page.status, headers: { ...Object.fromEntries(page.headers), "Cache-Control": "no-store" } }); } // Everything else is a page, or the 404 page from the asset layer. return env.ASSETS.fetch(request); } /** A plain-text answer. Never HTML, and never a redirect to somebody's login. */ function plain(body: string, status: number, headers: Record = {}): Response { return new Response(body, { status, headers: { "Content-Type": "text/plain; charset=utf-8", "Cache-Control": "no-store", ...headers }, }); } /** * The deployed appcast's text, or null when the feed is not on this deploy. * * The same asset the `/mac/appcast.xml` branch serves, read here so `latest` * and the feed can never name different builds — one file decides both. */ type Served = { ok: true; text: string } | { ok: false; status: number; why: string }; /** The serving Mac's origin, or null when this deployment names none. */ function feedOrigin(env: Env): string | null { const origin = env.MAC_FEED_ORIGIN?.trim().replace(/\/+$/, ""); return origin ? origin : null; } /** The feed, as the serving Mac answers it off the release records. */ async function servedAppcast(env: Env): Promise { const origin = feedOrigin(env); if (!origin) return { ok: false, status: 503, why: `${MAC_APPCAST_PATH}: this site names no serving Mac` }; let res: Response; try { res = await fetch(`${origin}${MAC_APPCAST_PATH}`, { headers: { Accept: "application/xml" } }); } catch { return { ok: false, status: 502, why: `${MAC_APPCAST_PATH}: the serving Mac did not answer` }; } const type = res.headers.get("Content-Type") ?? ""; if (!res.ok || !type.includes("xml")) { return { ok: false, status: 502, why: `${MAC_APPCAST_PATH}: the serving Mac answered ${res.status}` }; } return { ok: true, text: await res.text() }; } /** The response headers a download carries through from the serving Mac. */ const PASSED_THROUGH = ["Content-Length", "Content-Range", "Accept-Ranges", "ETag", "Last-Modified"]; /** * `/mac/download/…` — the Mac app's zip, and the `latest` pointer. * * The zip is STREAMED from the serving Mac (`MAC_FEED_ORIGIN`), which serves * exactly the files of published Mac releases. Only a name of the download * grammar is forwarded; a name the Mac does not publish is its 404, said here * in plain text — never a login page and never the site. */ async function macDownload(request: Request, env: Env, url: URL): Promise { if (isMacLatestPath(url.pathname)) { const xml = await servedAppcast(env); const latest = xml.ok ? latestRelease(xml.text) : null; const path = latest ? downloadPathForEnclosure(latest.url) : null; if (!path) { return plain( `no Mac build to download: ${MAC_APPCAST_PATH} names none this site serves`, 404, ); } return new Response(null, { status: 302, headers: { Location: new URL(path, url).toString(), "Cache-Control": MAC_LATEST_CACHE_CONTROL, }, }); } const key = macDownloadKey(url.pathname); if (!key) return plain(`${url.pathname} is not a CottonDB download`, 404); if (request.method !== "GET" && request.method !== "HEAD") { return plain(`${request.method} is not how a download is fetched`, 405, { Allow: "GET, HEAD" }); } const origin = feedOrigin(env); if (!origin) return plain(`${key}: this site names no serving Mac`, 503); const headers: Record = {}; const range = request.headers.get("Range"); if (range) headers.Range = range; let res: Response; try { res = await fetch(`${origin}${MAC_DOWNLOAD_PREFIX}${encodeURIComponent(key)}`, { method: request.method, headers }); } catch { return plain(`${key}: the serving Mac did not answer`, 502); } if (res.status === 404) return plain(`${key} is not published`, 404); if (res.status !== 200 && res.status !== 206) return plain(`${key}: the serving Mac answered ${res.status}`, 502); const out: Record = { "Content-Type": MAC_DOWNLOAD_CONTENT_TYPE, "Cache-Control": MAC_DOWNLOAD_CACHE_CONTROL, }; for (const name of PASSED_THROUGH) { const value = res.headers.get(name); if (value) out[name] = value; } return new Response(request.method === "HEAD" ? null : res.body, { status: res.status, headers: out }); } /** What a runner binary answers with. `downloadHeaders`' shape, its own type. */ function runnerHeaders(object: { size: number; httpEtag: string }): Record { return { "Content-Type": MAC_RUNNER_CONTENT_TYPE, "Content-Length": String(object.size), "Cache-Control": MAC_RUNNER_CACHE_CONTROL, ETag: object.httpEtag, }; } /** * `/mac/runner/…` — the darwin `forgejo-runner` the Mac app bundles. * * The same branch `macDownload` takes for a zip, against the same bucket, and * deliberately without a `latest`: the only caller is * `apps/cotton/scripts/fetch-forgejo-runner.sh`, which asks for one pinned * version and then checks the sha256 before the bytes are put anywhere * anything will run them. A missing object answers 404 in plain text naming * the file, so a pin bump that was never published reads as a pin bump that * was never published. */ /** * `/mac/cotton/…` — Cotton for the Mac's feed and zips, out of `MAC_RELEASES` under `cotton/`. Published is 200 * with its length; anything else is a plain-text 404 (an updater handed HTML says "could not check"). */ async function macCotton(request: Request, env: Env, url: URL): Promise { const named = macCottonKey(url.pathname); if (!named) return plain(`${url.pathname} is not a Cotton for the Mac build`, 404); if (request.method !== "GET" && request.method !== "HEAD") { return plain(`${request.method} is not how a download is fetched`, 405, { Allow: "GET, HEAD" }); } const missing = () => plain(`${named.key} is not published`, 404); const headers = (object: { size: number; httpEtag: string }) => ({ ...(named.kind === "feed" ? MAC_COTTON_FEED_HEADERS : MAC_COTTON_ZIP_HEADERS), "Content-Length": String(object.size), ETag: object.httpEtag, }); if (request.method === "HEAD") { const head = await env.MAC_RELEASES.head(named.key); return head ? new Response(null, { status: 200, headers: headers(head) }) : missing(); } const object = await env.MAC_RELEASES.get(named.key); return object ? new Response(object.body, { status: 200, headers: headers(object) }) : missing(); } async function macRunner(request: Request, env: Env, url: URL): Promise { const key = macRunnerKey(url.pathname); if (!key) return plain(`${url.pathname} is not a CottonDB runner build`, 404); if (request.method !== "GET" && request.method !== "HEAD") { return plain(`${request.method} is not how a download is fetched`, 405, { Allow: "GET, HEAD" }); } const missing = () => plain(`${key} is not published`, 404); if (request.method === "HEAD") { const head = await env.MAC_RELEASES.head(key); return head ? new Response(null, { status: 200, headers: runnerHeaders(head) }) : missing(); } const object = await env.MAC_RELEASES.get(key); return object ? new Response(object.body, { status: 200, headers: runnerHeaders(object) }) : missing(); }