import assert from "node:assert/strict"; import { execFileSync, spawn } from "node:child_process"; import fs from "node:fs"; import http from "node:http"; import net from "node:net"; import os from "node:os"; import path from "node:path"; import readline from "node:readline"; import { test } from "node:test"; const CLI = new URL("../refs.mjs", import.meta.url).pathname; const TOKEN = "refs_agent_0123456789abcdef"; function git(cwd: string, env: NodeJS.ProcessEnv, args: string[], input?: string): string { return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", env, input, stdio: ["pipe", "pipe", "ignore"] }); } test("the MCP proxy hands refs_take's token to git's credential helper, never to the model, and takes it back on release", async (t) => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "refs-cli-")); const clone = path.join(home, "clone"); const calls: Record[] = []; const server = http.createServer(async (request, response) => { let body = ""; for await (const chunk of request) body += chunk; if (!body) return response.writeHead(204).end(); const message = JSON.parse(body); calls.push(message.params.arguments); const refs = message.params.name === "refs_take" ? { remote, token: TOKEN } : { remote }; const text = message.params.arguments.credentials === "helper" ? "git in this clone already authenticates as this session." : `Bearer ${TOKEN}`; response.writeHead(200, { "content-type": "application/json", "mcp-session-id": "c.claude-code" }).end(JSON.stringify({ jsonrpc: "2.0", id: message.id, result: { content: [{ type: "text", text }], _meta: { refs } } })); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve)); const origin = `http://127.0.0.1:${(server.address() as net.AddressInfo).port}`; const remote = `${origin}/refs/demo.git`; const daemon = net.createServer((socket) => socket.end(JSON.stringify({ connected: true }) + "\n")).listen(path.join(home, "daemon.sock")); t.after(() => (server.close(), daemon.close(), fs.rmSync(home, { recursive: true, force: true }))); fs.mkdirSync(path.join(home, "bin")); fs.writeFileSync(path.join(home, "bin", "refs"), `#!/bin/sh\nexec "${process.execPath}" "${CLI}" "$@"\n`, { mode: 0o755 }); fs.writeFileSync(path.join(home, "credentials.json"), JSON.stringify({ origin, accessToken: "oauth", expiresAt: Date.now() / 1000 + 3600 })); const env = { ...process.env, REFS_HOME: home, GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1" }; fs.mkdirSync(clone); git(clone, env, ["init", "-q"]); git(clone, env, ["remote", "add", "origin", remote]); git(clone, env, ["config", `http.${remote}.extraHeader`, `Authorization: Bearer refs_agent_stale`]); const proxy = spawn(process.execPath, [CLI, "mcp"], { cwd: clone, env, stdio: ["pipe", "pipe", "inherit"] }); t.after(() => proxy.kill()); const answers = readline.createInterface({ input: proxy.stdout! })[Symbol.asyncIterator](); const call = async (id: number, name: string, args: Record) => { proxy.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } }) + "\n"); return (await answers.next()).value as string; }; const fill = () => git(clone, env, ["credential", "fill"], `url=${remote}\n\n`); const taken = await call(1, "refs_take", { task: 7 }); assert.doesNotMatch(taken, /refs_agent_/); assert.equal(calls[0].credentials, "helper"); assert.equal((fs.statSync(path.join(home, "git-tokens.json")).mode & 0o777).toString(8), "600"); assert.throws(() => git(clone, env, ["config", "--get-all", `http.${remote}.extraHeader`])); assert.match(fill(), new RegExp(`username=x-token\npassword=${TOKEN}\n`)); const released = await call(2, "refs_release", {}); assert.doesNotMatch(released, /"refs"/); assert.throws(() => git(clone, env, ["config", "--get-all", `credential.${remote}.helper`])); assert.deepEqual(JSON.parse(fs.readFileSync(path.join(home, "git-tokens.json"), "utf8")), {}); }); test("outside a refs clone, the MCP server answers on its own, offers no tools and never calls refs", async (t) => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "refs-cli-")); t.after(() => fs.rmSync(home, { recursive: true, force: true })); const project = path.join(home, "project"); fs.mkdirSync(project); const env = { ...process.env, REFS_HOME: home, GIT_CONFIG_NOSYSTEM: "1" }; git(project, env, ["init", "-q"]); git(project, env, ["remote", "add", "origin", "https://github.com/someone/project.git"]); for (const credentials of [null, { origin: "http://127.0.0.1:9", accessToken: "expired", expiresAt: 0 }]) { if (credentials) fs.writeFileSync(path.join(home, "credentials.json"), JSON.stringify(credentials)); const messages = [ { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } }, { jsonrpc: "2.0", method: "notifications/initialized" }, { jsonrpc: "2.0", id: 2, method: "tools/list" }, { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "refs_events", arguments: { event: "UserPromptSubmit" } } }, ]; const output = execFileSync(process.execPath, [CLI, "mcp"], { cwd: project, env, input: messages.map((message) => JSON.stringify(message)).join("\n") + "\n", encoding: "utf8", timeout: 5000 }); const answers = output.trim().split("\n").map((line) => JSON.parse(line)); assert.deepEqual( answers.map((answer) => [answer.id, answer.result]), [ [1, { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "refs", version: "0.1.0" } }], [2, { tools: [] }], [3, { content: [] }], ], ); assert.equal(fs.existsSync(path.join(home, "daemon.log")), false); } }); test("with no session token, the credential helper answers git with your own sign-in, but only when it has the git scope", (t) => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "refs-cli-")); t.after(() => fs.rmSync(home, { recursive: true, force: true })); const origin = "https://refs.example"; const helper = (url: string) => execFileSync(process.execPath, [CLI, "credential", "get"], { env: { ...process.env, REFS_HOME: home }, input: `protocol=https\nhost=${new URL(url).host}\npath=${new URL(url).pathname.slice(1)}\n\n`, encoding: "utf8" }); const signIn = (scope?: string) => fs.writeFileSync(path.join(home, "credentials.json"), JSON.stringify({ origin, scope, accessToken: "u:g:secret", expiresAt: Date.now() / 1000 + 3600 })); signIn("agents git"); assert.equal(helper(`${origin}/refs/demo.git`), "username=x-token\npassword=u:g:secret\n"); assert.equal(helper("https://github.com/someone/project.git"), ""); signIn("agents"); assert.equal(helper(`${origin}/refs/demo.git`), ""); }); test("the credential helper gives a session token only to git that the agent runs, and your sign-in to everyone else", (t) => { const home = fs.mkdtempSync(path.join(os.tmpdir(), "refs-cli-")); const other = spawn("sleep", ["30"]); t.after(() => (other.kill(), fs.rmSync(home, { recursive: true, force: true }))); const origin = "https://refs.example"; const remote = `${origin}/refs/demo.git`; const helper = () => execFileSync(process.execPath, [CLI, "credential", "get"], { env: { ...process.env, REFS_HOME: home }, input: `protocol=https\nhost=refs.example\npath=refs/demo.git\n\n`, encoding: "utf8" }); const hold = (owners: Record) => fs.writeFileSync(path.join(home, "git-tokens.json"), JSON.stringify({ [remote]: owners })); fs.writeFileSync(path.join(home, "credentials.json"), JSON.stringify({ origin, scope: "agents git", accessToken: "u:g:secret", expiresAt: Date.now() / 1000 + 3600 })); hold({ [other.pid!]: TOKEN }); assert.equal(helper(), "username=x-token\npassword=u:g:secret\n"); hold({ [other.pid!]: "refs_agent_other", [process.pid]: TOKEN }); assert.equal(helper(), `username=x-token\npassword=${TOKEN}\n`); hold({ 999999: TOKEN }); assert.equal(helper(), "username=x-token\npassword=u:g:secret\n"); });