iterate.com / kernel

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

Plain git at a mind's host with the CLI's sign-in #1

merged git-https-credential-helper was squashed into main as 5214eaa by jonas, 2026-11-26 14:13 UTC. jonas opened it 2026-11-26 13:09 UTC.

`npx iterate git setup git.<domain>` once on a computer; then plain `git clone`, `git pull` and `git push`.

- **core/auth-worker `host-tokens.ts`**: the token endpoint answers OAuth token exchange (RFC 8693) itself, for one resource: the origin of a hostname of the mind. A member's API access token is exchanged for a signed token that is that member at that one hostname and nowhere else. It ends when its subject token ends (an hour at most) and has no refresh token. Each use reads the session's grant and the membership again. The OAuth library's own token exchange stays off: it refuses to change a token's resource.
- **core/boundary-worker `stamp.ts`**: on a mind hostname, a token that comes as the password of Basic is read as a bearer is. Git sends its credential so. A password that is no token of ours goes on to the app as it came.
- **core/lib `cli/git.ts`**: `iterate git setup <host>` and git's helper `iterate git-credential`. With nobody there the helper prints the setup command and tells git to stop; with a person there it signs in while git waits. In a sandbox of the mind it signs nobody in and asks the mind for the one repo's token through the sandbox's own session.

Proven on a throwaway dev mind (blimro.com) together with the git app's pull: fresh computer, setup, clone, pull, push, a sign-in ended at the mind, recovery, and a sandbox. Two faults were found there and fixed in this branch (the last two commits).

Not done: nothing ran on macOS or Windows. Pasted tokens, gh wrappers and iterate pr are left out (decisions 6 and 7).

Card: tasks/implement-git-https-credential-helper-and-prove-it-on-a-dev-mind.md. Design: https://docs.iterate.com/notes/git-https-auth-design-2026-11-26.html (decisions 1 to 5 answered by Misha, 26 Nov 2026 12:34 UTC).

Session: claude 4bfd7dc5-ae25-44a2-9e97-71e8cda6eb3a on beelink

Conversation

Nobody has said anything yet.

Sign in to comment or to merge.

Files

11 files changed

