g1t/apps/web/workers/app.ts

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