iterate.com / kernel

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

kernel / core / lib / src / cli / git.tsmain at 949894f

// git.ts — PLAIN `git` OVER HTTPS WITH THE CLI'S OWN SIGN-IN, for a hostname of a mind that serves
// its repos (the git app of a mind's config, at `git.<zone>`):
//
//   iterate git setup git.example.com     once on a computer: sign in, and tell git
//   iterate git-credential get|store|erase  git's credential helper, which git runs itself
//
// `setup` writes two things into git's own config for that one host, and nothing else:
//   - the credential helper, with the helpers that git inherited cleared for this host, so no
//     keychain and no password window is asked for it;
//   - one request header, GIT_MARKER_HEADER. It is public and proves nothing. It tells the host
//     that this git has the helper, so the host answers a request with no credential 401, and git
//     asks the helper. Without the header the host answers 404 with words that say to run the
//     setup: git shows a 404's words and never a first 401's.
//
// THE CREDENTIAL that the helper hands git is a token for that one hostname, which the mind's
// issuer exchanges the CLI's session for (core/auth-worker/src/host-tokens.ts): it opens nothing
// else of the mind, and it ends with the session's own token, within the hour. Git sends it as the
// password of Basic, which every git knows. It is kept beside the session (./config.ts), under the
// host's origin, and in no keychain and no file of git's.
//
// WITH NO SIGN-IN the helper signs in while git waits, when a person is at the terminal. With
// nobody there it prints the setup command and tells git to stop, so git asks for no password.
//
// IN A SANDBOX OF THE MIND there is no sign-in and none is needed: the CLI reaches the mind as the
// code of the sandbox's own context (../node.ts `connectMind`), and code there may mint a token
// for a repo as the mind's other code does (`itx.cfArtifacts`). So the helper answers git a write
// token for the one repo that git names, which lasts five minutes and is kept nowhere, and the
// host passes it on. `setup` there has git name the repo to the helper, and signs nobody in. A
// sandbox whose requests the mind filters has no such session, and so no git. THE TOKEN GOES TO A
// HOST OF THE MIND ALONE (`isHostOfMind`, asked of the mind at each use and at the setup): a
// helper that was set for any other host answers it nothing.
import { spawnSync } from "node:child_process";
import { z } from "zod";
import { isCodingAgent } from "./coding-agent.ts";
import { readSession, removeSession, type StoredSession, writeSession } from "./config.ts";

/** What `setup` has git send to the host with every request: the mark of a git that has the
 *  helper. Public, and no credential. */
export const GIT_MARKER_HEADER = "X-Iterate-Git: 1";

/** The username beside the token. The host reads the password alone. */
const GIT_USERNAME = "iterate";

/** A token with less than this left is exchanged again: git's requests of one clone follow each
 *  other within it. */
export const HOST_TOKEN_LEAST_LEFT_MS = 10 * 60_000;

const TOKEN_EXCHANGE_GRANT = "urn:ietf:params:oauth:grant-type:token-exchange";
const ACCESS_TOKEN_TYPE = "urn:ietf:params:oauth:token-type:access_token";

/** A typed git host as a hostname: `git.example.com`, or a remote's whole address. */
export function gitHostOf(typed: string): string {
  const text = typed.trim().toLowerCase();
  const url = URL.canParse(text) ? new URL(text) : new URL(`https://${text}`);
  if (url.protocol !== "https:" || !url.hostname.includes(".") || url.port)
    throw new Error(`${typed} is no https host: write it as git.example.com.`);
  return url.hostname;
}

/** The mind whose host `host` is, as a person would type its address: the host without its first
 *  label (`git.example.com` is a host of `example.com`). `--mind` names any other. */
export const mindOfGitHost = (host: string) => host.split(".").slice(1).join(".");

/** The setup command, as every breadcrumb prints it. */
export const setupCommandOf = (host: string) => `npx iterate git setup ${host}`;

/** WHAT `setup` WRITES INTO GIT'S GLOBAL CONFIG for `host`, as arguments of `git config --global`,
 *  in order. Running them twice leaves the same config. `helper` is the shell command that runs
 *  this CLI's `git-credential` for the host's mind. */
