iterate.com / git

git clone https://git.iterate.com/repos/git

git / app.tsmain at 517348b

// app.ts — THE MIND'S REPOS AT git.<domain>, as config/worker.ts mounts it: a git remote for git
// itself, and pages for a person who reads a repo, or proposes a change to it, in a browser.
//
//   GET  /                                   the repos
//   GET  /repos/<name>                       the repo's files and its README
//   GET  /repos/<name>/tree/main/<path>      a folder of it, or a file
//   GET  /repos/<name>/edit/main/<path>      a file in a box, for a member to change and commit
//   GET  /repos/<name>/commits               its newest commits
//   GET  /repos/<name>/commit/<oid>          one commit: what it changed
//   GET  /repos/<name>/branches              its branches, each with its pull or a compare link
//   GET  /repos/<name>/releases              its releases: each a tag of git, with its notes
//   GET  /repos/<name>/compare/<branch>      a branch against main, and the box that opens a pull
//   GET  /repos/<name>/pulls                 its pulls
//   GET  /repos/<name>/pull/<number>         one pull: its conversation and what it changes
//
//   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
//
// The files: this one (who may do what, and the remote), pages.ts (each page's HTML), pulls.ts
// (what a pull is), releases.ts (what a release is, and how one is cut), and public/ (what the
// browser runs).
//
// WHO MAY READ. A repo that worker.ts lists as public is for anyone: its pages, its pulls, and a
// clone with no credential. Any other repo's pages, and git on it, are for a member of the mind.
// A push is a member's, on every repo.
//
// WHO MAY WRITE. A member alone opens a pull, comments and merges: the page does each through the
// member's own `itx` (public/mind.js, over the socket that `host.auth.memberPage` answers), so the
// platform records who did it. This file writes nothing of a pull. A member's edit of a file is
// written the same way: a commit to main is `repos.get(repo).commitFiles` of the member's own
// itx, and a commit to a new branch is a push from the member's page to the remote below, which
// takes it as it takes any member's push.
//
// WHO GIT IS. The platform says it, as for a page: git sends a token of the mind for this one
// host, which the `iterate` CLI's credential helper hands it (`npx iterate git setup <host>`),
// and the boundary checks that token on every request and stamps the member. This file reads the
// stamp. A sign-in that ended, or a member who was removed, has no stamp at the next request.
//
// THE REMOTE. Each of git's three requests goes to the repo's Cloudflare Artifacts remote, body
// streamed, answer streamed back, WITH A TOKEN OF THE APP'S OWN: a read token that this isolate
// keeps in memory while it lasts, or a write token that is minted for the one request of a push.
// A member's git never sees an Artifacts token. After a push the app writes who pushed which refs
// on the repo's log (`git/pushed`), and after one 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.
//
// A CALLER'S OWN ARTIFACTS TOKEN IS PASSED ON, and Artifacts checks it. Only code of the mind
// can mint one (`itx.cfArtifacts`): an agent's script, and git's helper in a sandbox of the mind,
// which has no person to sign in and asks the mind for the one repo's token through the
// sandbox's own session. Nobody is written as the one who pushed then: Artifacts knows a token
// and no person.
//
// WHAT A REQUEST WITH NO SIGN-IN IS TOLD is the same for a repo that is not public and for no
// repo at all, so the answer says nothing of what exists (`refusal`). Every refusal is on git's
// first request and is plain text: git shows those words, and shows none for a later request.
//
// 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 second request of a clone on one connection asks for neither. 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 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 { errorCode, reportIssue } from "iterate/lib";
import { type AppDescription, type IterateConfigEntrypoint, serveFiles } from "iterate/sdk";
import { openFile } from "@repos/stdlib/open-files.ts";
import theme from "@repos/stdlib/theme.css";
import {
  branchesPage,
  codePage,
  commitPage,
  commitsPage,
  comparePage,
  editPage,
  nameOf,
  note,
  page,
  PAGE_PATH,
  pullPage,
  pullsPage,
  releasesPage,
  reposPage,
} from "./pages.ts";
import files from "./public/";

type Host = Pick<IterateConfigEntrypoint, "getItx" | "auth">;

/** What the app says of itself to the mind's sign-in pages. Reading needs no sign-in; the one
 *  who signs in from here is a member. */
const GIT: AppDescription = { name: "Git", icon: "/icon.svg", for: "members" };

/** What the browser asks for beside a page: the app's own files, and the theme that every app of
 *  the mind shares (theme.css of /repos/stdlib). */
const FILES = { ...files, "theme.css": theme };

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, and the
 *  credential that goes is set by `remote`. */
