| 1 | import { createRequestHandler } from "react-router"; |
| 2 | |
| 3 | import { finishResponse, withRequestPerf } from "../app/lib/perf.server"; |
| 4 | |
| 5 | const requestHandler = createRequestHandler( |
| 6 | () => import("virtual:react-router/server-build"), |
| 7 | import.meta.env.MODE, |
| 8 | ); |
| 9 | |
| 10 | const GIT_PATH = /\/(info\/refs|git-upload-pack|git-receive-pack)$/; |
| 11 | /** An uploaded avatar, by the SHA-256 of its bytes. */ |
| 12 | const AVATAR_PATH = /^\/avatars\/([0-9a-f]{64})$/; |
| 13 | /** The only types identity stores, having checked each image's bytes. */ |
| 14 | const AVATAR_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]); |
| 15 | const DOCS = "https://docs.g1t.sh"; |
| 16 | |
| 17 | /** Where the documentation pages that used to live under /docs are now. */ |
| 18 | const MOVED_DOCS: Record<string, string> = { |
| 19 | "/docs": "/quickstart/", |
| 20 | "/docs/concepts": "/concepts/overview/", |
| 21 | "/docs/authentication": "/guides/authentication/", |
| 22 | "/docs/git": "/guides/git/", |
| 23 | "/docs/g1t-agents": "/guides/g1t-agents/", |
| 24 | "/docs/agents": "/guides/bring-your-own-agent/", |
| 25 | "/docs/api": "/reference/api/", |
| 26 | "/docs/api/reference": "/reference/api/", |
| 27 | }; |
| 28 | |
| 29 | export default { |
| 30 | async fetch(request, env, ctx) { |
| 31 | const { pathname } = new URL(request.url); |
| 32 | // Git over HTTPS shares this hostname but belongs to the repos service. |
| 33 | // Its answer goes back to the git client as it is: a repository under a |
| 34 | // renamed workspace's old name answers with a 301, which git follows and |
| 35 | // must see, so the redirect is never followed here. |
| 36 | if (GIT_PATH.test(pathname)) { |
| 37 | return proxyGit(env, request); |
| 38 | } |
| 39 | const avatar = AVATAR_PATH.exec(pathname); |
| 40 | if (avatar) { |
| 41 | return serveAvatar(env, ctx, request, avatar[1]); |
| 42 | } |
| 43 | // The documentation is its own site. |
| 44 | if (pathname === "/docs" || pathname.startsWith("/docs/")) { |
| 45 | const page = pathname.endsWith("/") ? pathname.slice(0, -1) : pathname; |
| 46 | const target = MOVED_DOCS[page] ?? "/"; |
| 47 | return Response.redirect(DOCS + target, 301); |
| 48 | } |
| 49 | // Every page and data request says where its time went (Server-Timing) |
| 50 | // and keeps the reader's D1 bookmarks (app/lib/perf.server.ts). |
| 51 | const render = () => withRequestPerf(request, async () => finishResponse(request, await requestHandler(request))); |
| 52 | if (anonymousPage(request, pathname)) return servePublic(request, ctx, render); |
| 53 | return render(); |
| 54 | }, |
| 55 | } satisfies ExportedHandler<Env>; |
| 56 | |
| 57 | /** |
| 58 | * Public pages as someone signed out sees them: the same for every such |
| 59 | * visitor, so kept in this data centre's cache. Reserved first segments |
| 60 | * (settings, sign-in, invitations and the like) and workspace pages (`-`) |
| 61 | * are never kept; docs/PERFORMANCE.md lists the rules. |
| 62 | */ |
| 63 | const PUBLIC_TOP = /^\/(?:|_root\.data|pricing|explore|security|support|policies(?:\/[a-z-]+)?)(?:\.data)?$/; |
| 64 | const PUBLIC_PROJECT = |
| 65 | /^\/(?!(?:settings|u|auth|oauth|integrations|new|invite|workspaces|device|verify|login|register|logout|forgot|reset|search|status|avatars|docs)\/)[^/]+\/(?!-\/|-$)[^/]+(?:\/(?:code|commits|issues|pulls|pull\/\d+|issues\/\d+|commit\/[0-9a-f]+|tree\/.+|blob\/.+))?(?:\.data)?$/; |
| 66 | /** Fresh for this long; then served once more while a new copy is made. */ |
| 67 | const PUBLIC_FRESH_SECONDS = 30; |
| 68 | const PUBLIC_STALE_SECONDS = 300; |
| 69 | |
| 70 | function anonymousPage(request: Request, pathname: string): boolean { |
| 71 | if (request.method !== "GET") return false; |
| 72 | if (/(?:^|;\s*)g1t_session=/.test(request.headers.get("cookie") ?? "")) return false; |
| 73 | return PUBLIC_TOP.test(pathname) || PUBLIC_PROJECT.test(pathname); |
| 74 | } |
| 75 | |
| 76 | async function servePublic(request: Request, ctx: ExecutionContext, render: () => Promise<Response>): Promise<Response> { |
| 77 | const cache = (caches as unknown as { default: Cache }).default; |
| 78 | const key = new Request(request.url, { method: "GET" }); |
| 79 | const cached = await cache.match(key); |
| 80 | const keptAt = Number(cached?.headers.get("x-g1t-kept-at") ?? 0); |
| 81 | const age = Math.round((Date.now() - keptAt) / 1000); |
| 82 | const refresh = async () => { |
| 83 | const fresh = await render(); |
| 84 | // Only a plain answer for everyone: nothing that sets a cookie or says |
| 85 | // it is private. |
| 86 | const cacheable = |
| 87 | (fresh.status === 200 || fresh.status === 404) && |
| 88 | !fresh.headers.has("set-cookie") && |
| 89 | !/private|no-store/.test(fresh.headers.get("cache-control") ?? ""); |
| 90 | if (cacheable) { |
| 91 | const copy = new Response(fresh.clone().body, fresh); |
| 92 | copy.headers.set("x-g1t-kept-at", String(Date.now())); |
| 93 | copy.headers.set("cache-control", `public, max-age=${PUBLIC_STALE_SECONDS}`); |
| 94 | ctx.waitUntil(cache.put(key, copy)); |
| 95 | } |
| 96 | return fresh; |
| 97 | }; |
| 98 | if (cached && keptAt > 0 && age < PUBLIC_STALE_SECONDS) { |
| 99 | if (age >= PUBLIC_FRESH_SECONDS) ctx.waitUntil(refresh().then(() => undefined, () => undefined)); |
| 100 | const answer = new Response(cached.body, cached); |
| 101 | answer.headers.delete("x-g1t-kept-at"); |
| 102 | answer.headers.delete("cache-control"); |
| 103 | answer.headers.set("server-timing", `cache;desc="hit, ${age}s old"`); |
| 104 | return answer; |
| 105 | } |
| 106 | return refresh(); |
| 107 | } |
| 108 | |
| 109 | /** |
| 110 | * A git request, answered by the repos service. Its `Server-Timing` header |
| 111 | * gains `repos`: how long the answer took to start from here, so the time |
| 112 | * between this Worker and the repos service shows beside the steps the |
| 113 | * repos service reports. |
| 114 | */ |
| 115 | async function proxyGit(env: Env, request: Request): Promise<Response> { |
| 116 | const started = Date.now(); |
| 117 | const answer = await env.REPOS.fetch(new Request(request, { redirect: "manual" })); |
| 118 | const response = new Response(answer.body, answer); |
| 119 | response.headers.append("server-timing", `repos;dur=${Date.now() - started}`); |
| 120 | return response; |
| 121 | } |
| 122 | |
| 123 | /** |
| 124 | * An uploaded avatar. Its address is its hash, so it never changes and is |
| 125 | * kept for good. It is served as nothing but an image: the stored type, |
| 126 | * no sniffing, and a policy that lets nothing in it run. |
| 127 | */ |
| 128 | /** |
| 129 | * An uploaded icon. Its address is its content's hash, so it never changes: |
| 130 | * each data centre keeps it in its cache after the first view, and storage |
| 131 | * is read about once per place, not once per visitor. |
| 132 | */ |
| 133 | async function serveAvatar(env: Env, ctx: ExecutionContext, request: Request, hash: string): Promise<Response> { |
| 134 | const method = request.method; |
| 135 | if (method !== "GET" && method !== "HEAD") { |
| 136 | return new Response("Method not allowed", { status: 405, headers: { allow: "GET, HEAD" } }); |
| 137 | } |
| 138 | // The Workers runtime's own cache, which the DOM types do not know. |
| 139 | const cache = (caches as unknown as { default: Cache }).default; |
| 140 | const key = new Request(new URL(`/avatars/${hash}`, request.url).toString(), { method: "GET" }); |
| 141 | const cached = await cache.match(key); |
| 142 | if (cached) { |
| 143 | return method === "HEAD" ? new Response(null, { headers: cached.headers }) : cached; |
| 144 | } |
| 145 | const { value, metadata } = await env.AVATARS.getWithMetadata<{ contentType?: string }>(hash, { |
| 146 | type: "arrayBuffer", |
| 147 | cacheTtl: 86400, |
| 148 | }); |
| 149 | const contentType = metadata?.contentType; |
| 150 | if (!value || !contentType || !AVATAR_TYPES.has(contentType)) { |
| 151 | return new Response("Not found", { |
| 152 | status: 404, |
| 153 | headers: { "cache-control": "public, max-age=60" }, |
| 154 | }); |
| 155 | } |
| 156 | const headers = { |
| 157 | "content-type": contentType, |
| 158 | "content-length": String(value.byteLength), |
| 159 | "cache-control": "public, max-age=31536000, immutable", |
| 160 | "x-content-type-options": "nosniff", |
| 161 | "content-security-policy": "default-src 'none'; sandbox", |
| 162 | "cross-origin-resource-policy": "cross-origin", |
| 163 | }; |
| 164 | ctx.waitUntil(cache.put(key, new Response(value, { headers }))); |
| 165 | return new Response(method === "HEAD" ? null : value, { headers }); |
| 166 | } |