Skip to content

Where people and agents ship software together. The open-source git platform for the whole job: issues, agents, checks and deploys to the edge.

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