const REQUEST_HEADERS = [
  "accept",
  "accept-encoding",
  "content-encoding",
  "content-type",
  "git-protocol",
  "user-agent",
];
/** Never Artifacts' own challenge: it would have git ask a person for a password. */
const ANSWER_HEADERS = ["cache-control", "content-type", "expires", "pragma"];

/** How long a read token of the app's lives. One serves the reads that reach this isolate in
 *  that time, a member's and for a public repo anyone's, and no other isolate has it. */
const READ_TOKEN_SECONDS = 600;
/** A write token is for the one request it was minted for, and is kept nowhere. */
const WRITE_TOKEN_SECONDS = 300;

/** The header that `iterate git setup` has git send (iterate/cli git.ts `GIT_MARKER_HEADER`): this
 *  git has the credential helper. It is public and proves nothing. */
const HELPER_MARKER = "x-iterate-git";

/** What one isolate knows of the repos' remotes, in memory alone and gone with the isolate: where
 *  Artifacts serves each repo, and a read token of it as git sends one, with the moment it ends.
 *  EACH IS KEPT AS A VALUE, AFTER ITS ANSWER CAME, AND NEVER AS A PROMISE. A promise belongs to the
 *  request that made it: when that request ends first (another part of it failed, or the caller
 *  went away), the promise never settles, and every later request that waits for it fails with
 *  the runtime's "created by a request that has since ended". On iterate.com, 26 Nov 2026, that
 *  turned a member's read of a missing repo into a 502 until the kept token's time was over. So
 *  two requests that come together each ask. */
type Remotes = {
  addresses: Map<string, string>;
  readTokens: Map<string, { authorization: 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),
    /** Every request on the app's host. No guard stands before it: the app says who may read. */
    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, 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);
      if (forMemberPage) return forMemberPage;

      const pathname = url.pathname.replace(/\/+$/, "") || "/";
      if (Object.hasOwn(FILES, pathname.slice(1))) return serveFiles(request, { files: FILES });
      // the mind's sign-in, then back to the page the person came from
      if (pathname === "/sign-in") {
        const to = url.searchParams.get("to") || "/";
        const back = to.startsWith("/") && !to.startsWith("//") ? to : "/";
        return host.auth.require(request) || Response.redirect(`${url.origin}${back}`, 302);
      }
      if (pathname === "/") return reposPage(request, url, host, publicRepos);

      const match = PAGE_PATH.exec(pathname);
      if (!match) return new Response("git: clone or push at /repos/<name>\n", { status: 404 });
      const repo = `/repos/${match[1]}`;
      const isPublic = publicRepos.includes(repo);
      // null for a member; for anyone else the mind's sign-in, which a repo that is not public
      // answers with
      const signIn = host.auth.require(request);
      if (signIn && !isPublic) return signIn;
      // the member, as a page shows them: the name before the `@` of their address
      const me = signIn ? null : host.auth.principal(request)?.email?.split("@")[0] || "a member";
      const view = { url, repo, isPublic, me };
      const rest = match[3] || "";
      // the page that edits a file is a member's, on a public repo too
      if (match[2] === "edit" && signIn) return signIn;
      try {
        using itx = host.getItx();
        const handle = itx.repos.get(repo);
        if (match[2] === "edit")
          return await editPage(view, handle, rest, host.auth.principal(request)?.email || null);
        if (match[2] === "commits") return await commitsPage(view, handle);
        if (match[2] === "commit") return await commitPage(view, handle, itx, rest);
        if (match[2] === "branches") return await branchesPage(view, handle, itx);
        if (match[2] === "releases")
          return await releasesPage(view, itx, await readRemote(itx, repo, remotes));
        if (match[2] === "pulls") return await pullsPage(view, handle, itx);
        if (match[2] === "pull") return await pullPage(view, handle, itx, rest);
        if (match[2] === "compare") return await comparePage(view, handle, itx, rest);
        const [branch, ...segments] = match[2] === "tree" ? rest.split("/") : ["main"];
        if (branch !== "main")
          return page(view, 404, "code", "Not found", note("Only main is shown here."), {});
        const path = segments.filter(Boolean).map(decodeURIComponent).join("/");
        return await codePage(view, handle, path, url.searchParams.has("plain"));
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        // the repo's own words for a path that holds no repo, or held one
        if (/: (not created|deleted)/.test(message))
          return page(view, 404, null, "Not found", note(`The mind has no repo ${nameOf(repo)}.`), {});
        return page(view, 502, null, "Not read", note(`The repo was not read: ${message}`), {});
      }
    },
  };
}

// ── THE REMOTE ──