A core/auth-worker/src/host-tokens.test.ts
@@ -0,0 +1,210 @@
+import { calculatePKCECodeChallenge, generateRandomCodeVerifier } from "oauth4webapi";
+import { expect, test } from "vitest";
+import { z } from "zod";
+import type { Env } from "./env.ts";
+import { hostTokenResponse, TOKEN_EXCHANGE_GRANT } from "./host-tokens.ts";
+import { keyTokenIdentity } from "./key-tokens.ts";
+import { type GrantProps, oauthHelpers, tokenEndpointResponse } from "./oauth.ts";
+import { configVars } from "./test-support.ts";
+import { whoIs } from "./who-is.ts";
+
+const ISSUER = "https://iterate.example.com";
+const API = `${ISSUER}/api`;
+const GIT = "https://git.example.com";
+const OWNER = "owner@elsewhere.test";
+const owner: GrantProps = {
+  userId: "user_owner",
+  email: OWNER,
+  method: "passkey",
+  standingByMethod: true,
+};
+const ACCESS_TOKEN = "urn:ietf:params:oauth:token-type:access_token";
+
+test("a member's session for the API is exchanged for a token that is that member at one hostname, and nowhere else", async () => {
+  const stack = stackOf();
+  const session = await signedIn(stack, owner);
+  const answer = await exchanged(stack, { subject_token: session.access_token, resource: GIT });
+  expect(answer).toMatchObject({
+    status: 200,
+    body: { token_type: "Bearer", issued_token_type: ACCESS_TOKEN },
+  });
+  // it ends with the session's own token, which lasts an hour
+  expect(answer.body.expires_in).toBeGreaterThan(3500);
+  expect(answer.body.expires_in).toBeLessThanOrEqual(3600);
+  const token = String(answer.body.access_token);
+  expect(await whoIs(stack, token, GIT)).toEqual({
+    principal: { actor: "user_owner", email: OWNER },
+    grant: session.grantId,
+    expiresAt: expect.any(Number),
+    member: true,
+    method: "passkey",
+  });
+  // for that hostname alone: no other hostname, and never the API or the MCP server
+  expect(await whoIs(stack, token, "https://guestbook.example.com")).toBeNull();
+  expect(await whoIs(stack, token, API)).toBeNull();
+  expect(await whoIs(stack, token, `${ISSUER}/mcp`)).toBeNull();
+  expect(await keyTokenIdentity(stack, token, API)).toBeNull();
+});
+
+test("the token stops at its next use when the session is ended, and when its person is no member", async () => {
+  const kv = new Map<string, string>();
+  const stack = stackOf({}, kv);
+  const session = await signedIn(stack, owner);
+  const { body } = await exchanged(stack, { subject_token: session.access_token, resource: GIT });
+  const token = String(body.access_token);
+  // the person is removed: the same store, a config that names another owner
+  const removed = stackOf({ ownerEmails: ["someone@elsewhere.test"] }, kv);
+  expect(await whoIs(removed, token, GIT)).toBeNull();
+  expect(await whoIs(stack, token, GIT)).toMatchObject({ member: true });
+  // the sign-in is ended, as /sessions and a sign-out end it
+  await oauthHelpers(stack).revokeGrant(session.grantId, owner.userId);
+  expect(await whoIs(stack, token, GIT)).toBeNull();
+  expect(
+    await exchanged(stack, { subject_token: session.access_token, resource: GIT }),
+  ).toMatchObject({ status: 400, body: { error: "invalid_request" } });
+});
+
+test("what is not a member's live session for the API gets no token", async () => {
+  const stack = stackOf();
+  const session = await signedIn(stack, owner);
+  const refusal = async (form: Record<string, string>) => {
+    const { status, body } = await exchanged(stack, form);
+    return [status, body.error];
+  };
+  // a made-up token, a refresh token, and a host token itself: nothing is exchanged twice
+  const host = await exchanged(stack, { subject_token: session.access_token, resource: GIT });
+  for (const subject_token of [
+    "user_owner:grant:secret",
+    session.refresh_token,
+    String(host.body.access_token).slice(0, 256),
+  ])
+    expect(await refusal({ subject_token, resource: GIT })).toEqual([400, "invalid_request"]);
+  // a resource that is no hostname of the mind: another site, the issuer's own, the API
+  for (const resource of ["https://git.elsewhere.test", ISSUER, API, "http://git.example.com"])
+    expect(await refusal({ subject_token: session.access_token, resource })).toEqual([
+      400,
+      "invalid_target",
+    ]);
+  expect(await refusal({ subject_token: session.access_token })).toEqual([400, "invalid_request"]);
+  expect(
+    await refusal({
+      subject_token: session.access_token,
+      resource: GIT,
+      subject_token_type: "urn:ietf:params:oauth:token-type:refresh_token",
+    }),
+  ).toEqual([400, "invalid_request"]);
+});
+
+test("a sign-in that names no way of signing in gets no token: a hostname stamps nobody without one", async () => {
+  const stack = stackOf();
+  // the old stack's grant from before 13 Nov 2026 (./oauth.ts `GrantProps.method`)
+  const session = await signedIn(stack, { userId: "user_owner", email: OWNER });
+  expect(await whoIs(stack, session.access_token, API)).toMatchObject({ member: true });
+  const answer = await exchanged(stack, { subject_token: session.access_token, resource: GIT });
+  expect(answer).toMatchObject({ status: 400, body: { error: "invalid_request" } });
+  expect(String(answer.body.error_description)).toContain("Sign in again");
+});
+
+test("any other grant type is the library's to answer", async () => {
+  const stack = stackOf();
+  const request = tokenRequest({ grant_type: "refresh_token", refresh_token: "x", client_id: "y" });
+  expect(await hostTokenResponse(stack, request)).toBeNull();
+});
+
+const ctx = { waitUntil() {}, passThroughOnException() {} } as unknown as ExecutionContext;
+const TokenAnswer = z.object({ access_token: z.string(), refresh_token: z.string() });
+
+/** A stack whose owner is `OWNER`, with `config` over that, the OAuth library's store in `kv`, and
+ *  a database in which nobody was added and nobody is blocked. */
+function stackOf(
+  config: Parameters<typeof configVars>[0] = {},
+  kv = new Map<string, string>(),
+): Env {
+  return {
+    ...configVars({ ownerEmails: [OWNER], ...config }),
+    OAUTH_KV: {
+      get: async (key: string, type?: unknown) => {
+        const kept = kv.get(key) ?? null;
+        const json = type === "json" || (type as { type?: string } | undefined)?.type === "json";
+        return kept && json ? JSON.parse(kept) : kept;
+      },
+      put: async (key: string, value: string) => void kv.set(key, value),
+      delete: async (key: string) => void kv.delete(key),
+      list: async ({ prefix = "" }: { prefix?: string } = {}) => ({
+        keys: [...kv.keys()].filter((key) => key.startsWith(prefix)).map((name) => ({ name })),
+        list_complete: true,
+      }),
+    },
+    DB: { prepare: () => ({ bind: () => ({ first: async () => null }) }) },
+    // the cast: a token's checks read these bindings and no other
+  } as unknown as Env;
+}
+
+/** A session for the API as the CLI holds one: a grant of `props`, and the tokens for its code. */
+async function signedIn(stack: Env, props: GrantProps) {
+  const helpers = oauthHelpers(stack);
+  const redirectUri = "http://127.0.0.1:7777/callback";
+  const { clientId } = await helpers.createClient({
+    redirectUris: [redirectUri],
+    tokenEndpointAuthMethod: "none",
+    grantTypes: ["authorization_code", "refresh_token"],
+    responseTypes: ["code"],
+  });
+  const verifier = generateRandomCodeVerifier();
+  const query = new URLSearchParams({
+    response_type: "code",
+    client_id: clientId,
+    redirect_uri: redirectUri,
+    resource: API,
+    scope: "iterate",
+    code_challenge: await calculatePKCECodeChallenge(verifier),
+    code_challenge_method: "S256",
+  });
+  const request = await helpers.parseAuthRequest(new Request(`${ISSUER}/oauth2/auth?${query}`));
+  const { redirectTo } = await helpers.completeAuthorization({
+    request,
+    userId: props.userId,
+    metadata: { clientName: "iterate CLI" },
+    scope: request.scope,
+    revokeExistingGrants: false,
+    props,
+  });
+  const code = new URL(redirectTo).searchParams.get("code")!;
+  const answer = await tokenEndpointResponse(
+    stack,
+    tokenRequest({
+      grant_type: "authorization_code",
+      code,
+      redirect_uri: redirectUri,
+      client_id: clientId,
+      code_verifier: verifier,
+      resource: API,
+    }),
+    ctx,
+  );
+  // the library's codes are `<userId>:<grantId>:<secret>`
+  return { ...TokenAnswer.parse(await answer.json()), grantId: code.split(":")[1]! };
+}
+
+/** The token endpoint's answer to a token exchange with `form` over the fields that every one has. */
+async function exchanged(stack: Env, form: Record<string, string>) {
+  const answer = await hostTokenResponse(
+    stack,
+    tokenRequest({
+      grant_type: TOKEN_EXCHANGE_GRANT,
+      subject_token_type: ACCESS_TOKEN,
+      ...form,
+    }),
+  );
+  return {
+    status: answer!.status,
+    body: z.record(z.string(), z.unknown()).parse(await answer!.json()),
+  };
+}
+
+const tokenRequest = (form: Record<string, string>) =>
+  new Request(`${ISSUER}/oauth2/token`, {
+    method: "POST",
+    headers: { "content-type": "application/x-www-form-urlencoded" },
+    body: new URLSearchParams(form),
+  });
A core/auth-worker/src/host-tokens.ts
@@ -0,0 +1,172 @@
+// host-tokens.ts — A TOKEN FOR ONE MIND HOSTNAME, FROM A MEMBER'S OWN SESSION. A program that
+// holds a member's sign-in for the mind's API (the CLI) may need to prove that member to one of
+// the mind's own hostnames, with a credential that opens nothing else: `iterate git-credential`
+// hands one to git for `git.<zone>` (core/lib/src/cli/git.ts).
+//
+//   POST /oauth2/token
+//     grant_type=urn:ietf:params:oauth:grant-type:token-exchange
+//     subject_token=<the session's access token for the API>
+//     subject_token_type=urn:ietf:params:oauth:token-type:access_token
+//     resource=https://<a hostname of the mind>
+//   → { access_token, issued_token_type, token_type: "Bearer", expires_in }
+//
+// This is OAuth token exchange (https://www.rfc-editor.org/rfc/rfc8693) with the resource of
+// https://www.rfc-editor.org/rfc/rfc8707. The OAuth library's own token exchange is off, and
+// refuses to change a token's resource; this file answers the grant type alone.
+//
+// THE TOKEN is signed by this Worker, as a key's token is (./key-tokens.ts), for that one
+// hostname's origin. It ends when its subject token ends, so it is never more than the session it
+// came from: an hour at most. There is no refresh token: the holder exchanges again.
+//
+// EVERY USE ASKS AGAIN (`hostTokenIdentity`): the session's grant must still be held, and its
+// person must still be a member. So a removed member stops the token at its next request, and a
+// sign-in that a member ended on /sessions, or a sign-out, stops it as it stops the session's own
+// token: at the next read of the grant's row, which KV may answer from its cache for up to a
+// minute at a place that read it just before.
+import type { TokenIdentity } from "iterate/workers";
+import { mindApiUrlOf } from "iterate/mind-api";
+import { SignInMethod } from "iterate/principal";
+import { jwtVerify, SignJWT } from "jose";
+import { z } from "zod";
+import { formOf, oauthError } from "./device/protocol.ts";
+import { configOf, type Env, issuerOf } from "./env.ts";
+import { isMember, isMemberByName } from "./members.ts";
+import { mindHostResourceOf, tokenIdentity } from "./oauth.ts";
+
+export 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 token with less than this left is no use to its holder: a clone outlives it. */
+const LEAST_SECONDS = 60;
+
+// The Worker's one signing key (./cookies.ts, ./key-tokens.ts). A host token's audience is a mind
+// hostname's origin, which is never a cookie's word or the API's URL.
+const signingKey = (env: Env) => new TextEncoder().encode(configOf(env).signingKey.exposeSecret());
+
+const Claims = z.object({
+  kind: z.literal("host-token"),
+  sub: z.string().startsWith("user_"),
+  /** The grant of the session that the token came from. */
+  grant: z.string().min(1),
+  email: z.string().min(1),
+  method: SignInMethod,
+  exp: z.number(),
+});
+
+const ExchangeForm = z.object({
+  grant_type: z.literal(TOKEN_EXCHANGE_GRANT),
+  subject_token: z.string().min(1).max(256),
+  subject_token_type: z.literal(ACCESS_TOKEN_TYPE),
+  requested_token_type: z.literal(ACCESS_TOKEN_TYPE).optional(),
+  resource: z.string().min(1),
+});
+
+/** The token endpoint's answer to a token exchange, or null for any other grant type. */
+export async function hostTokenResponse(env: Env, request: Request): Promise<Response | null> {
+  const fields = await formOf(request.clone());
+  if (fields.grant_type !== TOKEN_EXCHANGE_GRANT) return null;
+  const form = ExchangeForm.safeParse(fields);
+  if (!form.success)
+    return refused(
+      "invalid_request",
+      "A token exchange here takes subject_token (an access token of this mind's API), subject_token_type and resource (the origin of a hostname of this mind).",
+    );
+  const config = configOf(env);
+  const resource = mindHostResourceOf(config, form.data.resource);
+  if (!resource)
+    return refused("invalid_target", "The resource is not the origin of a hostname of this mind.");
+  // a member's own session for the API: never a key's token, and never a token for another resource
+  const subject = await tokenIdentity(
+    env,
+    form.data.subject_token,
+    mindApiUrlOf(config.controlPlaneHostname),
+  );
+  if (!subject?.member || !subject.principal.email)
+    return refused("invalid_request", "The subject token is not a member's live sign-in.");
+  // a hostname stamps a person by how they signed in (core/boundary-worker/src/stamp.ts)
+  if (!subject.method)
+    return refused(
+      "invalid_request",
+      "This sign-in is older than the hostnames' sign-in and names no way of signing in. Sign in again.",
+    );
+  const seconds = subject.expiresAt - Math.floor(Date.now() / 1000);
+  if (seconds < LEAST_SECONDS)
+    return refused("invalid_request", "The subject token is about to end. Renew it first.");
+  const token = await new SignJWT({
+    kind: "host-token",
+    grant: subject.grant,
+    email: subject.principal.email,
+    method: subject.method,
+  } satisfies Omit<z.infer<typeof Claims>, "sub" | "exp">)
+    .setProtectedHeader({ alg: "HS256" })
+    .setIssuer(issuerOf(env))
+    .setAudience(resource)
+    .setSubject(subject.principal.actor)
+    .setIssuedAt()
+    .setExpirationTime(subject.expiresAt)
+    .sign(signingKey(env));
+  console.info({
+    event: "auth.host-token-issued",
+    actor: subject.principal.actor,
+    grant: subject.grant,
+    resource,
+    seconds,
+  });
+  return Response.json(
+    {
+      access_token: token,
+      issued_token_type: ACCESS_TOKEN_TYPE,
+      token_type: "Bearer",
+      expires_in: seconds,
+    },
+    { headers: { "cache-control": "no-store" } },
+  );
+}
+
+/** Who a host token is, for the one mind hostname it was made for: a member, or nobody. The grant
+ *  and the membership are read on every use. */
+export async function hostTokenIdentity(
+  env: Env,
+  token: string,
+  resource: string,
+): Promise<TokenIdentity | null> {
+  if (token.split(".").length !== 3 || !mindHostResourceOf(configOf(env), resource)) return null;
+  const claims = await jwtVerify(token, signingKey(env), {
+    issuer: issuerOf(env),
+    audience: resource,
+    algorithms: ["HS256"],
+  }).then(
+    ({ payload }) => Claims.safeParse(payload).data,
+    () => undefined,
+  );
+  if (!claims) return null;
+  // As the session's own token is read (./oauth.ts `grantIsMembers`): a passkey's person is a
+  // member by any rule, and any other way's only by name.
+  const member =
+    claims.method === "passkey"
+      ? await isMember(env, claims.email)
+      : await isMemberByName(env, claims.email);
+  if (!member || !(await grantKept(env, claims.sub, claims.grant))) return null;
+  return {
+    principal: { actor: claims.sub, email: claims.email },
+    grant: claims.grant,
+    expiresAt: claims.exp,
+    member: true,
+    method: claims.method,
+  };
+}
+
+/** Whether the OAuth library still keeps a grant: it was not ended, and has not lapsed. READ BY
+ *  ITS OWN KEY, as the library reads it for a token of its own, and not from the list of a
+ *  person's grants: KV's list shows a new key late, so a token made right after a sign-in was
+ *  nobody's for some seconds (seen on a dev mind, 26 Nov 2026). The key's form is the library's
+ *  (`grant:<userId>:<grantId>`); ./host-tokens.test.ts fails when a new version changes it. */
+const grantKept = async (env: Env, userId: string, grantId: string) =>
+  (await env.OAUTH_KV.get(`grant:${userId}:${grantId}`)) !== null;
+
+// RFC 8693 §2.2.2: `invalid_request` for a subject token that is not taken, `invalid_target` for a
+// resource that is not.
+function refused(error: "invalid_request" | "invalid_target", description: string) {
+  console.info({ event: "auth.host-token-refused", error, description });
+  return oauthError(error, description);
+}
M core/auth-worker/src/http.ts
@@ -27,6 +27,7 @@
 import { firstPasskeyResponse } from "./enrolment.ts";
 import { configOf, dashOf, type Env, issuerOf } from "./env.ts";
 import { identityIntakeResponse, identityLogResponse } from "./identity.ts";
