An AI agent can now get a real Rithub account, a repo-scoped access token and a first repo with zero sign-in: GET /agent-signup/challenge (a proof-of-work puzzle, not a CAPTCHA an agent can't solve), POST /agent-signup (creates an agent-* user via the admin API, caps it at max_repo_creation: 3, mints a write:repository/read:user token via Basic auth -- the one call Rithub's admin-token+sudo can't reach -- and a starter repo, returns git_remote with the token embedded so `git push` works immediately), POST /agent-signup/claim (Bearer the token + a real email -> sets the account's email and lifts the quota, reusing Rithub's own forgot-password mail instead of new claim-token infra). Lives in apps/rithub-mcp (already live at rithub.dev/mcp), not apps/console: every /mcp call hard-requires a Bearer token already, so there is no token-less path through MCP itself for a first signup -- this is plain REST next to /mcp, same shape as the existing /agent-tokens settings route. Adds the `rithub` npm CLI (packages/rithub-cli): `npx rithub init` drives the two routes above and sets up the local git remote; `rithub claim --email ...` claims it. Adds rithub.dev/llms.txt and rithub.dev/agents.html documenting both the CLI and the plain-HTTP path (incl. the exact proof-of-work algorithm) for agents that would rather skip the CLI. Verified live locally with the real CLI binary, real git, a clean temp dir and the real rithub-mcp HTTP server (pointed at a local fake of Rithub's own admin API, since this environment has no RITHUB_ADMIN_TOKEN): 0.9s from zero to a working git remote, commit, and a push attempt that correctly reached the right host. Caught and fixed a real bug this way (bin/rithub.mjs's writeFile missing a mkdir) that the unit tests alone had missed. 49 automated tests across both packages, all passing. Still needed before this is live: RITHUB_ADMIN_TOKEN set on railyard-box's rithub-mcp deployment (owner/box-ops step, noted in plans/railyard.md) and an npm publish of packages/rithub-cli. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
195 lines
8.3 KiB
JavaScript
195 lines
8.3 KiB
JavaScript
// End-to-end over real HTTP: a fake Rithub server standing in for
|
|
// rithub.dev's own REST API, and rithub-mcp's real createHttpServer()
|
|
// talking to it -- the same wiring /agent-signup will run with in
|
|
// production, minus the real Gitea/Rithub admin token. Proves the full
|
|
// challenge -> solve -> signup -> push-ready-remote -> claim loop works
|
|
// end to end, which a unit test of agentSignup.mjs alone cannot.
|
|
import { test } from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { createHash } from "node:crypto";
|
|
import http from "node:http";
|
|
import { mkdtempSync, rmSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
|
|
const DATA_DIR = mkdtempSync(join(tmpdir(), "rithub-agent-signup-route-"));
|
|
process.env.RITHUB_MCP_DATA_DIR = DATA_DIR;
|
|
process.env.RITHUB_MCP_TOKEN_KEY = "44".repeat(32);
|
|
test.after(() => rmSync(DATA_DIR, { recursive: true, force: true }));
|
|
|
|
const { createHttpServer } = await import("../src/http.mjs");
|
|
|
|
function listen(server) {
|
|
return new Promise((resolve) => server.listen(0, "127.0.0.1", () => resolve(server.address().port)));
|
|
}
|
|
|
|
/** A minimal fake of Rithub's own REST API: enough of /admin/users, /admin/users/:u, /admin/users/:u/repos, /users/:u/tokens and /user to exercise the real agent-signup code path. */
|
|
function fakeRithub() {
|
|
const users = new Map(); // username -> { email, password, max_repo_creation }
|
|
const server = http.createServer(async (req, res) => {
|
|
const chunks = [];
|
|
for await (const c of req) chunks.push(c);
|
|
const body = chunks.length ? JSON.parse(Buffer.concat(chunks).toString("utf8")) : {};
|
|
const send = (status, json) => {
|
|
res.writeHead(status, { "content-type": "application/json" });
|
|
res.end(JSON.stringify(json));
|
|
};
|
|
const url = req.url;
|
|
|
|
if (req.method === "POST" && url === "/api/v1/admin/users") {
|
|
if (users.has(body.username) || [...users.values()].some((u) => u.email === body.email)) return send(422, { message: "taken" });
|
|
users.set(body.username, { email: body.email, password: body.password, max_repo_creation: null });
|
|
return send(201, { id: users.size, login: body.username });
|
|
}
|
|
const patchMatch = /^\/api\/v1\/admin\/users\/([^/]+)$/.exec(url);
|
|
if (req.method === "PATCH" && patchMatch) {
|
|
const user = users.get(decodeURIComponent(patchMatch[1]));
|
|
if (!user) return send(404, { message: "not found" });
|
|
Object.assign(user, body);
|
|
return send(200, { ...user, login: patchMatch[1] });
|
|
}
|
|
const repoMatch = /^\/api\/v1\/admin\/users\/([^/]+)\/repos$/.exec(url);
|
|
if (req.method === "POST" && repoMatch) {
|
|
const owner = decodeURIComponent(repoMatch[1]);
|
|
return send(201, { full_name: `${owner}/${body.name}`, html_url: `https://rithub.test/${owner}/${body.name}`, clone_url: `https://rithub.test/${owner}/${body.name}.git` });
|
|
}
|
|
const tokenMatch = /^\/api\/v1\/users\/([^/]+)\/tokens$/.exec(url);
|
|
if (req.method === "POST" && tokenMatch) {
|
|
const owner = decodeURIComponent(tokenMatch[1]);
|
|
const auth = /^Basic\s+(.+)$/i.exec(req.headers["authorization"] || "");
|
|
if (!auth) return send(401, { message: "basic auth required" });
|
|
const [user, pass] = Buffer.from(auth[1], "base64").toString("utf8").split(":");
|
|
const record = users.get(owner);
|
|
if (!record || user !== owner || pass !== record.password) return send(401, { message: "bad credentials" });
|
|
return send(201, { sha1: `tok_${owner}`, name: body.name, scopes: body.scopes });
|
|
}
|
|
if (req.method === "GET" && url === "/api/v1/user") {
|
|
const auth = /^token\s+(.+)$/i.exec(req.headers["authorization"] || "");
|
|
const token = auth?.[1];
|
|
const found = [...users.entries()].find(([login]) => `tok_${login}` === token);
|
|
if (!found) return send(401, { message: "bad token" });
|
|
return send(200, { login: found[0], email: found[1].email });
|
|
}
|
|
send(404, { message: "not found in fake rithub" });
|
|
});
|
|
return server;
|
|
}
|
|
|
|
function leadingZeroBits(buf) {
|
|
let n = 0;
|
|
for (const byte of buf) {
|
|
if (byte === 0) {
|
|
n += 8;
|
|
continue;
|
|
}
|
|
let b = byte;
|
|
while ((b & 0x80) === 0) {
|
|
n += 1;
|
|
b <<= 1;
|
|
}
|
|
break;
|
|
}
|
|
return n;
|
|
}
|
|
|
|
function solve(challenge, bits) {
|
|
for (let i = 0; ; i++) {
|
|
const nonce = String(i);
|
|
if (leadingZeroBits(createHash("sha256").update(`${challenge}:${nonce}`).digest()) >= bits) return nonce;
|
|
}
|
|
}
|
|
|
|
test("POST /agent-signup without RITHUB_ADMIN_TOKEN answers 503 (fail-closed, not silently open)", async () => {
|
|
delete process.env.RITHUB_ADMIN_TOKEN;
|
|
const server = createHttpServer({ baseUrl: "https://rithub.test" });
|
|
const port = await listen(server);
|
|
try {
|
|
const challengeRes = await fetch(`http://127.0.0.1:${port}/agent-signup/challenge`);
|
|
const { challenge, bits } = await challengeRes.json();
|
|
const res = await fetch(`http://127.0.0.1:${port}/agent-signup`, {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ challenge, nonce: solve(challenge, bits) }),
|
|
});
|
|
assert.equal(res.status, 503);
|
|
} finally {
|
|
server.close();
|
|
}
|
|
});
|
|
|
|
test("POST /agent-signup rejects a wrong proof-of-work nonce with 400, before any Rithub call", async () => {
|
|
process.env.RITHUB_ADMIN_TOKEN = "unused-in-this-test";
|
|
const server = createHttpServer({ baseUrl: "https://rithub.test" });
|
|
const port = await listen(server);
|
|
try {
|
|
const challengeRes = await fetch(`http://127.0.0.1:${port}/agent-signup/challenge`);
|
|
const { challenge } = await challengeRes.json();
|
|
const res = await fetch(`http://127.0.0.1:${port}/agent-signup`, {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ challenge, nonce: "not-a-real-solution" }),
|
|
});
|
|
assert.equal(res.status, 400);
|
|
} finally {
|
|
server.close();
|
|
delete process.env.RITHUB_ADMIN_TOKEN;
|
|
}
|
|
});
|
|
|
|
test("full loop: challenge -> solve -> signup -> git-ready remote -> claim, against a fake Rithub server", async () => {
|
|
const rithub = fakeRithub();
|
|
const rithubPort = await listen(rithub);
|
|
const baseUrl = `http://127.0.0.1:${rithubPort}`;
|
|
process.env.RITHUB_ADMIN_TOKEN = "admin-token-for-test";
|
|
const mcp = createHttpServer({ baseUrl });
|
|
const mcpPort = await listen(mcp);
|
|
try {
|
|
const { challenge, bits } = await (await fetch(`http://127.0.0.1:${mcpPort}/agent-signup/challenge`)).json();
|
|
const signupRes = await fetch(`http://127.0.0.1:${mcpPort}/agent-signup`, {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json" },
|
|
body: JSON.stringify({ challenge, nonce: solve(challenge, bits) }),
|
|
});
|
|
assert.equal(signupRes.status, 201);
|
|
const account = await signupRes.json();
|
|
assert.match(account.username, /^agent-/);
|
|
assert.ok(account.token.startsWith("tok_"));
|
|
assert.ok(account.git_remote.includes(`${account.username}:${account.token}@`));
|
|
assert.ok(account.git_remote.endsWith(`/${account.username}/first-repo.git`));
|
|
|
|
const claimRes = await fetch(`http://127.0.0.1:${mcpPort}/agent-signup/claim`, {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json", authorization: `Bearer ${account.token}` },
|
|
body: JSON.stringify({ email: "founder@example.com" }),
|
|
});
|
|
assert.equal(claimRes.status, 200);
|
|
const claimed = await claimRes.json();
|
|
assert.equal(claimed.username, account.username);
|
|
assert.equal(claimed.quota, "removed");
|
|
|
|
// Claiming twice is refused: the email is no longer the placeholder.
|
|
const secondClaim = await fetch(`http://127.0.0.1:${mcpPort}/agent-signup/claim`, {
|
|
method: "POST",
|
|
headers: { "content-type": "application/json", authorization: `Bearer ${account.token}` },
|
|
body: JSON.stringify({ email: "someone-else@example.com" }),
|
|
});
|
|
assert.equal(secondClaim.status, 409);
|
|
} finally {
|
|
mcp.close();
|
|
rithub.close();
|
|
delete process.env.RITHUB_ADMIN_TOKEN;
|
|
}
|
|
});
|
|
|
|
test("GET /agent-signup/challenge issues a fresh single-use challenge each time", async () => {
|
|
const server = createHttpServer({ baseUrl: "https://rithub.test" });
|
|
const port = await listen(server);
|
|
try {
|
|
const a = await (await fetch(`http://127.0.0.1:${port}/agent-signup/challenge`)).json();
|
|
const b = await (await fetch(`http://127.0.0.1:${port}/agent-signup/challenge`)).json();
|
|
assert.notEqual(a.challenge, b.challenge);
|
|
} finally {
|
|
server.close();
|
|
}
|
|
});
|