/** Where a repo's remote is, with the app's read token for it: both from this isolate's memory
 *  while they last, so a page that reads the remote (the releases, which are tags) mints at most
 *  one token in ten minutes here, whoever asks and however often. Each is kept as a value, after
 *  its answer came (`Remotes`). */
async function readRemote(
  itx: ReturnType<Host["getItx"]>,
  repo: string,
  remotes: Remotes,
): Promise<{ address: string; authorization: string }> {
  const now = Date.now();
  const keptAddress = remotes.addresses.get(repo);
  const keptToken = remotes.readTokens.get(repo);
  const artifacts = itx.cfArtifacts.get(repo);
  const [address, authorization] = await Promise.all([
    keptAddress ??
      artifacts
        .then((found) => found.remote())
        .then((found) => (remotes.addresses.set(repo, found), found)),
    keptToken && keptToken.until > now + 60_000
      ? keptToken.authorization
      : artifacts
          .then((found) => found.createToken("read", READ_TOKEN_SECONDS))
          .then((made) => {
            const minted = `Basic ${btoa(`x:${made.plaintext}`)}`;
            remotes.readTokens.set(repo, { authorization: minted, until: now + READ_TOKEN_SECONDS * 1000 });
            return minted;
          }),
  ]);
  return { address, authorization };
}