export function gitConfigOf(input: {
  host: string;
  helper: string;
  /** In a sandbox: git tells the helper which repo it asks for. */
  namesRepo?: boolean;
}): string[][] {
  const credential = `credential.https://${input.host}`;
  return [
    // an empty value clears the helpers that git inherited (the system's keychain, a manager's
    // window), for this host alone
    ["--replace-all", `${credential}.helper`, ""],
    ["--add", `${credential}.helper`, `!${input.helper}`],
    ["--replace-all", `${credential}.useHttpPath`, input.namesRepo ? "true" : "false"],
    ["--replace-all", `http.https://${input.host}/.extraHeader`, GIT_MARKER_HEADER],
  ];
}

/** Writes `gitConfigOf` with the `git` on the path, or throws with what git said. */
export function writeGitConfig(input: Parameters<typeof gitConfigOf>[0]) {
  for (const args of gitConfigOf(input)) {
    const run = spawnSync("git", ["config", "--global", ...args], { encoding: "utf8" });
    if (run.error) throw new Error(`git could not be run: ${run.error.message}`);
    if (run.status !== 0)
      throw new Error(`git config ${args.join(" ")} failed: ${run.stderr.trim()}`);
  }
}

/** What git writes to a helper's stdin: `key=value` lines up to an empty one
 *  (https://git-scm.com/docs/git-credential#IOFMT). A key that ends in `[]` may come many times;
 *  the last is kept, and nothing here reads one. */
export function credentialInputOf(text: string): Record<string, string> {
  const fields: Record<string, string> = {};
  for (const line of text.split("\n")) {
    const at = line.indexOf("=");
    if (at > 0) fields[line.slice(0, at)] = line.slice(at + 1).replace(/\r$/, "");
  }
  return fields;
}

const ExchangeAnswer = z.object({ access_token: z.string().min(1), expires_in: z.number() });

/** A token for `resource` (a mind hostname's origin) in exchange for the session's own token, at
 *  the issuer's token endpoint. A refusal throws with the issuer's words. */
export async function exchangedHostToken(input: {
  tokenEndpoint: string;
  subjectToken: string;
  resource: string;
  fetcher?: typeof fetch;
}): Promise<{ token: string; expiresAt: string }> {
  const started = Date.now();
  const answer = await (input.fetcher || fetch)(input.tokenEndpoint, {
    method: "POST",
    headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
    body: new URLSearchParams({
      grant_type: TOKEN_EXCHANGE_GRANT,
      subject_token: input.subjectToken,
      subject_token_type: ACCESS_TOKEN_TYPE,
      resource: input.resource,
    }),
    signal: AbortSignal.timeout(30_000),
  });
  const body: unknown = await answer.json().catch(() => null);
  const parsed = ExchangeAnswer.safeParse(body);
  if (!answer.ok || !parsed.success) {
    const refusal = z
      .object({ error: z.string(), error_description: z.string().optional() })
      .safeParse(body).data;
    throw new Error(
      refusal
        ? `${refusal.error}${refusal.error_description ? `: ${refusal.error_description}` : ""}`
        : `the sign-in provider answered ${answer.status}`,
    );
  }
  return {
    token: parsed.data.access_token,
    expiresAt: new Date(started + parsed.data.expires_in * 1000).toISOString(),
  };
}

/** What the helper needs of the CLI's sign-in to the host's mind. */
export type GitCredentialIo = {
  /** The session for the mind's API with at least `leastLeftMs` left, signed in or renewed on the
   *  way. With `signIn` false it throws when there is no session to renew. `anew`: the kept
   *  session was refused, so it is forgotten and the person signs in again. */
  session(input: { leastLeftMs: number; signIn: boolean; anew?: boolean }): Promise<StoredSession>;
  fetcher?: typeof fetch;
  /** A line for the person: stderr, which git passes to the screen. */
  say(line: string): void;
  /** IN A SANDBOX OF THE MIND ALONE: a write token of the mind for the one repo at `repo`
   *  (`/repos/<name>`), through the sandbox's own session. Absent on any other computer. */
  repoToken?(repo: string, host: string): Promise<string>;
};

/** Whether `host` is a host of the mind whose own address is `mindUrl` (`itx.url()`, its apex):
 *  that hostname, or a name under it. A sandbox's helper hands a repo's token to no other host:
 *  git asks the helper for whatever host its config names.
 *  A NAME UNDER THE APEX IS ENOUGH IN A SANDBOX, whatever DNS says of it: every request of a
 *  sandbox is the mind's own `itx.fetch`, and a request for a hostname of one of the mind's zones
 *  never leaves the stack. The boundary's own handler answers it
 *  (core/boundary-worker/src/rpc.ts `Door.fetch`), so a record that points such a name at
 *  someone else's server is not followed, and the token reaches the mind's own code alone. */
