131 lines · 7.9 KBRaw
| 1 | import assert from "node:assert/strict"; |
| 2 | import { execFileSync, spawn } from "node:child_process"; |
| 3 | import fs from "node:fs"; |
| 4 | import http from "node:http"; |
| 5 | import net from "node:net"; |
| 6 | import os from "node:os"; |
| 7 | import path from "node:path"; |
| 8 | import readline from "node:readline"; |
| 9 | import { test } from "node:test"; |
| 10 | |
| 11 | const CLI = new URL("../refs.mjs", import.meta.url).pathname; |
| 12 | const TOKEN = "refs_agent_0123456789abcdef"; |
| 13 | |
| 14 | function git(cwd: string, env: NodeJS.ProcessEnv, args: string[], input?: string): string { |
| 15 | return execFileSync("git", ["-C", cwd, ...args], { encoding: "utf8", env, input, stdio: ["pipe", "pipe", "ignore"] }); |
| 16 | } |
| 17 | |
| 18 | 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) => { |
| 19 | const home = fs.mkdtempSync(path.join(os.tmpdir(), "refs-cli-")); |
| 20 | const clone = path.join(home, "clone"); |
| 21 | const calls: Record<string, unknown>[] = []; |
| 22 | const server = http.createServer(async (request, response) => { |
| 23 | let body = ""; |
| 24 | for await (const chunk of request) body += chunk; |
| 25 | if (!body) return response.writeHead(204).end(); |
| 26 | const message = JSON.parse(body); |
| 27 | calls.push(message.params.arguments); |
| 28 | const refs = message.params.name === "refs_take" ? { remote, token: TOKEN } : { remote }; |
| 29 | const text = message.params.arguments.credentials === "helper" ? "git in this clone already authenticates as this session." : `Bearer ${TOKEN}`; |
| 30 | 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 } } })); |
| 31 | }); |
| 32 | await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve)); |
| 33 | const origin = `http://127.0.0.1:${(server.address() as net.AddressInfo).port}`; |
| 34 | const remote = `${origin}/refs/demo.git`; |
| 35 | const daemon = net.createServer((socket) => socket.end(JSON.stringify({ connected: true }) + "\n")).listen(path.join(home, "daemon.sock")); |
| 36 | t.after(() => (server.close(), daemon.close(), fs.rmSync(home, { recursive: true, force: true }))); |
| 37 | |
| 38 | fs.mkdirSync(path.join(home, "bin")); |
| 39 | fs.writeFileSync(path.join(home, "bin", "refs"), `#!/bin/sh\nexec "${process.execPath}" "${CLI}" "$@"\n`, { mode: 0o755 }); |
| 40 | fs.writeFileSync(path.join(home, "credentials.json"), JSON.stringify({ origin, accessToken: "oauth", expiresAt: Date.now() / 1000 + 3600 })); |
| 41 | const env = { ...process.env, REFS_HOME: home, GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1" }; |
| 42 | fs.mkdirSync(clone); |
| 43 | git(clone, env, ["init", "-q"]); |
| 44 | git(clone, env, ["remote", "add", "origin", remote]); |
| 45 | git(clone, env, ["config", `http.${remote}.extraHeader`, `Authorization: Bearer refs_agent_stale`]); |
| 46 | |
| 47 | const proxy = spawn(process.execPath, [CLI, "mcp"], { cwd: clone, env, stdio: ["pipe", "pipe", "inherit"] }); |
| 48 | t.after(() => proxy.kill()); |
| 49 | const answers = readline.createInterface({ input: proxy.stdout! })[Symbol.asyncIterator](); |
| 50 | const call = async (id: number, name: string, args: Record<string, unknown>) => { |
| 51 | proxy.stdin!.write(JSON.stringify({ jsonrpc: "2.0", id, method: "tools/call", params: { name, arguments: args } }) + "\n"); |
| 52 | return (await answers.next()).value as string; |
| 53 | }; |
| 54 | const fill = () => git(clone, env, ["credential", "fill"], `url=${remote}\n\n`); |
| 55 | |
| 56 | const taken = await call(1, "refs_take", { task: 7 }); |
| 57 | assert.doesNotMatch(taken, /refs_agent_/); |
| 58 | assert.equal(calls[0].credentials, "helper"); |
| 59 | assert.equal((fs.statSync(path.join(home, "git-tokens.json")).mode & 0o777).toString(8), "600"); |
| 60 | assert.throws(() => git(clone, env, ["config", "--get-all", `http.${remote}.extraHeader`])); |
| 61 | assert.match(fill(), new RegExp(`username=x-token\npassword=${TOKEN}\n`)); |
| 62 | |
| 63 | const released = await call(2, "refs_release", {}); |
| 64 | assert.doesNotMatch(released, /"refs"/); |
| 65 | assert.throws(() => git(clone, env, ["config", "--get-all", `credential.${remote}.helper`])); |
| 66 | assert.deepEqual(JSON.parse(fs.readFileSync(path.join(home, "git-tokens.json"), "utf8")), {}); |
| 67 | |
| 68 | }); |
| 69 | |
| 70 | test("outside a refs clone, the MCP server answers on its own, offers no tools and never calls refs", async (t) => { |
| 71 | const home = fs.mkdtempSync(path.join(os.tmpdir(), "refs-cli-")); |
| 72 | t.after(() => fs.rmSync(home, { recursive: true, force: true })); |
| 73 | const project = path.join(home, "project"); |
| 74 | fs.mkdirSync(project); |
| 75 | const env = { ...process.env, REFS_HOME: home, GIT_CONFIG_NOSYSTEM: "1" }; |
| 76 | git(project, env, ["init", "-q"]); |
| 77 | git(project, env, ["remote", "add", "origin", "https://github.com/someone/project.git"]); |
| 78 | |
| 79 | for (const credentials of [null, { origin: "http://127.0.0.1:9", accessToken: "expired", expiresAt: 0 }]) { |
| 80 | if (credentials) fs.writeFileSync(path.join(home, "credentials.json"), JSON.stringify(credentials)); |
| 81 | const messages = [ |
| 82 | { jsonrpc: "2.0", id: 1, method: "initialize", params: { protocolVersion: "2025-06-18" } }, |
| 83 | { jsonrpc: "2.0", method: "notifications/initialized" }, |
| 84 | { jsonrpc: "2.0", id: 2, method: "tools/list" }, |
| 85 | { jsonrpc: "2.0", id: 3, method: "tools/call", params: { name: "refs_events", arguments: { event: "UserPromptSubmit" } } }, |
| 86 | ]; |
| 87 | const output = execFileSync(process.execPath, [CLI, "mcp"], { cwd: project, env, input: messages.map((message) => JSON.stringify(message)).join("\n") + "\n", encoding: "utf8", timeout: 5000 }); |
| 88 | const answers = output.trim().split("\n").map((line) => JSON.parse(line)); |
| 89 | assert.deepEqual( |
| 90 | answers.map((answer) => [answer.id, answer.result]), |
| 91 | [ |
| 92 | [1, { protocolVersion: "2025-06-18", capabilities: { tools: {} }, serverInfo: { name: "refs", version: "0.1.0" } }], |
| 93 | [2, { tools: [] }], |
| 94 | [3, { content: [] }], |
| 95 | ], |
| 96 | ); |
| 97 | assert.equal(fs.existsSync(path.join(home, "daemon.log")), false); |
| 98 | } |
| 99 | }); |
| 100 | |
| 101 | test("with no session token, the credential helper answers git with your own sign-in, but only when it has the git scope", (t) => { |
| 102 | const home = fs.mkdtempSync(path.join(os.tmpdir(), "refs-cli-")); |
| 103 | t.after(() => fs.rmSync(home, { recursive: true, force: true })); |
| 104 | const origin = "https://refs.example"; |
| 105 | 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" }); |
| 106 | const signIn = (scope?: string) => fs.writeFileSync(path.join(home, "credentials.json"), JSON.stringify({ origin, scope, accessToken: "u:g:secret", expiresAt: Date.now() / 1000 + 3600 })); |
| 107 | |
| 108 | signIn("agents git"); |
| 109 | assert.equal(helper(`${origin}/refs/demo.git`), "username=x-token\npassword=u:g:secret\n"); |
| 110 | assert.equal(helper("https://github.com/someone/project.git"), ""); |
| 111 | signIn("agents"); |
| 112 | assert.equal(helper(`${origin}/refs/demo.git`), ""); |
| 113 | }); |
| 114 | |
| 115 | test("the credential helper gives a session token only to git that the agent runs, and your sign-in to everyone else", (t) => { |
| 116 | const home = fs.mkdtempSync(path.join(os.tmpdir(), "refs-cli-")); |
| 117 | const other = spawn("sleep", ["30"]); |
| 118 | t.after(() => (other.kill(), fs.rmSync(home, { recursive: true, force: true }))); |
| 119 | const origin = "https://refs.example"; |
| 120 | const remote = `${origin}/refs/demo.git`; |
| 121 | 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" }); |
| 122 | const hold = (owners: Record<number, string>) => fs.writeFileSync(path.join(home, "git-tokens.json"), JSON.stringify({ [remote]: owners })); |
| 123 | fs.writeFileSync(path.join(home, "credentials.json"), JSON.stringify({ origin, scope: "agents git", accessToken: "u:g:secret", expiresAt: Date.now() / 1000 + 3600 })); |
| 124 | |
| 125 | hold({ [other.pid!]: TOKEN }); |
| 126 | assert.equal(helper(), "username=x-token\npassword=u:g:secret\n"); |
| 127 | hold({ [other.pid!]: "refs_agent_other", [process.pid]: TOKEN }); |
| 128 | assert.equal(helper(), `username=x-token\npassword=${TOKEN}\n`); |
| 129 | hold({ 999999: TOKEN }); |
| 130 | assert.equal(helper(), "username=x-token\npassword=u:g:secret\n"); |
| 131 | }); |