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.

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