export function isHostOfMind(host: string, mindUrl: string): boolean {
  if (!URL.canParse(mindUrl)) return false;
  const apex = new URL(mindUrl).hostname.toLowerCase();
  const asked = host.toLowerCase();
  return asked === apex || asked.endsWith(`.${apex}`);
}

/** The repo that git names to the helper as `path` (`repos/config.git`), as the mind names it
 *  (`/repos/config`), or null for what is no repo's path. */
export function repoOfGitPath(path: string | undefined): string | null {
  const repo = `/${(path || "").replace(/^\/+|\/+$/g, "").replace(/\.git$/, "")}`;
  return /^\/repos\/[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*$/.test(repo) ? repo : null;
}

/** Whether a person is there to sign in while git waits: a terminal on stderr, prompts not turned
 *  off, and no coding agent. */
export const personIsThere = (env: Record<string, string | undefined>, stderrIsTty: boolean) =>
  stderrIsTty && env.GIT_TERMINAL_PROMPT !== "0" && !isCodingAgent(env);

/** ONE RUN OF GIT'S CREDENTIAL HELPER: what to write to stdout. `get` answers the host's token, or
 *  `quit=1` after a line that says what to run, so git stops and asks for no password. `erase`
 *  forgets the host's token: git calls it when the host refused one. It never ends the CLI's
 *  sign-in. `store`, and any other word, does nothing. */
export async function gitCredential(input: {
  operation: string;
  /** What git wrote to stdin. */
  asked: string;
  /** The mind's address, as `setup` wrote it into the helper's command. */
  address: string;
  interactive: boolean;
  io: GitCredentialIo;
}): Promise<string> {
  const fields = credentialInputOf(input.asked);
  if (fields.protocol !== "https" || !fields.host) return "";
  const resource = `https://${fields.host}`;
  if (input.operation === "erase") {
    removeSession(resource);
    return "";
  }
  if (input.operation !== "get") return "";
  const stop = (why: string) => {
    input.io.say(
      `iterate: ${why} Run this, then the same git command again:\n  ${setupCommandOf(fields.host!)}`,
    );
    return "quit=1\n";
  };
  if (input.io.repoToken) {
    const repo = repoOfGitPath(fields.path);
    if (!repo) return stop(`git named no repo of ${fields.host} to its helper.`);
    try {
      return credentialOf(await input.io.repoToken(repo, fields.host));
    } catch (error) {
      input.io.say(
        `iterate: this sandbox got no token for ${repo} from ${input.address}: ${error instanceof Error ? error.message : String(error)}`,
      );
      return "quit=1\n";
    }
  }
  const kept = readSession(resource);
  if (kept?.expiresAt && Date.parse(kept.expiresAt) > Date.now() + HOST_TOKEN_LEAST_LEFT_MS)
    return credentialOf(kept.token);
  // twice the least, so the host's token starts with more than the least left
  const leastLeftMs = 2 * HOST_TOKEN_LEAST_LEFT_MS;
  const tokenBy = async (session: StoredSession) => {
    const { token, expiresAt } = await exchangedHostToken({
      tokenEndpoint: session.tokenEndpoint,
      subjectToken: session.token,
      resource,
      fetcher: input.io.fetcher,
    });
    writeSession(resource, {
      issuer: session.issuer,
      tokenEndpoint: session.tokenEndpoint,
      clientId: session.clientId,
      token,
      expiresAt,
    });
    return credentialOf(token);
  };
  let session: StoredSession;
  try {
    session = await input.io.session({ leastLeftMs, signIn: input.interactive });
  } catch (error) {
    return stop(
      `not signed in to ${input.address} (${error instanceof Error ? error.message : String(error)}).`,
    );
  }
  try {
    return await tokenBy(session);
  } catch (refusal) {
    const why = (error: unknown) =>
      `${input.address} gave no token for ${fields.host} (${error instanceof Error ? error.message : String(error)}).`;
    // the kept session was ended at the mind: with a person there, sign in again, once
    if (!input.interactive) return stop(why(refusal));
    try {
      input.io.say(`iterate: your sign-in to ${input.address} has ended.`);
      return await tokenBy(await input.io.session({ leastLeftMs, signIn: true, anew: true }));
    } catch (error) {
      return stop(why(error));
    }
  }
}

const credentialOf = (token: string) => `username=${GIT_USERNAME}\npassword=${token}\n`;