git: a git remote at git.<domain>/repos/<name>
Misha Kaletsky, 2026-11-24 18:22 UTC · 20d58946e4537a27e602931358f920b03f3d4efd · the first commit
3 files changed
A app.test.mjs
@@ -0,0 +1,256 @@ +// app.test.mjs — the git app (app.ts) between a git client and a repo's Artifacts remote. The +// remote here is a local HTTP server that records what reaches it, and the mind is a fake `itx` +// with a kv and the Artifacts verbs the app calls. The app's own fetch goes to that server. +// Run it from the repo's root with `node --test app.test.mjs`. +import assert from "node:assert/strict"; +import { createServer } from "node:http"; +import { test } from "node:test"; +import { gitApp } from "./app.ts"; + +test("anyone clones a public repo: the app adds a read token of its own, minted once and kept in the mind's kv", async () => { + await using remote = await artifactsRemote(); + const mind = fakeMind(remote); + const git = gitApp({ public: ["/repos/kernel"] }); + + const refs = await git.fetch( + new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack"), + mind, + ); + assert.equal(refs.status, 200); + assert.equal(await refs.text(), "refs of /remote/kernel"); + const pack = await git.fetch( + new Request("https://git.example.com/repos/kernel/git-upload-pack", { + method: "POST", + headers: { "content-type": "application/x-git-upload-pack-request" }, + body: "want main", + }), + mind, + ); + assert.equal(await pack.text(), "pack for: want main"); + + const readToken = `Basic ${btoa("x:read-token-1-of-/repos/kernel")}`; + assert.deepEqual( + remote.requests.map(({ method, url, authorization }) => ({ method, url, authorization })), + [ + { + method: "GET", + url: "/remote/kernel/info/refs?service=git-upload-pack", + authorization: readToken, + }, + { method: "POST", url: "/remote/kernel/git-upload-pack", authorization: readToken }, + ], + ); + assert.deepEqual(mind.minted, [{ repo: "/repos/kernel", scope: "read", ttlSeconds: 3600 }]); + assert.deepEqual(Object.keys(mind.kv), ["git-app:/repos/kernel"]); +}); + +test("a repo that is not listed as public is read with the caller's own token, and with none it gets the remote's 401", async () => { + await using remote = await artifactsRemote(); + const mind = fakeMind(remote); + const git = gitApp({ public: ["/repos/kernel"] }); + + const refused = await git.fetch( + new Request("https://git.example.com/repos/config/info/refs?service=git-upload-pack"), + mind, + ); + assert.equal(refused.status, 401); + // git asks for a password when it reads this header + assert.equal(refused.headers.get("www-authenticate"), 'Basic realm="artifacts"'); + + const own = `Basic ${btoa("misha:the-callers-own-token")}`; + const allowed = await git.fetch( + new Request("https://git.example.com/repos/config.git/info/refs?service=git-upload-pack", { + headers: { authorization: own, cookie: "session=of-the-mind", "git-protocol": "version=2" }, + }), + mind, + ); + assert.equal(allowed.status, 200); + assert.deepEqual( + remote.requests.map(({ url, authorization, cookie, gitProtocol }) => ({ + url, + authorization, + cookie, + gitProtocol, + })), + [ + { + url: "/remote/config/info/refs?service=git-upload-pack", + authorization: undefined, + cookie: undefined, + gitProtocol: undefined, + }, + { + url: "/remote/config/info/refs?service=git-upload-pack", + authorization: own, + // a cookie of the mind's never leaves; what git says of its protocol does + cookie: undefined, + gitProtocol: "version=2", + }, + ], + ); + assert.deepEqual(mind.minted, []); +}); + +test("a push needs the caller's own token, to a public repo too: the app adds none", async () => { + await using remote = await artifactsRemote(); + const mind = fakeMind(remote); + const git = gitApp({ public: ["/repos/kernel"] }); + + const refused = await git.fetch( + new Request("https://git.example.com/repos/kernel/info/refs?service=git-receive-pack"), + mind, + ); + assert.equal(refused.status, 401); + + const own = `Basic ${btoa("x:a-write-token")}`; + const pushed = await git.fetch( + new Request("https://git.example.com/repos/kernel/git-receive-pack", { + method: "POST", + headers: { authorization: own }, + body: "the pack", + }), + mind, + ); + assert.equal(await pushed.text(), "pack for: the pack"); + assert.deepEqual( + remote.requests.map(({ url, authorization }) => ({ url, authorization })), + [ + { url: "/remote/kernel/info/refs?service=git-receive-pack", authorization: undefined }, + { url: "/remote/kernel/git-receive-pack", authorization: own }, + ], + ); + assert.deepEqual(mind.minted, []); +}); + +test("a read token that is about to end is replaced, and the repo's remote is not asked for again", async () => { + await using remote = await artifactsRemote(); + const mind = fakeMind(remote); + const git = gitApp({ public: ["/repos/kernel"] }); + const read = () => + git.fetch( + new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack"), + mind, + ); + + await read(); + const kept = JSON.parse(mind.kv["git-app:/repos/kernel"]); + // the kept token ends in half a minute + mind.kv["git-app:/repos/kernel"] = JSON.stringify({ + ...kept, + readToken: { ...kept.readToken, until: Date.now() + 30_000 }, + }); + await read(); + + assert.equal(remote.requests.at(-1).authorization, `Basic ${btoa("x:read-token-2-of-/repos/kernel")}`); + assert.equal(mind.minted.length, 2); + assert.deepEqual(mind.remotesAsked, ["/repos/kernel"]); +}); + +test("what is no git request is refused before the mind is asked anything", async () => { + await using remote = await artifactsRemote(); + const mind = fakeMind(remote); + const git = gitApp({ public: ["/repos/kernel"] }); + + const page = await git.fetch(new Request("https://git.example.com/"), mind); + assert.equal(page.status, 404); + // git's older "dumb" protocol asks for info/refs with no service + const dumb = await git.fetch( + new Request("https://git.example.com/repos/kernel/info/refs"), + mind, + ); + assert.equal(dumb.status, 403); + assert.deepEqual(remote.requests, []); + assert.deepEqual(mind.kv, {}); +}); + +test("a repo the mind does not have is not found", async () => { + await using remote = await artifactsRemote(); + const mind = fakeMind(remote); + const git = gitApp({ public: ["/repos/kernel"] }); + + const answer = await git.fetch( + new Request("https://git.example.com/repos/missing/info/refs?service=git-upload-pack"), + mind, + ); + assert.equal(answer.status, 404); + assert.match(await answer.text(), /^git: no repo at \/repos\/missing/); + assert.deepEqual(remote.requests, []); +}); + +// ── the fixtures ── + +/** The mind as the app reaches it: a kv, and the Artifacts repos `kernel` and `config`, served + * by `remote`. It records each token it mints and each repo whose remote it was asked for. */ +function fakeMind(remote) { + const kv = {}; + const minted = []; + const remotesAsked = []; + const repos = ["/repos/kernel", "/repos/config"]; + const itx = { + kv: { + get: async (key) => kv[key] || null, + put: async (key, value) => { + kv[key] = value; + return { ok: true }; + }, + }, + cfArtifacts: { + get: async (repo) => ({ + remote: async () => { + if (!repos.includes(repo)) throw new Error(`Artifacts: repo not found: ${repo}`); + remotesAsked.push(repo); + return `${remote.origin}/remote/${repo.split("/").at(-1)}`; + }, + createToken: async (scope, ttlSeconds) => { + minted.push({ repo, scope, ttlSeconds }); + return { plaintext: `${scope}-token-${minted.length}-of-${repo}` }; + }, + }), + }, + [Symbol.dispose]() {}, + }; + return { kv, minted, remotesAsked, getItx: () => itx }; +} + +/** A repo's Artifacts remote: a server on this machine that records each request and answers as + * git's smart HTTP does in outline. A request with no credential gets Artifacts' own 401, but + * for a read with a read token or any request with a caller's token. */ +async function artifactsRemote() { + // Node's fetch wants `duplex: "half"` said for a body that is a stream, which the app's is. + // workerd, where the app runs, takes a stream as it is. + const nodeFetch = globalThis.fetch; + globalThis.fetch = (input, init) => nodeFetch(input, { ...init, duplex: "half" }); + + const requests = []; + const server = createServer(async (request, response) => { + const chunks = []; + for await (const chunk of request) chunks.push(chunk); + const body = Buffer.concat(chunks).toString(); + requests.push({ + method: request.method, + url: request.url, + authorization: request.headers.authorization, + cookie: request.headers.cookie, + gitProtocol: request.headers["git-protocol"], + }); + if (!request.headers.authorization) { + response.writeHead(401, { "www-authenticate": 'Basic realm="artifacts"' }).end(); + return; + } + const path = request.url.split("?")[0]; + response.writeHead(200, { "content-type": "application/x-git-advertisement" }); + response.end( + path.endsWith("/info/refs") ? `refs of ${path.replace("/info/refs", "")}` : `pack for: ${body}`, + ); + }); + await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); + return { + requests, + origin: `http://127.0.0.1:${server.address().port}`, + async [Symbol.asyncDispose]() { + globalThis.fetch = nodeFetch; + server.closeAllConnections(); + await new Promise((resolve) => server.close(resolve)); + }, + }; +}
A app.ts
@@ -0,0 +1,121 @@ +// app.ts — A GIT REMOTE AT git.<domain>/repos/<name>, as config/worker.ts mounts it. +// +// It is a pass-through. git's smart HTTP has three requests, and each goes to the repo's +// Cloudflare Artifacts remote as it came, body streamed, answer streamed back: +// +// GET /repos/<name>/info/refs?service=git-upload-pack | git-receive-pack +// POST /repos/<name>/git-upload-pack clone, fetch +// POST /repos/<name>/git-receive-pack push +// +// It adds two things. The address is the mind's own. And a repo that worker.ts lists as public is +// read with no credential: the app adds a read token of its own, minted once and kept while it +// lasts. Every other request needs the caller's own Artifacts token, as git's password (any +// username): Artifacts checks it, not this file. +// +// THE READ TOKEN IS KEPT IN THE MIND'S KV, not in memory: most connections get a new isolate, so +// memory alone would mint a token for almost every clone. A kv read takes 12 to 32 ms, a mint 150 +// (measured on tthq.app, 24 Nov 2026). +// +// What stops a push is Artifacts' own limit of 64 MiB a push, with the same words through this +// app as straight to Artifacts. +import type { IterateConfigEntrypoint } from "iterate/sdk"; +import { z } from "zod"; + +const GIT_PATH = + /^(\/repos\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*?)\/(info\/refs|git-upload-pack|git-receive-pack)$/; + +/** What git sends that Artifacts needs. A cookie or a stamp of the mind's never leaves. */ +const REQUEST_HEADERS = [ + "accept", + "accept-encoding", + "authorization", + "content-encoding", + "content-type", + "git-protocol", + "user-agent", +]; +const ANSWER_HEADERS = ["cache-control", "content-type", "expires", "pragma", "www-authenticate"]; + +/** A mint is billed: one token serves every anonymous read of the repo for this long. */ +const READ_TOKEN_SECONDS = 3600; + +/** What the app keeps of a repo, in the mind's kv under `git-app:<repo>`: where Artifacts serves + * it, and for a public repo a read token and the moment that token ends. */ +const Kept = z.object({ + remote: z.string(), + readToken: z.object({ authorization: z.string(), until: z.number() }).optional(), +}); + +/** `public`: the repos that anyone may clone and fetch, by path (`/repos/<name>`). */ +export function gitApp({ public: publicRepos }: { public: string[] }) { + return { + /** Every request on the app's host. No guard stands before it: Artifacts checks the caller's + * token, and a public repo is for anyone. */ + async fetch( + request: Request, + host: Pick<IterateConfigEntrypoint, "getItx">, + ): Promise<Response> { + const url = new URL(request.url); + const match = GIT_PATH.exec(url.pathname); + if (!match) return new Response("git: clone or push at /repos/<name>\n", { status: 404 }); + // `/repos/<name>.git` is the same repo: a person may write the address either way + const repo = match[1]!.replace(/\.git$/, ""); + const verb = match[2]!; + const service = verb === "info/refs" ? url.searchParams.get("service") : verb; + if (service !== "git-upload-pack" && service !== "git-receive-pack") + return new Response("git: only smart HTTP is served here\n", { status: 403 }); + + const headers = new Headers(); + for (const name of REQUEST_HEADERS) { + const value = request.headers.get(name); + if (value) headers.set(name, value); + } + const anonymousRead = + !headers.has("authorization") && + service === "git-upload-pack" && + publicRepos.includes(repo); + + const now = Date.now(); + let kept: z.infer<typeof Kept>; + try { + using itx = host.getItx(); + const text = await itx.kv.get(`git-app:${repo}`); + const found = text ? Kept.parse(JSON.parse(text)) : null; + // a token that ends within a minute could end in the middle of this clone + const tokenLasts = Boolean(found?.readToken && found.readToken.until > now + 60_000); + if (found && (tokenLasts || !anonymousRead)) kept = found; + else { + const artifacts = await itx.cfArtifacts.get(repo); + kept = { remote: found ? found.remote : await artifacts.remote() }; + if (anonymousRead) { + const token = await artifacts.createToken("read", READ_TOKEN_SECONDS); + kept.readToken = { + authorization: `Basic ${btoa(`x:${token.plaintext}`)}`, + until: now + READ_TOKEN_SECONDS * 1000, + }; + } + await itx.kv.put(`git-app:${repo}`, JSON.stringify(kept)); + } + } catch (error) { + const message = error instanceof Error ? error.message : String(error); + return new Response(`git: no repo at ${repo} (${message})\n`, { + status: /not found|10200/i.test(message) ? 404 : 502, + }); + } + if (anonymousRead && kept.readToken) headers.set("authorization", kept.readToken.authorization); + + const upstream = await fetch(`${kept.remote}/${verb}${url.search}`, { + method: request.method, + headers, + body: request.body, + redirect: "manual", + }); + const answerHeaders = new Headers(); + for (const name of ANSWER_HEADERS) { + const value = upstream.headers.get(name); + if (value) answerHeaders.set(name, value); + } + return new Response(upstream.body, { status: upstream.status, headers: answerHeaders }); + }, + }; +}
A tsconfig.json
@@ -0,0 +1,4 @@ +{ + "extends": "../tsconfig.base.json", + "include": ["**/*.ts"] +}