pr_01m47d15m3e54sn21z27rpy5n9/apps/web/workers/app.ts

94 lines3,963 bytesCodeBlame
1import { createRequestHandler } from "react-router";
2
3const requestHandler = createRequestHandler(
4 () => import("virtual:react-router/server-build"),
5 import.meta.env.MODE,
6);
7
8const GIT_PATH = /\/(info\/refs|git-upload-pack|git-receive-pack)$/;
9/** An uploaded avatar, by the SHA-256 of its bytes. */
10const AVATAR_PATH = /^\/avatars\/([0-9a-f]{64})$/;
11/** The only types identity stores, having checked each image's bytes. */
12const AVATAR_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
13const DOCS = "https://docs.g1t.sh";
14
15/** Where the documentation pages that used to live under /docs are now. */
16const MOVED_DOCS: Record<string, string> = {
17 "/docs": "/quickstart/",
18 "/docs/concepts": "/concepts/overview/",
19 "/docs/authentication": "/guides/authentication/",
20 "/docs/git": "/guides/git/",
21 "/docs/g1t-agents": "/guides/g1t-agents/",
22 "/docs/agents": "/guides/bring-your-own-agent/",
23 "/docs/api": "/reference/api/",
24 "/docs/api/reference": "/reference/api/",
25};
26
27export default {
28 async fetch(request, env, ctx) {
29 const { pathname } = new URL(request.url);
30 // Git over HTTPS shares this hostname but belongs to the repos service.
31 // Its answer goes back to the git client as it is: a repository under a
32 // renamed workspace's old name answers with a 301, which git follows and
33 // must see, so the redirect is never followed here.
34 if (GIT_PATH.test(pathname)) {
35 return env.REPOS.fetch(new Request(request, { redirect: "manual" }));
36 }
37 const avatar = AVATAR_PATH.exec(pathname);
38 if (avatar) {
39 return serveAvatar(env, ctx, request, avatar[1]);
40 }
41 // The documentation is its own site.
42 if (pathname === "/docs" || pathname.startsWith("/docs/")) {
43 const page = pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
44 const target = MOVED_DOCS[page] ?? "/";
45 return Response.redirect(DOCS + target, 301);
46 }
47 return requestHandler(request);
48 },
49} satisfies ExportedHandler<Env>;
50
51/**
52 * An uploaded avatar. Its address is its hash, so it never changes and is
53 * kept for good. It is served as nothing but an image: the stored type,
54 * no sniffing, and a policy that lets nothing in it run.
55 */
56/**
57 * An uploaded icon. Its address is its content's hash, so it never changes:
58 * each data centre keeps it in its cache after the first view, and storage
59 * is read about once per place, not once per visitor.
60 */
61async function serveAvatar(env: Env, ctx: ExecutionContext, request: Request, hash: string): Promise<Response> {
62 const method = request.method;
63 if (method !== "GET" && method !== "HEAD") {
64 return new Response("Method not allowed", { status: 405, headers: { allow: "GET, HEAD" } });
65 }
66 // The Workers runtime's own cache, which the DOM types do not know.
67 const cache = (caches as unknown as { default: Cache }).default;
68 const key = new Request(new URL(`/avatars/${hash}`, request.url).toString(), { method: "GET" });
69 const cached = await cache.match(key);
70 if (cached) {
71 return method === "HEAD" ? new Response(null, { headers: cached.headers }) : cached;
72 }
73 const { value, metadata } = await env.AVATARS.getWithMetadata<{ contentType?: string }>(hash, {
74 type: "arrayBuffer",
75 cacheTtl: 86400,
76 });
77 const contentType = metadata?.contentType;
78 if (!value || !contentType || !AVATAR_TYPES.has(contentType)) {
79 return new Response("Not found", {
80 status: 404,
81 headers: { "cache-control": "public, max-age=60" },
82 });
83 }
84 const headers = {
85 "content-type": contentType,
86 "content-length": String(value.byteLength),
87 "cache-control": "public, max-age=31536000, immutable",
88 "x-content-type-options": "nosniff",
89 "content-security-policy": "default-src 'none'; sandbox",
90 "cross-origin-resource-policy": "cross-origin",
91 };
92 ctx.waitUntil(cache.put(key, new Response(value, { headers })));
93 return new Response(method === "HEAD" ? null : value, { headers });
94}