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.

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