+import { hostTokenResponse } from "./host-tokens.ts";
 import { keyTokenResponse } from "./key-tokens.ts";
 import { keysPagesResponse } from "./keys-pages.ts";
 import { isMemberSession, membersResponse } from "./members.ts";
@@ -85,7 +86,9 @@
   if (pathname === AUTHORIZE_ENDPOINT) return authorizeResponse(env, request);
   if (pathname === TOKEN_ENDPOINT && request.method === "POST")
     return (
-      (await devicePollResponse(env, request, ctx)) || tokenEndpointResponse(env, request, ctx)
+      (await devicePollResponse(env, request, ctx)) ||
+      (await hostTokenResponse(env, request)) ||
+      tokenEndpointResponse(env, request, ctx)
     );
   if (pathname === "/.well-known/oauth-authorization-server" && request.method === "GET")
     return metadataResponse(env, request, ctx);
M core/auth-worker/src/who-is.ts
@@ -1,7 +1,9 @@
-// who-is.ts — WHO HOLDS A TOKEN, for one resource: a key's token, or an OAuth access token.
+// who-is.ts — WHO HOLDS A TOKEN, for one resource: a key's token, a token for one mind hostname
+// that a member's session was exchanged for, or an OAuth access token.
 // ./rpc.ts answers the boundary with it, and ./http.ts the members' API.
 import type { TokenIdentity } from "iterate/workers";
 import type { Env } from "./env.ts";
