Skip to content
216 linesCodeBlameRaw

Pick any line to see why it is the way it is: the commit, the pull request and issue it came from, and what the agent was thinking.

Initial g1t: services, event bus, intents and attempts1import { createRequestHandler } from "react-router";
2
Merge branch 'worktree-agent-a8385d293d42c913a'3import { identityClient, isNamespaceShaped } from "@g1t/contracts";
4
Merge g1tusercontent.com: registry answers run nothing in a browser, the site's pages run only their own scripts, repository files and avatars on their own origin, raw files rate limited per address5import { addressesFor } from "../app/lib/addresses";
6import { hardenRegistryHeaders } from "../app/lib/content-safety";
7import { withSiteHeaders } from "../app/lib/page-headers";
Fast pages, required checks on the branch, self-hosted runners, honest incidents8import { finishResponse, withRequestPerf } from "../app/lib/perf.server";
Merge g1tusercontent.com: registry answers run nothing in a browser, the site's pages run only their own scripts, repository files and avatars on their own origin, raw files rate limited per address9import { gitLimited, pageLimited, usercontentLimited } from "../app/lib/front-door-limits";
Composer from the workspace's own repositories, and go get from g1t.sh10import { goImport } from "../app/lib/go-get";
Signed-out page cache: a repository's kept page is served only while the repository is still public, so one made private or deleted never shows from any data centre's copy11import { repositoryOfPage, stillPublic } from "../app/lib/public-cache";
Merge branch 'worktree-agent-a8385d293d42c913a'12import { registryWorkspace, servicePath } from "../app/lib/registry-paths";
Merge g1tusercontent.com: registry answers run nothing in a browser, the site's pages run only their own scripts, repository files and avatars on their own origin, raw files rate limited per address13import { usercontentPath } from "../app/lib/usercontent";
14import { serveUsercontent } from "./usercontent";
Fast pages, required checks on the branch, self-hosted runners, honest incidents15
Initial g1t: services, event bus, intents and attempts16const requestHandler = createRequestHandler(
17 () => import("virtual:react-router/server-build"),
18 import.meta.env.MODE,
19);
20
Docs as their own app; shared theme package21const DOCS = "https://docs.g1t.sh";
Initial g1t: services, event bus, intents and attempts22
Docs as their own app; shared theme package23/** Where the documentation pages that used to live under /docs are now. */
24const MOVED_DOCS: Record<string, string> = {
25 "/docs": "/quickstart/",
26 "/docs/concepts": "/concepts/overview/",
27 "/docs/authentication": "/guides/authentication/",
28 "/docs/git": "/guides/git/",
g1t is one name: its agent's work, commits and comments show as @g1t, and nobody can claim g1t or g1t-agent29 "/docs/g1t-agents": "/guides/working-with-g1t/",
Docs as their own app; shared theme package30 "/docs/agents": "/guides/bring-your-own-agent/",
31 "/docs/api": "/reference/api/",
Merge branch 'worktree-agent-ab2e39e11a6493412'32 "/docs/api/reference": "/reference/api/",
Docs as their own app; shared theme package33};
docs.g1t.sh, generated OpenAPI with an interactive reference, full footer34
Initial g1t: services, event bus, intents and attempts35export default {
Icons are cached at the edge36 async fetch(request, env, ctx) {
Merge g1tusercontent.com: registry answers run nothing in a browser, the site's pages run only their own scripts, repository files and avatars on their own origin, raw files rate limited per address37 // Repository files and avatars, on their own origin
38 // (g1tusercontent.com): answered before anything of the site's runs,
39 // so nothing there reads or sets the session cookie.
40 const usercontent = usercontentPath(new URL(request.url), addressesFor(env).usercontent);
41 if (usercontent !== null) {
42 return (await usercontentLimited(env, request, usercontent)) ?? serveUsercontent(env, ctx, request, usercontent);
Composer from the workspace's own repositories, and go get from g1t.sh43 }
Merge g1tusercontent.com: registry answers run nothing in a browser, the site's pages run only their own scripts, repository files and avatars on their own origin, raw files rate limited per address44 // Every answer: no sniffing, a referrer of the origin alone, and no
45 // framing of pages (app/lib/page-headers.ts).
46 return withSiteHeaders(await site(request, env, ctx));
Initial g1t: services, event bus, intents and attempts47 },
48} satisfies ExportedHandler<Env>;
Workspace names and icons, and a component kit for every control49
Merge g1tusercontent.com: registry answers run nothing in a browser, the site's pages run only their own scripts, repository files and avatars on their own origin, raw files rate limited per address50async function site(request: Request, env: Env, ctx: ExecutionContext): Promise<Response> {
51 const { pathname } = new URL(request.url);
52 // Git over HTTPS shares this hostname but belongs to the repos service.
53 // Its answer goes back to the git client as it is: a repository under a
54 // renamed workspace's old name answers with a 301, which git follows and
55 // must see, so the redirect is never followed here.
56 // The container registry (`docker login g1t.sh`) and the npm registry
57 // (`g1t.sh/-/npm/`) are the packages
58 // service's, handed over the same way.
59 // `go get g1t.sh/<workspace>/<repo>`: where its code is, from the
60 // address alone, so it costs nothing and caches.
61 const go = request.method === "GET" ? goImport(new URL(request.url)) : null;
62 if (go) {
63 return new Response(go, {
64 headers: { "content-type": "text/html; charset=utf-8", "cache-control": "public, max-age=3600" },
65 });
66 }
67 const service = servicePath(pathname);
68 if (service === "git") {
69 // Per address without credentials, per credential with them
70 // (app/lib/front-door-limits.ts): anonymous clones are not free to
71 // the repository's owner.
72 return (await gitLimited(env, request)) ?? proxyGit(env, request);
73 }
74 if (service === "packages") {
75 return proxyPackages(env, request);
76 }
77 // The documentation is its own site.
78 if (pathname === "/docs" || pathname.startsWith("/docs/")) {
79 const page = pathname.endsWith("/") ? pathname.slice(0, -1) : pathname;
80 const target = MOVED_DOCS[page] ?? "/";
81 return Response.redirect(DOCS + target, 301);
82 }
83 // Pages and data requests, limited per address signed out and per
84 // session signed in (app/lib/front-door-limits.ts).
85 const limited = await pageLimited(env, request, pathname);
86 if (limited) return limited;
87 // Every page and data request says where its time went (Server-Timing)
88 // and keeps the reader's D1 bookmarks (app/lib/perf.server.ts).
89 const render = () => withRequestPerf(request, async () => finishResponse(request, await requestHandler(request)));
90 if (anonymousPage(request, pathname)) return servePublic(env, request, ctx, render);
91 return render();
92}
93
Workspace names and icons, and a component kit for every control94/**
Fast pages, required checks on the branch, self-hosted runners, honest incidents95 * Public pages as someone signed out sees them: the same for every such
96 * visitor, so kept in this data centre's cache. Reserved first segments
97 * (settings, sign-in, invitations and the like) and workspace pages (`-`)
Signed-out page cache: a repository's kept page is served only while the repository is still public, so one made private or deleted never shows from any data centre's copy98 * are never kept; docs/PERFORMANCE.md lists the rules. A repository's kept
99 * page is served only while repos says the repository is still public: one
100 * made private or deleted is never served from any data centre's copy.
Fast pages, required checks on the branch, self-hosted runners, honest incidents101 */
102const PUBLIC_TOP = /^\/(?:|_root\.data|pricing|explore|security|support|policies(?:\/[a-z-]+)?)(?:\.data)?$/;
103const PUBLIC_PROJECT =
Merge email confirmation gate: a code and a link, nothing until confirmed (identity 0036)104 /^\/(?!(?: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)?$/;
Fast pages, required checks on the branch, self-hosted runners, honest incidents105/** Fresh for this long; then served once more while a new copy is made. */
106const PUBLIC_FRESH_SECONDS = 30;
107const PUBLIC_STALE_SECONDS = 300;
108
109function anonymousPage(request: Request, pathname: string): boolean {
110 if (request.method !== "GET") return false;
111 if (/(?:^|;\s*)g1t_session=/.test(request.headers.get("cookie") ?? "")) return false;
112 return PUBLIC_TOP.test(pathname) || PUBLIC_PROJECT.test(pathname);
113}
114
Signed-out page cache: a repository's kept page is served only while the repository is still public, so one made private or deleted never shows from any data centre's copy115async function servePublic(env: Env, request: Request, ctx: ExecutionContext, render: () => Promise<Response>): Promise<Response> {
Fast pages, required checks on the branch, self-hosted runners, honest incidents116 const cache = (caches as unknown as { default: Cache }).default;
117 const key = new Request(request.url, { method: "GET" });
Signed-out page cache: a repository's kept page is served only while the repository is still public, so one made private or deleted never shows from any data centre's copy118 const repository = PUBLIC_PROJECT.test(new URL(request.url).pathname) ? repositoryOfPage(new URL(request.url).pathname) : null;
119 // Asked alongside the cache, so a hit waits for one indexed read at most.
120 const [cached, visible] = await Promise.all([cache.match(key), repository ? isStillPublic(env, repository) : Promise.resolve(true)]);
121 if (cached && !visible) {
122 ctx.waitUntil(cache.delete(key).then(() => undefined, () => undefined));
123 return render();
124 }
Fast pages, required checks on the branch, self-hosted runners, honest incidents125 const keptAt = Number(cached?.headers.get("x-g1t-kept-at") ?? 0);
126 const age = Math.round((Date.now() - keptAt) / 1000);
127 const refresh = async () => {
128 const fresh = await render();
129 // Only a plain answer for everyone: nothing that sets a cookie or says
130 // it is private.
131 const cacheable =
132 (fresh.status === 200 || fresh.status === 404) &&
133 !fresh.headers.has("set-cookie") &&
134 !/private|no-store/.test(fresh.headers.get("cache-control") ?? "");
135 if (cacheable) {
136 const copy = new Response(fresh.clone().body, fresh);
137 copy.headers.set("x-g1t-kept-at", String(Date.now()));
138 copy.headers.set("cache-control", `public, max-age=${PUBLIC_STALE_SECONDS}`);
139 ctx.waitUntil(cache.put(key, copy));
140 }
141 return fresh;
142 };
143 if (cached && keptAt > 0 && age < PUBLIC_STALE_SECONDS) {
144 if (age >= PUBLIC_FRESH_SECONDS) ctx.waitUntil(refresh().then(() => undefined, () => undefined));
145 const answer = new Response(cached.body, cached);
146 answer.headers.delete("x-g1t-kept-at");
147 answer.headers.delete("cache-control");
148 answer.headers.set("server-timing", `cache;desc="hit, ${age}s old"`);
149 return answer;
150 }
151 return refresh();
152}
153
Signed-out page cache: a repository's kept page is served only while the repository is still public, so one made private or deleted never shows from any data centre's copy154/** Whether the repository is there and public; anything else, including no answer, is no. */
155async function isStillPublic(env: Env, repository: string): Promise<boolean> {
156 try {
157 const answer = await env.REPOS.fetch("https://service/rpc/visibility", {
158 method: "POST",
159 headers: { "content-type": "application/json" },
160 body: JSON.stringify({ paths: [repository] }),
161 });
162 return answer.ok && stillPublic(await answer.json(), repository);
163 } catch {
164 return false;
165 }
166}
167
Fast pages, required checks on the branch, self-hosted runners, honest incidents168/**
Mission control shows where you are needed and what agents landed without you; git answers in about 200ms169 * A git request, answered by the repos service. Its `Server-Timing` header
170 * gains `repos`: how long the answer took to start from here, so the time
171 * between this Worker and the repos service shows beside the steps the
172 * repos service reports.
173 */
174async function proxyGit(env: Env, request: Request): Promise<Response> {
175 const started = Date.now();
176 const answer = await env.REPOS.fetch(new Request(request, { redirect: "manual" }));
177 const response = new Response(answer.body, answer);
178 response.headers.append("server-timing", `repos;dur=${Date.now() - started}`);
179 return response;
180}
181
182/**
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member183 * A registry request, answered by the packages service as it is: its
184 * redirects (a large blob sent to storage) go back to the client, which
Merge branch 'worktree-agent-a8385d293d42c913a'185 * follows them itself. One that found nothing under a workspace's old name
186 * or an alias staff set (`g1t` for `flagon-io`) is sent to the same path
187 * under the workspace's name: only the not-found answer pays for the lookup.
Merge g1tusercontent.com: registry answers run nothing in a browser, the site's pages run only their own scripts, repository files and avatars on their own origin, raw files rate limited per address188 * Every answer runs nothing in a browser (app/lib/content-safety.ts): what
189 * a registry serves is its publisher's, on this origin.
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member190 */
191async function proxyPackages(env: Env, request: Request): Promise<Response> {
192 const started = Date.now();
193 const answer = await env.PACKAGES.fetch(new Request(request, { redirect: "manual" }));
Merge branch 'worktree-agent-a8385d293d42c913a'194 const moved = answer.status === 404 ? await registryMoved(env, request) : null;
195 const response = moved ?? new Response(answer.body, answer);
Merge g1tusercontent.com: registry answers run nothing in a browser, the site's pages run only their own scripts, repository files and avatars on their own origin, raw files rate limited per address196 hardenRegistryHeaders(response.headers);
Packages, with a container registry on g1t.sh; workspaces deleted whole and kept 30 days; Members for every member197 response.headers.append("server-timing", `packages;dur=${Date.now() - started}`);
198 return response;
199}
200
Merge branch 'worktree-agent-a8385d293d42c913a'201/** Where a registry request under an alias or old name goes now, or null. */
202async function registryMoved(env: Env, request: Request): Promise<Response | null> {
203 const url = new URL(request.url);
204 const named = registryWorkspace(url.pathname);
205 if (!named || !isNamespaceShaped(named.slug)) return null;
206 let current: string | null = null;
207 try {
208 current = await identityClient(env.IDENTITY).resolveSlug(named.slug);
209 } catch {
210 return null;
211 }
212 if (!current || current === named.slug) return null;
213 const get = request.method === "GET" || request.method === "HEAD";
214 // 308 keeps a publish a PUT, for the clients that follow it.
215 return new Response(null, { status: get ? 301 : 308, headers: { location: named.under(current) + url.search } });
Workspace names and icons, and a component kit for every control216}

This file's history is long; its oldest lines are credited to the oldest commit read.