The remote keeps nothing in the mind's kv: no read token, and no address
jonas@nustom.com, 2026-11-26 15:12 UTC · b491c3e1c71cd50531c39fddd160503e705cbf0b · parent ca8adfe
2 files changed
M app.ts
@@ -28,18 +28,24 @@ // // THE REMOTE IS A PASS-THROUGH. Each of git's three requests goes to the repo's Cloudflare // Artifacts remote as it came, body streamed, answer streamed back. The app adds three things. -// The address is the mind's own. For a public repo it adds a read token of its own, minted once -// and kept while it lasts. And after a push that moved `main` it tells the mind's repo, which is -// how the mind comes to publish a push to a repo that was made after the deploy. Artifacts checks -// every token, not this file. +// The address is the mind's own. For a public repo it adds a read token of its own. And after a +// push that moved `main` it tells the mind's repo, which is how the mind comes to publish a push +// to a repo that was made after the deploy. Artifacts checks every token, 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. +// NOTHING OF THE REMOTE IS WRITTEN DOWN. Where Artifacts serves a repo is asked of Artifacts, and +// a read token is minted for the request: both are kept in this isolate's memory, a token while it +// lasts, so the two requests of one clone on one connection share them. Until 26 Nov 2026 both +// were in the mind's kv, the token for an hour. Any code that reads the kv could then read a repo +// straight from Artifacts, past the public list, also after the repo was taken off it; and any +// code that writes the kv could name another address, to which the app would then send a token. +// A token lives ten minutes now. Most connections get a new isolate, so most clones ask twice and +// mint once: the remote takes about 60 ms and a mint 150 (measured on iterate.com, 26 Nov 2026, +// and on tthq.app, 24 Nov 2026), and the two run at the same time. NOTHING BOUNDS THE MINTS ACROSS +// ISOLATES: each anonymous read that reaches a new isolate mints one. 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 { reportIssue } from "iterate/lib"; import { type AppDescription, type IterateConfigEntrypoint, serveFiles } from "iterate/sdk"; -import { z } from "zod"; import { openFile } from "@repos/stdlib/open-files.ts"; import theme from "@repos/stdlib/theme.css"; import { @@ -83,20 +89,24 @@ ]; 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; +/** How long a read token of the app's lives. One serves the anonymous reads that reach this + * isolate in that time, and no other isolate has it. */ +const READ_TOKEN_SECONDS = 600; -/** 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(), -}); +/** What one isolate knows of the repos' remotes, in memory alone and gone with the isolate: where + * Artifacts serves each repo, and for a public repo a read token as git sends one, with the + * moment it ends. Each is kept as it is being asked for, so two requests that come together ask + * once. */ +type Remotes = { + addresses: Map<string, Promise<string>>; + readTokens: Map<string, { authorization: Promise<string>; until: number }>; +}; /** `public`: the repos that anyone may read, clone and fetch, by path (`/repos/<name>`). * `icon`: the answer for the mind's icon, which every app serves as its own * (open-files.ts of /repos/stdlib). */ export function gitApp({ public: publicRepos, icon }: { public: string[]; icon: () => Response }) { + const remotes: Remotes = { addresses: new Map(), readTokens: new Map() }; return { /** The app's description and icon, for anyone: the mind's sign-in pages ask for both. */ open: (request: Request) => openFile(request, GIT, icon), @@ -104,7 +114,7 @@ async fetch(request: Request, host: Host): Promise<Response> { const url = new URL(request.url); const wire = GIT_PATH.exec(url.pathname); - if (wire) return remote(request, url, wire, host, publicRepos); + if (wire) return remote(request, url, wire, host, publicRepos, remotes); // a member's page writes through the member's own itx: its socket, and what the socket's // script asks of its host. Anyone else gets the mind's sign-in there. const forMemberPage = host.auth.memberPage(request); @@ -165,6 +175,7 @@ wire: RegExpExecArray, host: Host, publicRepos: string[], + remotes: Remotes, ): Promise<Response> { // `/repos/<name>.git` is the same repo: a person may write the address either way const repo = wire[1]!.replace(/\.git$/, ""); @@ -182,37 +193,41 @@ !headers.has("authorization") && service === "git-upload-pack" && publicRepos.includes(repo); const now = Date.now(); - let kept: z.infer<typeof Kept>; + let address: string; + let authorization: string | undefined; 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); - // a request with its own token needs the remote alone; an anonymous read needs the token too - const enough = anonymousRead ? tokenLasts : true; - if (found && enough) 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)); + // kept as a promise, and forgotten when it fails: the next request asks again + const once = <Kept>(kept: Map<string, Kept>, entry: Kept, asked: Promise<unknown>) => { + kept.set(repo, entry); + asked.catch(() => kept.get(repo) === entry && kept.delete(repo)); + }; + let asked = remotes.addresses.get(repo); + if (!asked) { + asked = itx.cfArtifacts.get(repo).then((artifacts) => artifacts.remote()); + once(remotes.addresses, asked, asked); } + // a request with its own token needs the address alone; an anonymous read needs a token too. + // One that ends within a minute could end in the middle of this clone. + let token = anonymousRead ? remotes.readTokens.get(repo) : undefined; + if (anonymousRead && !(token && token.until > now + 60_000)) { + const minted = itx.cfArtifacts + .get(repo) + .then((artifacts) => artifacts.createToken("read", READ_TOKEN_SECONDS)) + .then((made) => `Basic ${btoa(`x:${made.plaintext}`)}`); + token = { authorization: minted, until: now + READ_TOKEN_SECONDS * 1000 }; + once(remotes.readTokens, token, minted); + } + [address, authorization] = await Promise.all([asked, token?.authorization]); } 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); + if (authorization) headers.set("authorization", authorization); - const upstream = await fetch(`${kept.remote}/${verb}${url.search}`, { + const upstream = await fetch(`${address}/${verb}${url.search}`, { method: request.method, headers, body: request.body,
M tests/app.test.mjs
@@ -10,7 +10,7 @@ const { gitApp } = await import("../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 () => { +test("anyone clones a public repo: the app adds a read token of its own, minted once, and nothing of it is in the mind's kv", async () => { await using remote = await artifactsRemote(); const mind = fakeMind(remote); const git = gitApp({ public: ["/repos/kernel"], ...look }); @@ -43,10 +43,76 @@ { 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"]); + assert.deepEqual(mind.minted, [{ repo: "/repos/kernel", scope: "read", ttlSeconds: 600 }]); + assert.deepEqual(mind.remotesAsked, ["/repos/kernel"]); + assert.deepEqual(mind.kv, {}); }); +test("what an earlier version kept in the kv is never read: not its token, and not its address for the repo", async () => { + await using remote = await artifactsRemote(); + await using elsewhere = await artifactsRemote(); + const mind = fakeMind(remote); + const old = `Basic ${btoa("x:read-token-of-an-earlier-version")}`; + // an entry as the version before kept it, with an address that some other code wrote over it + const entry = JSON.stringify({ + remote: `${elsewhere.origin}/remote/kernel`, + readToken: { authorization: old, until: Date.now() + 3_000_000 }, + }); + mind.kv["git-app:/repos/kernel"] = entry; + const git = gitApp({ public: ["/repos/kernel"], ...look }); + + await git.fetch( + new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack"), + mind, + ); + await git.fetch( + new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack", { + headers: { authorization: "Basic a-callers-own" }, + }), + mind, + ); + assert.deepEqual( + remote.requests.map(({ authorization }) => authorization), + [`Basic ${btoa("x:read-token-1-of-/repos/kernel")}`, "Basic a-callers-own"], + ); + // no credential went to the address in the kv, and the app wrote nothing there + assert.deepEqual(elsewhere.requests, []); + assert.deepEqual(mind.kv, { "git-app:/repos/kernel": entry }); +}); + +test("requests that come together to a new isolate ask for the address once and mint one token", async () => { + await using remote = await artifactsRemote(); + const mind = fakeMind(remote); + const git = gitApp({ public: ["/repos/kernel"], ...look }); + const read = () => + git.fetch( + new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack"), + mind, + ); + + const answers = await Promise.all([read(), read(), read()]); + assert.deepEqual(answers.map(({ status }) => status), [200, 200, 200]); + assert.equal(mind.minted.length, 1); + assert.deepEqual(mind.remotesAsked, ["/repos/kernel"]); +}); + +test("a repo that was public and is taken off the list gets no token: a new isolate has none, and nothing is written down", async () => { + await using remote = await artifactsRemote(); + const mind = fakeMind(remote); + const read = (git) => + git.fetch( + new Request("https://git.example.com/repos/kernel/info/refs?service=git-upload-pack"), + mind, + ); + + assert.equal((await read(gitApp({ public: ["/repos/kernel"], ...look }))).status, 200); + // the config's next publish: the list no longer names the repo + const refused = await read(gitApp({ public: [], ...look })); + assert.equal(refused.status, 401); + assert.equal(remote.requests.at(-1).authorization, undefined); + assert.equal(mind.minted.length, 1); +}); + 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); @@ -180,13 +246,17 @@ ); 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(); + // the same isolate, the same token + assert.equal(mind.minted.length, 1); + // nine and a half minutes later the token ends in half a minute + const realNow = Date.now; + Date.now = () => realNow() + 570_000; + try { + await read(); + } finally { + Date.now = realNow; + } assert.equal(remote.requests.at(-1).authorization, `Basic ${btoa("x:read-token-2-of-/repos/kernel")}`); assert.equal(mind.minted.length, 2);