+import { hostTokenIdentity } from "./host-tokens.ts";
 import { keyTokenIdentity } from "./key-tokens.ts";
 import { tokenIdentity } from "./oauth.ts";
 
@@ -12,6 +14,8 @@
 ): Promise<TokenIdentity | null> {
   if (!token || !resource) return null;
   return (
-    (await keyTokenIdentity(env, token, resource)) ?? (await tokenIdentity(env, token, resource))
+    (await keyTokenIdentity(env, token, resource)) ??
+    (await hostTokenIdentity(env, token, resource)) ??
+    (await tokenIdentity(env, token, resource))
   );
 }
M core/boundary-worker/src/stamp.test.ts
@@ -60,6 +60,38 @@
   expect(stamped.forwarded.headers.get("x-itx-principal")).not.toBeNull();
 });
 
+test("a token as the password of Basic, as git sends one, is read as a bearer is, and never reaches the app", async () => {
+  const member: TokenIdentity = { ...signedIn, member: true, method: "passkey" };
+  const asked: unknown[] = [];
+  const auth = {
+    whoIs: async (token: string, resource: string) => {
+      asked.push([token, resource]);
+      return token === "t.o:k" ? member : null;
+    },
+  } as unknown as AuthService;
+  const basic = (pair: string) =>
+    stampedRequest(
+      new Request("https://git.example.com/repos/config/info/refs", {
+        headers: { authorization: `Basic ${btoa(pair)}` },
+      }),
+      { auth, route: null, config },
+    );
+  // the username says nothing, and the password is all that follows the first colon
+  const stamped = await basic("iterate:t.o:k");
+  expect(asked).toEqual([["t.o:k", "https://git.example.com"]]);
+  expect(stamped).toMatchObject({ caller: "member", email: "ada@elsewhere.example" });
+  expect(stamped.forwarded.headers.get("authorization")).toBeNull();
+  // a password that is no token of ours may be the app's own: it goes on as it came
+  const other = await basic("ada:secret");
+  expect(other).toMatchObject({ caller: "anonymous", email: null });
+  expect(other.forwarded.headers.get("authorization")).toBe(`Basic ${btoa("ada:secret")}`);
+  expect(other.forwarded.headers.get("x-itx-principal")).toBeNull();
+  // no password, and what is no pair, asks nobody
+  asked.length = 0;
+  for (const pair of ["ada:", "ada"]) expect(await basic(pair)).toMatchObject({ caller: "anonymous" });
+  expect(asked).toEqual([]);
+});
+
 test("a token that says no sign-in method is no person's: it stamps nobody", async () => {
   const { method: _none, ...noPerson } = signedIn;
   const auth = { whoIs: async () => noPerson } as unknown as AuthService;
M core/boundary-worker/src/stamp.ts
@@ -144,9 +144,12 @@
   const statement = request.headers.get(ITERATE_STATEMENT_HEADER);
   if (statement) return mindStamped(request, headers, statement, auth, config);
 
-  // An app's own script may send a bearer of its own beside the session cookie.
+  // An app's own script may send a bearer of its own beside the session cookie. GIT SENDS ITS
+  // CREDENTIAL AS BASIC, and before 2.46 knows no other way: a token as the password of Basic is
+  // read as a bearer is, whatever the username says (core/lib/src/cli/git.ts hands git one).
   const session = sessionTokenOf(request);
-  const byBearer = bearer ? await auth.whoIs(bearer, url.origin) : null;
+  const presented = bearer || basicPasswordOf(request.headers);
+  const byBearer = presented ? await auth.whoIs(presented, url.origin) : null;
   const tokenIdentity = byBearer || (session ? await auth.whoIs(session, url.origin) : null);
   // A PERSON'S TOKEN SAYS HOW THE PERSON SIGNED IN (iterate/workers `TokenIdentity.method`), and
   // the stamp carries it to the app (iterate/sdk `auth.person`). A token that says none is no
@@ -162,7 +165,7 @@
     request,
   });
   setAppCookies(headers, request.headers.get("cookie"));
