Skip to content
230 linesCodeBlameRaw
1import { createRequestHandler } from "react-router";
2
3import { identityClient, isNamespaceShaped } from "@g1t/contracts";
4
5import { addressesFor } from "../app/lib/addresses";
6import { hardenRegistryHeaders } from "../app/lib/content-safety";
7import { withSiteHeaders } from "../app/lib/page-headers";
8import { finishResponse, withRequestPerf } from "../app/lib/perf.server";
9import { gitLimited, pageLimited, usercontentLimited } from "../app/lib/front-door-limits";
10import { goImport } from "../app/lib/go-get";
11import { repositoryOfPage, stillPublic } from "../app/lib/public-cache";
12import { registryWorkspace, servicePath } from "../app/lib/registry-paths";
13import { usercontentPath } from "../app/lib/usercontent";
14import { serveUsercontent } from "./usercontent";
15
16const loadBuild = () => import("virtual:react-router/server-build");
17
18/**
19 * Given a function for the build, React Router derives everything from it
20 * again on every request: each route wrapped for the timings in
21 * entry.server.tsx, then the route table flattened and ranked, about a
22 * millisecond and a half of CPU a page. The build never changes while an
23 * isolate lives, so outside development it is loaded once and the handler
24 * made once. Development keeps the function, so a changed file is picked up.
25 * Only the made handler is kept, never a promise of one, so no request
26 * waits on another's (a build that fails to load is loaded again next time).
27 */
28let handler: ReturnType<typeof createRequestHandler> | undefined;
29async function requestHandler(request: Request): Promise<Response> {
30 if (import.meta.env.DEV) return createRequestHandler(loadBuild, import.meta.env.MODE)(request);
31 handler ??= createRequestHandler(await loadBuild(), import.meta.env.MODE);
32 return handler(request);
33}
34
35const DOCS = "https://docs.g1t.sh";
36
37/** Where the documentation pages that used to live under /docs are now. */
38const MOVED_DOCS: Record<string, string> = {
39 "/docs": "/quickstart/",
40 "/docs/concepts": "/concepts/overview/",
41 "/docs/authentication": "/guides/authentication/",
42 "/docs/git": "/guides/git/",
43 "/docs/g1t-agents": "/guides/working-with-g1t/",
44 "/docs/agents": "/guides/bring-your-own-agent/",
45 "/docs/api": "/reference/api/",
46 "/docs/api/reference": "/reference/api/",
47};
48
49export default {
50 async fetch(request, env, ctx) {
51 // Repository files and avatars, on their own origin
52 // (g1tusercontent.com): answered before anything of the site's runs,
53 // so nothing there reads or sets the session cookie.
54 const usercontent = usercontentPath(new URL(request.url), addressesFor(env).usercontent);
55 if (usercontent !== null) {
56 return (await usercontentLimited(env, request, usercontent)) ?? serveUsercontent(env, ctx, request, usercontent);
57 }
58 // Every answer: no sniffing, a referrer of the origin alone, and no
59 // framing of pages (app/lib/page-headers.ts).
60 return withSiteHeaders(await site(request, env, ctx));
61 },
62} satisfies ExportedHandler<Env>;
63
64async function site(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
65 const { pathname } = new URL(request.url);
66 // Git over HTTPS shares this hostname but belongs to the repos service.
67 // Its answer goes back to the git client as it is: a repository under a
68 // renamed workspace's old name answers with a 301, which git follows and
69 // must see, so the redirect is never followed here.
70 // The container registry (`docker login g1t.sh`) and the npm registry
71 // (`g1t.sh/-/npm/`) are the packages
72 // service's, handed over the same way.
73 // `go get g1t.sh/<workspace>/<repo>`: where its code is, from the
74 // address alone, so it costs nothing and caches.
75 const go = request.method === "GET" ? goImport(new URL(request.url)) : null;
76 if (go) {
77 return new Response(go, {
78 headers: { "content-type": "text/html; charset=utf-8", "cache-control": "public, max-age=3600" },
79 });
80 }
81 const service = servicePath(pathname);
82 if (service === "git") {
83 // Per address without credentials, per credential with them
84 // (app/lib/front-door-limits.ts): anonymous clones are not free to
85 // the repository's owner.
86 return (await gitLimited(env, request)) ?? proxyGit(env, request);
87 }
88 if (service === "packages") {
89 return proxyPackages(env, request);
90 }
91 // The documentation is its own site.
92 if (pathname === "/docs" || pathname.startsWith("/docs/")) {
93 const page = pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
94 const target = MOVED_DOCS[page] ?? "/";
95 return Response.redirect(DOCS + target, 301);
96 }
97 // Pages and data requests, limited per address signed out and per
98 // session signed in (app/lib/front-door-limits.ts).
99 const limited = await pageLimited(env, request, pathname);
100 if (limited) return limited;
101 // Every page and data request says where its time went (Server-Timing)
102 // and keeps the reader's D1 bookmarks (app/lib/perf.server.ts).
103 const render = () => withRequestPerf(request, async () => finishResponse(request, await requestHandler(request)));
104 if (anonymousPage(request, pathname)) return servePublic(env, request, ctx, render);
105 return render();
106}
107
108/**
109 * Public pages as someone signed out sees them: the same for every such
110 * visitor, so kept in this data centre's cache. Reserved first segments
111 * (settings, sign-in, invitations and the like) and workspace pages (`-`)
112 * are never kept; docs/PERFORMANCE.md lists the rules. A repository's kept
113 * page is served only while repos says the repository is still public: one
114 * made private or deleted is never served from any data centre's copy.
115 */
116const PUBLIC_TOP = /^\/(?:|_root\.data|pricing|explore|security|support|policies(?:\/[a-z-]+)?)(?:\.data)?$/;
117const PUBLIC_PROJECT =
118 /^\/(?!(?:settings|u|auth|oauth|integrations|new|invite|workspaces|device|verify|confirm-email|login|register|logout|forgot|reset|search|status|avatars|docs)\/)[^/]+\/(?!-\/|-$)[^/]+(?:\/(?:code|commits|issues|pulls|pull\/\d+|issues\/\d+|commit\/[0-9a-f]+|tree\/.+|blob\/.+))?(?:\.data)?$/;
119/** Fresh for this long; then served once more while a new copy is made. */
120const PUBLIC_FRESH_SECONDS = 30;
121const PUBLIC_STALE_SECONDS = 300;
122
123function anonymousPage(request: Request, pathname: string): boolean {
124 if (request.method !== "GET") return false;
125 if (/(?:^|;\s*)g1t_session=/.test(request.headers.get("cookie") ?? "")) return false;
126 return PUBLIC_TOP.test(pathname) || PUBLIC_PROJECT.test(pathname);
127}
128
129async function servePublic(env: Env, request: Request, ctx: ExecutionContext, render: () => Promise<Response>): Promise<Response> {
130 const cache = (caches as unknown as { default: Cache }).default;
131 const key = new Request(request.url, { method: "GET" });
132 const repository = PUBLIC_PROJECT.test(new URL(request.url).pathname) ? repositoryOfPage(new URL(request.url).pathname) : null;
133 // Asked alongside the cache, so a hit waits for one indexed read at most.
134 const [cached, visible] = await Promise.all([cache.match(key), repository ? isStillPublic(env, repository) : Promise.resolve(true)]);
135 if (cached && !visible) {
136 ctx.waitUntil(cache.delete(key).then(() => undefined, () => undefined));
137 return render();
138 }
139 const keptAt = Number(cached?.headers.get("x-g1t-kept-at") ?? 0);
140 const age = Math.round((Date.now() - keptAt) / 1000);
141 const refresh = async () => {
142 const fresh = await render();
143 // Only a plain answer for everyone: nothing that sets a cookie or says
144 // it is private.
145 const cacheable =
146 (fresh.status === 200 || fresh.status === 404) &&
147 !fresh.headers.has("set-cookie") &&
148 !/private|no-store/.test(fresh.headers.get("cache-control") ?? "");
149 if (cacheable) {
150 const copy = new Response(fresh.clone().body, fresh);
151 copy.headers.set("x-g1t-kept-at", String(Date.now()));
152 copy.headers.set("cache-control", `public, max-age=${PUBLIC_STALE_SECONDS}`);
153 ctx.waitUntil(cache.put(key, copy));
154 }
155 return fresh;
156 };
157 if (cached && keptAt > 0 && age < PUBLIC_STALE_SECONDS) {
158 if (age >= PUBLIC_FRESH_SECONDS) ctx.waitUntil(refresh().then(() => undefined, () => undefined));
159 const answer = new Response(cached.body, cached);
160 answer.headers.delete("x-g1t-kept-at");
161 answer.headers.delete("cache-control");
162 answer.headers.set("server-timing", `cache;desc="hit, ${age}s old"`);
163 return answer;
164 }
165 return refresh();
166}
167
168/** Whether the repository is there and public; anything else, including no answer, is no. */
169async function isStillPublic(env: Env, repository: string): Promise<boolean> {
170 try {
171 const answer = await env.REPOS.fetch("https://service/rpc/visibility", {
172 method: "POST",
173 headers: { "content-type": "application/json" },
174 body: JSON.stringify({ paths: [repository] }),
175 });
176 return answer.ok && stillPublic(await answer.json(), repository);
177 } catch {
178 return false;
179 }
180}
181
182/**
183 * A git request, answered by the repos service. Its `Server-Timing` header
184 * gains `repos`: how long the answer took to start from here, so the time
185 * between this Worker and the repos service shows beside the steps the
186 * repos service reports.
187 */
188async function proxyGit(env: Env, request: Request): Promise<Response> {
189 const started = Date.now();
190 const answer = await env.REPOS.fetch(new Request(request, { redirect: "manual" }));
191 const response = new Response(answer.body, answer);
192 response.headers.append("server-timing", `repos;dur=${Date.now() - started}`);
193 return response;
194}
195
196/**
197 * A registry request, answered by the packages service as it is: its
198 * redirects (a large blob sent to storage) go back to the client, which
199 * follows them itself. One that found nothing under a workspace's old name
200 * or an alias staff set (`g1t` for `flagon-io`) is sent to the same path
201 * under the workspace's name: only the not-found answer pays for the lookup.
202 * Every answer runs nothing in a browser (app/lib/content-safety.ts): what
203 * a registry serves is its publisher's, on this origin.
204 */
205async function proxyPackages(env: Env, request: Request): Promise<Response> {
206 const started = Date.now();
207 const answer = await env.PACKAGES.fetch(new Request(request, { redirect: "manual" }));
208 const moved = answer.status === 404 ? await registryMoved(env, request) : null;
209 const response = moved ?? new Response(answer.body, answer);
210 hardenRegistryHeaders(response.headers);
211 response.headers.append("server-timing", `packages;dur=${Date.now() - started}`);
212 return response;
213}
214
215/** Where a registry request under an alias or old name goes now, or null. */
216async function registryMoved(env: Env, request: Request): Promise<Response | null> {
217 const url = new URL(request.url);
218 const named = registryWorkspace(url.pathname);
219 if (!named || !isNamespaceShaped(named.slug)) return null;
220 let current: string | null = null;
221 try {
222 current = await identityClient(env.IDENTITY).resolveSlug(named.slug);
223 } catch {
224 return null;
225 }
226 if (!current || current === named.slug) return null;
227 const get = request.method === "GET" || request.method === "HEAD";
228 // 308 keeps a publish a PUT, for the clients that follow it.
229 return new Response(null, { status: get ? 301 : 308, headers: { location: named.under(current) + url.search } });
230}