async function remote(
  request: Request,
  url: URL,
  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$/, "");
  const verb = wire[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 write = service === "git-receive-pack";
  // A PUSH FROM A PAGE IS THIS APP'S OWN PAGE'S. A browser says where a request comes from
  // (`sec-fetch-site`), and git says nothing. A member's page pushes the branch of an edit
  // (public/branch-commit.js) with the member's sign-in, which the browser sends by itself: a page
  // of another site must not push with it.
  const from = request.headers.get("sec-fetch-site");
  if (write && from && from !== "same-origin")
    return new Response("git: a page of another site does not push here\n", { status: 403 });

  // a member, as the boundary stamped them; another mind's stamp is no member's
  const stamped = host.auth.principal(request);
  const member = stamped && stamped.kind !== "mind" ? stamped : null;
  // what the boundary did not take as a token of its own is still here
  const presented = request.headers.get("authorization");
  const ownToken = !member && presented && isArtifactsToken(presented) ? presented : null;
  const anonymousRead = !write && publicRepos.includes(repo);
  if (!member && !ownToken && !anonymousRead) return refusal(request, url, presented);

  const headers = new Headers();
  for (const name of REQUEST_HEADERS) {
    const value = request.headers.get(name);
    if (value) headers.set(name, value);
  }
  const now = Date.now();
  let address: string;
  let authorization: string | undefined;
  try {
    using itx = host.getItx();
    const kept = remotes.addresses.get(repo);
    const asked =
      kept ??
      itx.cfArtifacts
        .get(repo)
        .then((artifacts) => artifacts.remote())
        .then((found) => (remotes.addresses.set(repo, found), found));
    // A read with no token of its own, a member's or anyone's of a public repo, gets the app's
    // read token. One that ends within a minute could end in the middle of this clone.
    const reads = !write && !ownToken;
    const token = reads ? remotes.readTokens.get(repo) : undefined;
    const forRead = !reads
      ? undefined
      : token && token.until > now + 60_000
        ? token.authorization
        : itx.cfArtifacts
            .get(repo)
            .then((artifacts) => artifacts.createToken("read", READ_TOKEN_SECONDS))
            .then((made) => {
              const minted = `Basic ${btoa(`x:${made.plaintext}`)}`;
              remotes.readTokens.set(repo, {
                authorization: minted,
                until: now + READ_TOKEN_SECONDS * 1000,
              });
              return minted;
            });
    // a member's push: a write token for this one request, kept nowhere
    const forPush =
      write && !ownToken
        ? itx.cfArtifacts
            .get(repo)
            .then((artifacts) => artifacts.createToken("write", WRITE_TOKEN_SECONDS))
            .then((made) => `Basic ${btoa(`x:${made.plaintext}`)}`)
        : undefined;
    [address, authorization] = await Promise.all([
      asked,
      ownToken ?? forPush ?? forRead,
    ]);
  } catch (error) {
    // THE MIND DID NOT ANSWER (code UNAVAILABLE: an overload, a reset, a lost connection): that is
    // no word about the repo. A member, and anyone who reads a repo that worker.ts lists as
    // public, gets 503 and when to ask again, so that a script tries again; a 404 here said "no
    // repo" of a repo that is there (27 Nov 2026: CI read it as final). Anyone else still gets the
    // answer that names no repo.
    if (errorCode(error) === "UNAVAILABLE" && (member || anonymousRead))
      return new Response("git: the mind did not answer just now. Try again in a few seconds.\n", {
        status: 503,
        headers: { "retry-after": "10", "cache-control": "no-store" },
      });
    // only a member is told that a repo is not there, or was not read
    if (!member) return refusal(request, url, presented);
    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 (authorization) headers.set("authorization", authorization);

  const upstream = await fetch(`${address}/${verb}${url.search}`, {
    method: request.method,
    headers,
    body: request.body,
    redirect: "manual",
  });
  // Artifacts refused the caller's own token: the app's answer, which names no repo
  if (ownToken && [401, 403, 404].includes(upstream.status)) return refusal(request, url, presented);
  const answerHeaders = new Headers();
  for (const name of ANSWER_HEADERS) {
    const value = upstream.headers.get(name);
    if (value) answerHeaders.set(name, value);
  }
  // A PUSH: git's report is small, so it is read whole and passed on as it came. Who pushed is
  // written on the repo's log, and a push that moved main is told to the repo, so the mind
  // publishes what was pushed.
  if (verb === "git-receive-pack" && upstream.ok) {
    const report = await upstream.arrayBuffer();
    const refs = [...new TextDecoder().decode(report).matchAll(/ok (refs\/\S+)\n/g)].map(
      (line) => line[1]!,
    );
    if (member && refs.length > 0) await recordPush(host, repo, member.email || member.actor, refs);
    if (refs.includes("refs/heads/main")) await tellOfNewTip(host, repo);
    return new Response(report, { status: upstream.status, headers: answerHeaders });
  }
  return new Response(upstream.body, { status: upstream.status, headers: answerHeaders });
}

/** Whether a credential is a Cloudflare Artifacts token (`art_…`), as a bearer or as the password
 *  of Basic: the one credential of a caller's own that the app passes on. */
function isArtifactsToken(authorization: string): boolean {
  const [scheme, value = ""] = authorization.split(/ +/, 2);
  if (scheme?.toLowerCase() === "bearer") return value.startsWith("art_");
  if (scheme?.toLowerCase() !== "basic") return false;
  try {
    const pair = atob(value);
    return pair.slice(pair.indexOf(":") + 1).startsWith("art_");
  } catch {
    return false;
  }
}

/** WHAT A REQUEST THAT IS NO MEMBER'S IS TOLD, the same whether the repo is there or not:
 *
 *    a credential came, and nobody took it    401, "this sign-in has ended": git forgets the token
 *    no credential, the helper's marker       401 with a challenge: git asks the helper
 *    no credential, no marker                 404, with the command that sets the helper up
 *
 *  Git shows a 404's words and a refused credential's, and never a first 401's: so a git with no
 *  helper gets the 404, which is the only way to put its next step on the screen. The challenge
 *  is `Basic`, never the platform's `Bearer realm="iterate"`, which the boundary would turn into
 *  a sign-in page. */
function refusal(request: Request, url: URL, presented: string | null): Response {
  const setup = `  npx iterate git setup ${url.hostname}\n`;
  const plain = { "content-type": "text/plain; charset=utf-8", "cache-control": "no-store" };
  const challenge = { ...plain, "www-authenticate": 'Basic realm="iterate git"' };
  if (presented)
    return new Response(
      `iterate: this sign-in has ended or was taken away.\nSign in again, then run the same command:\n${setup}`,
      { status: 401, headers: challenge },
    );
  if (request.headers.has(HELPER_MARKER))
    return new Response("iterate: sign in to read this repo\n", { status: 401, headers: challenge });
  return new Response(
    `iterate: there is no repo here that you can read.\nIf it is private, sign in once, then run the same command again:\n${setup}`,
    { status: 404, headers: plain },
  );
}

/** Writes who pushed which refs on the repo's log. Artifacts knows a token and no person, so
 *  nothing else says it. A failure is reported and the push stands. */
async function recordPush(host: Host, repo: string, by: string, refs: string[]): Promise<void> {
  try {
    using itx = host.getItx();
    await itx.cd(repo).append({ type: "git/pushed", payload: { by, refs } });
  } catch (error) {
    reportIssue("git-app.push-not-recorded", error, { repo });
  }
}

/** Tells a repo of the mind that its main has a new tip. Cloudflare tells the mind of a push too,
 *  some seconds later, but only for a repo that the deploy knew: `kernel` and `config`. For those
 *  the repo finds the commit told already, and does nothing. A failure is reported and the push
 *  stands: the commits are in the repo, and `itx.repos.get(repo).announceTip()` tells it again. */
async function tellOfNewTip(host: Host, repo: string): Promise<void> {
  try {
    using itx = host.getItx();
    await itx.repos.get(repo).announceTip();
  } catch (error) {
    reportIssue("git-app.push-not-announced", error, { repo });
  }
}