-  // a bearer of ours never reaches the app; one that did not verify may be the app's own
+  // a token of ours never reaches the app; one that did not verify may be the app's own
   if (byBearer) headers.delete("authorization");
   if (identity && caller !== "anonymous") {
     const person = personOf(
@@ -296,6 +299,21 @@
  *  client that writes `bearer` sent the same credential. */
 export const bearerOf = (headers: Headers) =>
   headers.get("authorization")?.match(/^Bearer +(.+)$/i)?.[1];
+
+/** THE PASSWORD OF A REQUEST'S BASIC CREDENTIAL (RFC 7617: base64 of `user:password`, split at
+ *  the first colon), or undefined when the header is absent, of another scheme, or not such a
+ *  pair. */
+export function basicPasswordOf(headers: Headers): string | undefined {
+  const encoded = headers.get("authorization")?.match(/^Basic +([A-Za-z0-9+/]+=*)$/i)?.[1];
+  if (!encoded) return undefined;
+  try {
+    const pair = atob(encoded);
+    const colon = pair.indexOf(":");
+    return colon < 0 ? undefined : pair.slice(colon + 1) || undefined;
+  } catch {
+    return undefined;
+  }
+}
 
 function stamp(headers: Headers, identity: TokenIdentity) {
   headers.set(ITX_PRINCIPAL_HEADER, JSON.stringify(identity.principal));
M core/lib/src/cli/README.md
@@ -21,6 +21,7 @@
 npx iterate tunnel 5173 --name blog       # a local port on blog.<address>
 npx iterate provide ./whatsapp.ts         # a local file's functions as itx.whatsapp
 npx iterate chatgpt connect example.com   # a ChatGPT plan pays for the mind's Responses requests
+npx iterate git setup git.example.com     # plain git at the mind's git host, with this computer's sign-in
 npx iterate logout
 npx iterate fs read ./notes.md            # a file's bytes on stdout; also write, stat, lstat, ls, mkdir, mv, rm
 ```
@@ -57,6 +58,36 @@
 In a terminal with colors, the QR code is drawn as `qrencode -t ANSI` draws it; without colors (a
 pipe, `NO_COLOR`, `TERM=dumb`) as half blocks in the text color. `FORCE_COLOR=1` forces the colors.
 The link under the code works everywhere.
+
+## Git with the mind's sign-in
+
+`iterate git setup git.example.com` lets plain `git clone`, `git pull` and `git push` work at a
+host where a mind serves its repos. It signs this computer in to the mind when it is not signed in
+(the mind is the host without its first label; `--mind` names another), and writes two things
+into git's global config for that one host:
+
+- the credential helper `iterate git-credential`, with the inherited helpers cleared for this
+  host, so no keychain and no password window is asked for it;
+- the request header `X-Iterate-Git: 1`, which is public and proves nothing: it tells the host
+  that this git has the helper, so the host answers 401 and git asks it.
+
+The helper hands git a token for that one hostname, which the mind's issuer exchanges the CLI's
+session for (RFC 8693; `core/auth-worker/src/host-tokens.ts`). It opens nothing else of the mind,
+it ends within the hour, and the issuer asks at every use whether the session is still held and
+its person still a member. It is kept in `sessions.json` beside the session, under the host's
+origin, and git sends it as the password of Basic.
+
+With no sign-in, the helper signs in while git waits when a person is at the terminal. With
+nobody there (no terminal, `GIT_TERMINAL_PROMPT=0`, a coding agent) it prints the setup command
+and git stops without asking for a password. Run under `npx`, the setup names the helper as
+`npx --yes iterate git-credential`; otherwise by the Node and the file that ran it.
+
+In a sandbox of the mind, `iterate git setup <host>` signs nobody in. The helper there reaches
+the mind as the code of the sandbox's own context, mints a write token for the one repo that git
+names (`itx.cfArtifacts`, five minutes, kept nowhere) and hands it to git, and the host passes it
+on. A sandbox whose requests the mind filters has no such session, and so no git.
+
+Not tried on macOS or Windows.
 
 ## Deploy a mind
 
M core/lib/src/cli/cli.ts
@@ -4,10 +4,10 @@
 // profile, or the only one picks it, and `--mind <address>` overrides it for one command. Every
 // connection is the Node client's (../node.ts `connectMind`).
 import { spawnSync } from "node:child_process";
-import { existsSync, readFileSync, rmSync } from "node:fs";
+import { existsSync, readFileSync, realpathSync, rmSync } from "node:fs";
 import { readFile } from "node:fs/promises";
 import { text as streamText } from "node:stream/consumers";
-import { dirname, join } from "node:path";
+import { dirname, join, sep } from "node:path";
 import process from "node:process";
 import repl from "node:repl";
 import { setTimeout as sleep } from "node:timers/promises";
@@ -15,8 +15,20 @@
 import { RpcTarget } from "capnweb";
 import { createCli, os, yamlTableConsoleLogger } from "trpc-cli";
 import { z } from "zod";
-import { addressOf, connectMind, discoveredMind, openForSignIn, signInToMind } from "../node.ts";
-import { mindApiUrlOf, mindMcpUrlOf, mindProvideConnectResourceOf } from "../mind-api.ts";
+import {
+  addressOf,
+  connectMind,
+  discoveredMind,
+  mindToken,
+  openForSignIn,
+  signInToMind,
+} from "../node.ts";
+import {
+  mindApiUrlOf,
+  mindMcpUrlOf,
+  mindProvideConnectResourceOf,
+  ownSandboxOf,
+} from "../mind-api.ts";
 import { MCP_CLIENTS, type McpClient, mcpAddArgvOf } from "./mcp-clients.ts";
 import { connectChatgpt } from "./chatgpt.ts";
 import { isCodingAgent } from "./coding-agent.ts";
@@ -31,6 +43,15 @@
   writeKeptSignIn,
 } from "./cloudflare-access.ts";
 import { deployMind } from "./deploy.ts";
+import {
+  gitCredential,
+  type GitCredentialIo,
+  gitHostOf,
+  isHostOfMind,
+  mindOfGitHost,
+  personIsThere,
+  writeGitConfig,
+} from "./git.ts";
 import { IDENTITIES, type IdentityIo, postIdentity, shownIdentity } from "./identity.ts";
 import { recoverOwner } from "./recover.ts";
 import { runFs } from "./fs.ts";
@@ -200,6 +221,72 @@
   };
 };
 
+/** How git's credential helper reaches the CLI's sign-in to the mind at `address` (./git.ts). */
+const gitCredentialIo = (address: string): GitCredentialIo => ({
+  say: (line) => console.error(line),
+  async session({ leastLeftMs, signIn, anew }) {
+    const resource = mindApiUrlOf(address);
+    if (anew) removeSession(resource);
+    const token = await mindToken({
+      address,
+      resource,
+      leastLeftMs,
+      signIn: signIn ? {} : false,
+    });
+    const stored = readSession(resource);
+    if (stored?.token === token) return stored;
+    // a token from the environment (ITERATE_MIND_TOKEN): the issuer is found by discovery
+    const mind = await discoveredMind(address);
+    return { issuer: mind.issuer, tokenEndpoint: mind.endpoints.token, clientId: "", token };
+  },
+  // in a sandbox of this mind: the mind's own token for the repo, by the sandbox's own session
+  ...(ownSandboxOf(process.env, address) && {
+    async repoToken(repo, host) {
+      using connection = await connectMind({ address });
+      const mindUrl = await connection.itx.url();
+      if (!isHostOfMind(host, mindUrl))
+        throw new Error(`${host} is no host of this mind (${mindUrl}), so it gets no token`);
+      const token = await connection.itx.cfArtifacts.get(repo).createToken("write", 300);
+      return token.plaintext;
+    },
+  }),
+});
+
+/** THE COMMAND THAT GIT RUNS AS ITS HELPER for a host of the mind at `address`: this same CLI,
+ *  by the Node and the file that run now. A CLI that npx fetched lives in npx's cache, which npm
+ *  may clear, so that one is named as `npx` finds it again. */
+const gitHelperCommandOf = (address: string) => {
+  const script = realpathSync(process.argv[1]!);
+  const cli = script.includes(`${sep}_npx${sep}`)
+    ? ["npx", "--yes", "iterate"]
+    : [process.execPath, script];
+  return shellCommand([...cli, "git-credential", "--mind", address]);
+};
+
+/** `iterate git-credential --mind <address> <operation>`, as git runs it (./git.ts): its answer
+ *  goes to stdout as it is, with no logger between. */
+const runGitCredential = async (args: string[]): Promise<number> => {
+  const at = args.indexOf("--mind");
+  const address = at >= 0 ? args[at + 1] : undefined;
+  const operation = args.filter((_arg, index) => at < 0 || (index !== at && index !== at + 1))[0];
+  if (!address || !operation) {
+    console.error(
+      "iterate git-credential is git's own helper: `iterate git setup <host>` tells git how to run it.",
+    );
+    return 1;
+  }
+  process.stdout.write(
+    await gitCredential({
+      operation,
+      asked: await streamText(process.stdin),
+      address,
+      interactive: personIsThere(process.env, Boolean(process.stderr.isTTY)),
+      io: gitCredentialIo(address),
+    }),
+  );
+  return 0;
+};
+
 const mindOption = z
   .string()
   .optional()
@@ -532,6 +619,65 @@
         };
       }),
   },
+  git: {
+    setup: os
+      .input(
+        z.object({
+          host: z
+            .string()
+            .meta({ positional: true })
+            .describe("The host that serves the mind's repos, e.g. git.example.com"),
+          mind: z
+            .string()
+            .optional()
+            .describe("The mind's address (default: the host without its first label)"),
+        }),
+      )
+      .meta({
+        description:
+          "Let plain git clone, pull and push at a mind's git host with this computer's sign-in: sign in if needed, and set git's credential helper for that one host",
+      })
+      .handler(async ({ input }) => {
+        const host = gitHostOf(input.host);
+        // in a sandbox of the mind there is nobody to sign in: the helper asks the mind itself
+        const told = process.env.ITERATE_MIND?.trim().toLowerCase() || "";
+        if (!input.mind && ownSandboxOf(process.env, told)) {
+          using connection = await connectMind({ address: told });
+          const mindUrl = await connection.itx.url();
+          if (!isHostOfMind(host, mindUrl))
+            throw new Error(
+              `${host} is no host of this sandbox's mind (${mindUrl}): a sandbox's git is set up for its own mind's host alone.`,
+            );
+          writeGitConfig({ host, helper: gitHelperCommandOf(told), namesRepo: true });
+          return {
+            message: `Git is set up for https://${host} in this sandbox, with no sign-in: it asks ${told} for each repo's token.`,
+          };
+        }
+        const mind = await discoveredMind(addressOf(input.mind || mindOfGitHost(host)));
+        const signedIn =
+          readSession(mindApiUrlOf(mind.address)) || process.env.ITERATE_MIND_TOKEN?.trim()
+            ? undefined
+            : (await login({ address: mind.address })).message;
+        writeGitConfig({ host, helper: gitHelperCommandOf(mind.address) });
+        // one token now, so a host that is not this mind's, or a sign-in that cannot be used for
+        // it, is said here and not at the first clone
+        const said: string[] = [];
+        const credential = await gitCredential({
+          operation: "get",
+          asked: `protocol=https\nhost=${host}\n\n`,
+          address: mind.address,
+          interactive: true,
+          io: { ...gitCredentialIo(mind.address), say: (line) => said.push(line) },
+        });
+        if (!credential.startsWith("username="))
+          throw new Error(
+            `Git's config is written, but no token came for ${host}:\n${said.join("\n")}`,
+          );
+        return {
+          message: `${signedIn ? `${signedIn}. ` : ""}Git is set up for https://${host}. Run your git command again.`,
+        };
+      }),
+  },
   login: os
     .input(
       z.object({
@@ -914,6 +1060,11 @@
   // the machine's own files, no sign-in and no flags of ours (fs.ts); a sandbox runs the same file alone
   if (process.argv[2] === "fs") {
     process.exitCode = await runFs(process.argv.slice(3), process);
+    return;
+  }
+  // git's own helper (git.ts): git reads its stdout, so no flag of ours and no logger
+  if (process.argv[2] === "git-credential") {
+    process.exitCode = await runGitCredential(process.argv.slice(3));
     return;
   }
   configFlagOverride = consumeCliStringFlag("--config");
A core/lib/src/cli/git.test.ts
@@ -0,0 +1,264 @@
+// Git's credential helper and the config that `iterate git setup` writes (./git.ts), against a
+// stand-in for the issuer's token endpoint and a sign-in folder of the test's own.
+import { mkdtempDisposableSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { expect, test as base, vi } from "vitest";
+
+// the CLI's folder is read once, when ./config.ts is loaded: so before the import
+const config = mkdtempDisposableSync(join(tmpdir(), "iterate-test-"));
+vi.stubEnv("XDG_CONFIG_HOME", config.path);
+const { CONFIG_DIR, readSession, writeSession } = await import("./config.ts");
+const {
+  credentialInputOf,
+  gitConfigOf,
+  gitCredential,
+  gitHostOf,
+  HOST_TOKEN_LEAST_LEFT_MS,
+  isHostOfMind,
+  mindOfGitHost,
+  personIsThere,
+  repoOfGitPath,
+} = await import("./git.ts");
+/** `test`, with the folder removed after the file's last test. */
+const test = base.extend<{ folderRemoved: void }>({
+  folderRemoved: [
+    // oxlint-disable-next-line no-empty-pattern -- vitest reads the fixture's needs from this pattern
+    async ({}, use) => {
+      await use();
+      config.remove();
+    },
+    { scope: "file", auto: true },
+  ],
+});
+
+const ADDRESS = "iterate.example.com";
+const ISSUER = `https://${ADDRESS}`;
+const TOKEN_ENDPOINT = `${ISSUER}/oauth2/token`;
+const session = { issuer: ISSUER, tokenEndpoint: TOKEN_ENDPOINT, clientId: "cli", token: "api-1" };
+const ASKED = "protocol=https\nhost=git.example.com\nwwwauth[]=Basic realm=x\n\n";
+
+test("the sign-ins of this file are in its own folder, not the person's", () => {
+  expect(CONFIG_DIR).toBe(join(config.path, "iterate"));
+});
+
+test("setup writes the helper for the one host, with the inherited helpers cleared, and the marker", () => {
+  expect(gitConfigOf({ host: "git.example.com", helper: "iterate git-credential --mind m" })).toEqual(
+    [
+      ["--replace-all", "credential.https://git.example.com.helper", ""],
+      ["--add", "credential.https://git.example.com.helper", "!iterate git-credential --mind m"],
+      ["--replace-all", "credential.https://git.example.com.useHttpPath", "false"],
+      ["--replace-all", "http.https://git.example.com/.extraHeader", "X-Iterate-Git: 1"],
+    ],
+  );
+  // in a sandbox git names the repo to the helper
+  expect(gitConfigOf({ host: "git.example.com", helper: "h", namesRepo: true })[2]).toEqual([
+    "--replace-all",
+    "credential.https://git.example.com.useHttpPath",
+    "true",
+  ]);
+});
+
+test("in a sandbox of the mind, get answers the mind's own token for the repo that git names, and keeps nothing", async () => {
+  await run(issuerOf(), "erase");
+  const issuer = issuerOf();
+  const minted: string[] = [];
+  const io = {
+    ...issuer.io,
+    repoToken: async (repo: string, host: string) => {
+      expect(host).toBe("git.example.com");
+      minted.push(repo);
+      if (repo === "/repos/away") throw new Error("no such repo");
+      return `token-of-${repo}`;
+    },
+  };
+  const get = (path: string) =>
+    gitCredential({
+      operation: "get",
+      asked: `protocol=https\nhost=git.example.com\n${path}\n`,
+      address: ADDRESS,
+      interactive: false,
+      io,
+    });
+  expect(await get("path=repos/config.git")).toBe(
+    "username=iterate\npassword=token-of-/repos/config\n",
+  );
+  expect(await get("path=repos/away")).toBe("quit=1\n");
+  // git named no repo: the setup of a sandbox has it name one
+  expect(await get("")).toBe("quit=1\n");
+  expect(minted).toEqual(["/repos/config", "/repos/away"]);
+  expect(issuer.said).toEqual([
+    "iterate: this sandbox got no token for /repos/away from iterate.example.com: no such repo",
+    "iterate: git named no repo of git.example.com to its helper. Run this, then the same git command again:\n  npx iterate git setup git.example.com",
+  ]);
+  // no session was asked for, no exchange was made, and nothing is kept
+  expect([issuer.sessions, issuer.asked, readSession("https://git.example.com")]).toEqual([
+    [],
+    [],
+    null,
+  ]);
+});
+
+test("a git host is a hostname, typed bare or as a remote's address, and its mind is the host without its first label", () => {
+  expect([
+    gitHostOf("git.example.com"),
+    gitHostOf("https://Git.Example.com/repos/config"),
+    mindOfGitHost("git.example.com"),
+  ]).toEqual(["git.example.com", "git.example.com", "example.com"]);
+  for (const typed of ["localhost", "http://git.example.com", "git.example.com:8443"])
+    expect(() => gitHostOf(typed)).toThrow("no https host");
+});
+
+test("a host of the mind is its apex or a name under it, and nothing that only looks like it", () => {
+  const mind = "https://example.com";
+  expect(
+    ["git.example.com", "example.com", "GIT.Example.com", "git.example.com.evil.test", "evilexample.com", "git.other.test"].map(
+      (host) => isHostOfMind(host, mind),
+    ),
+  ).toEqual([true, true, true, false, false, false]);
+  expect(isHostOfMind("git.example.com", "not an address")).toBe(false);
+});
+
+test("the path that git names is a repo of the mind, or none", () => {
+  expect(
+    ["repos/config", "/repos/config.git/", "repos/github.com/iterate/core", "config", "repos/a b", undefined].map(
+      repoOfGitPath,
+    ),
+  ).toEqual(["/repos/config", "/repos/config", "/repos/github.com/iterate/core", null, null, null]);
+});
+
+test("what git writes is read line by line up to the empty line", () => {
+  expect(credentialInputOf("protocol=https\r\nhost=git.example.com\npath=a=b\n\n")).toEqual({
+    protocol: "https",
+    host: "git.example.com",
+    path: "a=b",
+  });
+});
+
+test("get exchanges the session for the host's token, keeps it, and answers it as a Basic pair", async () => {
+  const issuer = issuerOf();
+  const stdout = await get(issuer);
+  expect(stdout).toBe("username=iterate\npassword=host-1\n");
+  expect(issuer.asked).toEqual([
+    {
+      url: TOKEN_ENDPOINT,
+      grant_type: "urn:ietf:params:oauth:grant-type:token-exchange",
+      subject_token: "api-1",
+      subject_token_type: "urn:ietf:params:oauth:token-type:access_token",
+      resource: "https://git.example.com",
+    },
+  ]);
+  // the session was asked for with enough left for a clone
+  expect(issuer.sessions).toEqual([{ leastLeftMs: 2 * HOST_TOKEN_LEAST_LEFT_MS, signIn: false }]);
+  // a second git command within the token's life asks nobody
+  expect(await get(issuer)).toBe(stdout);
+  expect(issuer.asked).toHaveLength(1);
+  // erase, which git calls after the host refused the token, forgets it and no more
+  expect(await run(issuer, "erase")).toBe("");
+  expect(readSession("https://git.example.com")).toBeNull();
+  expect(await get(issuer)).toBe("username=iterate\npassword=host-2\n");
+});
+
+test("a kept token that is about to end is exchanged again", async () => {
+  writeSession("https://git.example.com", {
+    ...session,
+    token: "old",
+    expiresAt: new Date(Date.now() + HOST_TOKEN_LEAST_LEFT_MS - 1000).toISOString(),
+  });
+  expect(await get(issuerOf())).toBe("username=iterate\npassword=host-1\n");
+});
+
+test("with no sign-in and nobody there, get says what to run and tells git to stop", async () => {
+  await run(issuerOf(), "erase");
+  const issuer = issuerOf({ session: new Error("Not signed in to iterate.example.com.") });
+  expect(await get(issuer)).toBe("quit=1\n");
+  expect(issuer.said).toEqual([
+    "iterate: not signed in to iterate.example.com (Not signed in to iterate.example.com.). Run this, then the same git command again:\n  npx iterate git setup git.example.com",
+  ]);
+  expect(issuer.asked).toEqual([]);
+});
+
+test("a session that the issuer refuses for the host stops git with the issuer's words", async () => {
+  const issuer = issuerOf({
+    refusal: { error: "invalid_request", error_description: "The subject token is not live." },
+  });
+  expect(await get(issuer)).toBe("quit=1\n");
+  expect(issuer.said[0]).toContain(
+    "iterate.example.com gave no token for git.example.com (invalid_request: The subject token is not live.)",
+  );
+  expect(readSession("https://git.example.com")).toBeNull();
+});
+
+test("with a person there, a session that the issuer refuses is forgotten and signed in again, once", async () => {
+  await run(issuerOf(), "erase");
+  const issuer = issuerOf();
+  let refusals = 1;
+  const io = {
+    ...issuer.io,
+    fetcher: (async (url: string, init: RequestInit) =>
+      refusals-- > 0
+        ? Response.json({ error: "invalid_request" }, { status: 400 })
+        : issuer.io.fetcher(url, init)) as typeof fetch,
+  };
+  const stdout = await gitCredential({
+    operation: "get",
+    asked: ASKED,
+    address: ADDRESS,
+    interactive: true,
+    io,
+  });
+  expect(stdout).toBe("username=iterate\npassword=host-1\n");
+  expect(issuer.sessions).toEqual([
+    { leastLeftMs: 2 * HOST_TOKEN_LEAST_LEFT_MS, signIn: true },
+    { leastLeftMs: 2 * HOST_TOKEN_LEAST_LEFT_MS, signIn: true, anew: true },
+  ]);
+  expect(issuer.said).toEqual(["iterate: your sign-in to iterate.example.com has ended."]);
+});
+
+test("store, an unknown word and a request that is not https answer nothing and ask nobody", async () => {
+  const issuer = issuerOf();
+  expect(await run(issuer, "store")).toBe("");
+  expect(await run(issuer, "capability")).toBe("");
+  expect(await run(issuer, "get", "protocol=http\nhost=git.example.com\n\n")).toBe("");
+  expect(issuer.asked).toEqual([]);
+});
+
+test("a person is there with a terminal on stderr, prompts on, and no coding agent", () => {
+  expect([
+    personIsThere({}, true),
+    personIsThere({}, false),
+    personIsThere({ GIT_TERMINAL_PROMPT: "0" }, true),
+    personIsThere({ AGENT: "1" }, true),
+  ]).toEqual([true, false, false, false]);
+});
+
+/** A stand-in for the CLI's sign-in and the issuer's token endpoint: each exchange answers the
+ *  next `host-<n>` for an hour, or `refusal`. */
+function issuerOf(options: { session?: Error; refusal?: Record<string, string> } = {}) {
+  const asked: Record<string, string>[] = [];
+  const sessions: unknown[] = [];
+  const said: string[] = [];
+  return {
+    asked,
+    sessions,
+    said,
+    io: {
+      say: (line: string) => void said.push(line),
+      async session(input: { leastLeftMs: number; signIn: boolean; anew?: boolean }) {
+        sessions.push(input);
+        if (options.session) throw options.session;
+        return session;
+      },
+      fetcher: (async (url: string, init: RequestInit) => {
+        asked.push({ url, ...Object.fromEntries(new URLSearchParams(String(init.body))) });
+        return options.refusal
+          ? Response.json(options.refusal, { status: 400 })
+          : Response.json({ access_token: `host-${asked.length}`, expires_in: 3600 });
+      }) as typeof fetch,
+    },
+  };
+}
+
+const run = (issuer: ReturnType<typeof issuerOf>, operation: string, asked = ASKED) =>
+  gitCredential({ operation, asked, address: ADDRESS, interactive: false, io: issuer.io });
+const get = (issuer: ReturnType<typeof issuerOf>) => run(issuer, "get");
A core/lib/src/cli/git.ts
@@ -0,0 +1,274 @@
+// 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`;
M core/lib/src/node.ts
@@ -123,7 +123,8 @@
 
 /** A LIVE BEARER FOR `resource` of the mind at `address` (as it is: `addressOf` reads what a
  *  person typed): `token`, else ITERATE_MIND_TOKEN,
- *  else the stored session, refreshed when it ends within the minute. With none, or one the issuer
+ *  else the stored session, refreshed when it ends within the minute, or within `leastLeftMs`
+ *  for a caller that needs more of it (cli/git.ts). With none, or one the issuer
  *  refuses to refresh, a sign-in when `signIn` allows it; else an error that says how to sign in. */
 export async function mindToken(input: {
   address: string;
@@ -131,19 +132,21 @@
   token?: string;
   /** false: never sign in, fail instead (a script, the smoke check) */
   signIn?: SignInOptions | false;
+  leastLeftMs?: number;
 }): Promise<string> {
   const fixed = input.token || process.env.ITERATE_MIND_TOKEN?.trim();
   if (fixed) return fixed;
   const { resource } = input;
+  const endsSoon = (session: StoredSession) => endsWithin(session, input.leastLeftMs ?? 60_000);
   const stored = readSession(resource);
-  if (stored && !endsWithinTheMinute(stored)) return stored.token;
+  if (stored && !endsSoon(stored)) return stored.token;
   if (stored?.refreshToken) {
     // ONE AT A TIME (cli/config.ts `withSessionsLock`), and the file is read again inside: a
     // process that waited finds the sign-in that the first one renewed, or finds none that can
     // be renewed (null: the sign-in below).
     const token = await withSessionsLock(async () => {
       const now = readSession(resource);
-      if (now && !endsWithinTheMinute(now)) return now.token;
+      if (now && !endsSoon(now)) return now.token;
       if (!now?.refreshToken) return null;
       try {
         const refreshed = await refreshOAuthSession({ resource, session: now });
@@ -174,10 +177,10 @@
   return (await signInToMind(mind, resource, input.signIn)).token;
 }
 
-const endsWithinTheMinute = (session: StoredSession) => {
+const endsWithin = (session: StoredSession, ms: number) => {
   if (!session.expiresAt) return false;
   const expiresAt = Date.parse(session.expiresAt);
-  return Number.isFinite(expiresAt) && expiresAt <= Date.now() + 60_000;
+  return Number.isFinite(expiresAt) && expiresAt <= Date.now() + ms;
 };
 
 /** The mind's root context, as capnweb hands it: pipelined, and disposable. */