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>
220 lines
8.9 KiB
JavaScript
220 lines
8.9 KiB
JavaScript
import { test } from "node:test";
|
|
import assert from "node:assert/strict";
|
|
import { mkdtempSync, rmSync, readFileSync } from "node:fs";
|
|
import { tmpdir } from "node:os";
|
|
import { join } from "node:path";
|
|
|
|
const DATA_DIR = mkdtempSync(join(tmpdir(), "rithub-agent-signup-"));
|
|
process.env.RITHUB_MCP_DATA_DIR = DATA_DIR;
|
|
test.after(() => rmSync(DATA_DIR, { recursive: true, force: true }));
|
|
|
|
const mod = await import("../src/agentSignup.mjs");
|
|
const { ApiError } = await import("../src/rithubApi.mjs");
|
|
|
|
const BASE_URL = "https://rithub.test";
|
|
|
|
/** A fake admin client matching makeClient()'s shape (get/post/patch/...), standing in for the real Rithub admin API. */
|
|
function fakeAdmin({ onPost, onPatch } = {}) {
|
|
const users = new Map(); // username -> { email, max_repo_creation }
|
|
return {
|
|
async post(path, body) {
|
|
if (path === "/admin/users") {
|
|
if (onPost) onPost(body);
|
|
if ([...users.values()].some((u) => u.email === body.email)) {
|
|
throw new ApiError(422, "email already used");
|
|
}
|
|
users.set(body.username, { email: body.email, max_repo_creation: null });
|
|
return { id: users.size, login: body.username };
|
|
}
|
|
const repoMatch = /^\/admin\/users\/([^/]+)\/repos$/.exec(path);
|
|
if (repoMatch) {
|
|
return { html_url: `${BASE_URL}/${repoMatch[1]}/${body.name}`, clone_url: `${BASE_URL}/${repoMatch[1]}/${body.name}.git` };
|
|
}
|
|
throw new Error(`fakeAdmin: unexpected POST ${path}`);
|
|
},
|
|
async patch(path, body) {
|
|
const match = /^\/admin\/users\/([^/]+)$/.exec(path);
|
|
if (!match) throw new Error(`fakeAdmin: unexpected PATCH ${path}`);
|
|
if (onPatch) onPatch(match[1], body);
|
|
const user = users.get(match[1]);
|
|
if (user) Object.assign(user, body);
|
|
return { ...user };
|
|
},
|
|
_users: users,
|
|
};
|
|
}
|
|
|
|
function withFakeFetch(scriptedResponse, fn) {
|
|
const real = globalThis.fetch;
|
|
globalThis.fetch = async (url, init) => {
|
|
const body = JSON.stringify(scriptedResponse.body ?? {});
|
|
return {
|
|
status: scriptedResponse.status ?? 201,
|
|
text: async () => body,
|
|
_url: url,
|
|
_init: init,
|
|
};
|
|
};
|
|
return fn().finally(() => {
|
|
globalThis.fetch = real;
|
|
});
|
|
}
|
|
|
|
test("provisionAgent without an admin client fails closed with 503", async () => {
|
|
await assert.rejects(() => mod.provisionAgent({ admin: null, baseUrl: BASE_URL }), (err) => err.status === 503);
|
|
});
|
|
|
|
test("provisionAgent creates a unique agent-* user, caps its repo quota, and returns a git remote with the token embedded", async () => {
|
|
const admin = fakeAdmin();
|
|
await withFakeFetch({ status: 201, body: { sha1: "tok_abc123" } }, async () => {
|
|
const result = await mod.provisionAgent({ admin, baseUrl: BASE_URL });
|
|
assert.match(result.username, /^agent-/);
|
|
assert.equal(result.token, "tok_abc123");
|
|
assert.equal(result.repo, `${result.username}/first-repo`);
|
|
assert.equal(result.git_remote, `https://${result.username}:tok_abc123@rithub.test/${result.username}/first-repo.git`);
|
|
assert.equal(result.quota.repos, 3);
|
|
const stored = admin._users.get(result.username);
|
|
assert.equal(stored.max_repo_creation, 3);
|
|
assert.ok(stored.email.endsWith("@agents.rithub.dev"));
|
|
});
|
|
});
|
|
|
|
test("provisionAgent retries once on a username/email collision (422) instead of failing", async () => {
|
|
const admin = fakeAdmin();
|
|
let posts = 0;
|
|
const realPost = admin.post.bind(admin);
|
|
admin.post = async (path, body) => {
|
|
if (path === "/admin/users") {
|
|
posts += 1;
|
|
if (posts === 1) throw new ApiError(422, "taken");
|
|
}
|
|
return realPost(path, body);
|
|
};
|
|
await withFakeFetch({ status: 201, body: { sha1: "tok_retry" } }, async () => {
|
|
const result = await mod.provisionAgent({ admin, baseUrl: BASE_URL, repoName: "custom-repo" });
|
|
assert.equal(posts, 2);
|
|
assert.equal(result.repo, `${result.username}/custom-repo`);
|
|
});
|
|
});
|
|
|
|
test("provisionAgent falls back to the default repo name when given an unsafe one", async () => {
|
|
const admin = fakeAdmin();
|
|
await withFakeFetch({ status: 201, body: { sha1: "tok_safe" } }, async () => {
|
|
const result = await mod.provisionAgent({ admin, baseUrl: BASE_URL, repoName: "../../etc/passwd" });
|
|
assert.equal(result.repo.endsWith("/first-repo"), true);
|
|
});
|
|
});
|
|
|
|
test("provisionAgent surfaces a 502 when the token-mint call fails", async () => {
|
|
const admin = fakeAdmin();
|
|
await withFakeFetch({ status: 401, body: { message: "bad basic auth" } }, async () => {
|
|
await assert.rejects(() => mod.provisionAgent({ admin, baseUrl: BASE_URL }), (err) => err.status === 502);
|
|
});
|
|
});
|
|
|
|
test("issueChallenge + verifyChallenge: a real proof-of-work solution passes, is single-use, and a wrong nonce fails", async () => {
|
|
const { challenge, bits } = mod.issueChallenge(8); // low difficulty so the brute force below is instant
|
|
const { createHash } = await import("node:crypto");
|
|
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;
|
|
}
|
|
let nonce;
|
|
for (let i = 0; i < 100000; i++) {
|
|
const candidate = String(i);
|
|
const hash = createHash("sha256").update(`${challenge}:${candidate}`).digest();
|
|
if (leadingZeroBits(hash) >= bits) {
|
|
nonce = candidate;
|
|
break;
|
|
}
|
|
}
|
|
assert.ok(nonce, "expected to find a solution within 100000 tries at 8 bits of difficulty");
|
|
assert.equal(mod.verifyChallenge(challenge, nonce).ok, true);
|
|
// Single-use: the same challenge cannot be redeemed twice.
|
|
assert.equal(mod.verifyChallenge(challenge, nonce).ok, false);
|
|
});
|
|
|
|
test("verifyChallenge rejects an unknown or expired challenge", () => {
|
|
assert.equal(mod.verifyChallenge("not-a-real-challenge", "0").ok, false);
|
|
});
|
|
|
|
test("checkRateLimit allows up to the configured max per IP per hour, then blocks", () => {
|
|
const ip = `203.0.113.${Math.floor(Math.random() * 255)}`; // isolate from other tests
|
|
for (let i = 0; i < 3; i++) assert.equal(mod.checkRateLimit(ip, { maxPerHour: 3 }), true);
|
|
assert.equal(mod.checkRateLimit(ip, { maxPerHour: 3 }), false);
|
|
});
|
|
|
|
test("claimAgent sets the real email and lifts the quota for an unclaimed agent account", async () => {
|
|
const admin = fakeAdmin();
|
|
const fakeAsUser = { get: async () => ({ login: "agent-xyz123", email: "agent-xyz123@agents.rithub.dev" }) };
|
|
admin._users.set("agent-xyz123", { email: "agent-xyz123@agents.rithub.dev", max_repo_creation: 3 });
|
|
|
|
// claimAgent builds its own `asUser` client via makeClient(); swap in a
|
|
// fake by monkey-patching global fetch so `GET /user` resolves without a
|
|
// real server. Simpler here: call the internal flow through a stub that
|
|
// bypasses makeClient -- since claimAgent is not parameterized with
|
|
// asUser, drive it through a real HTTP loop instead in http.test.mjs,
|
|
// and keep this test to the admin-side effects via a direct fetch stub.
|
|
const real = globalThis.fetch;
|
|
globalThis.fetch = async (url) => ({
|
|
status: 200,
|
|
headers: { get: () => "application/json" },
|
|
ok: true,
|
|
text: async () => JSON.stringify({ login: "agent-xyz123", email: "agent-xyz123@agents.rithub.dev" }),
|
|
});
|
|
try {
|
|
const result = await mod.claimAgent({ admin, baseUrl: BASE_URL, token: "tok_abc123", email: "real-human@example.com" });
|
|
assert.equal(result.username, "agent-xyz123");
|
|
assert.equal(result.quota, "removed");
|
|
const stored = admin._users.get("agent-xyz123");
|
|
assert.equal(stored.email, "real-human@example.com");
|
|
assert.equal(stored.max_repo_creation, -1);
|
|
} finally {
|
|
globalThis.fetch = real;
|
|
}
|
|
});
|
|
|
|
test("claimAgent refuses an already-claimed account (email no longer a placeholder)", async () => {
|
|
const admin = fakeAdmin();
|
|
const real = globalThis.fetch;
|
|
globalThis.fetch = async () => ({
|
|
status: 200,
|
|
headers: { get: () => "application/json" },
|
|
ok: true,
|
|
text: async () => JSON.stringify({ login: "agent-already", email: "someone@real.com" }),
|
|
});
|
|
try {
|
|
await assert.rejects(() => mod.claimAgent({ admin, baseUrl: BASE_URL, token: "tok_any", email: "other@example.com" }), (err) => err.status === 409);
|
|
} finally {
|
|
globalThis.fetch = real;
|
|
}
|
|
});
|
|
|
|
test("claimAgent rejects a malformed email before calling the admin API", async () => {
|
|
const admin = fakeAdmin();
|
|
await assert.rejects(() => mod.claimAgent({ admin, baseUrl: BASE_URL, token: "tok_any", email: "not-an-email" }), (err) => err.status === 400);
|
|
});
|
|
|
|
test("provisionAgent appends an audit line to data/agent-signups.jsonl", async () => {
|
|
const admin = fakeAdmin();
|
|
await withFakeFetch({ status: 201, body: { sha1: "tok_audit" } }, async () => {
|
|
await mod.provisionAgent({ admin, baseUrl: BASE_URL, ip: "198.51.100.7" });
|
|
});
|
|
const lines = readFileSync(join(DATA_DIR, "agent-signups.jsonl"), "utf8").trim().split("\n");
|
|
const last = JSON.parse(lines[lines.length - 1]);
|
|
assert.equal(last.event, "signup");
|
|
assert.equal(last.ip, "198.51.100.7");
|
|
});
|