Diffinery

codician/diffinerypublic

Open-source, agent-first GitHub and GitHub Actions alternative that runs on your own Cloudflare account: git hosting, pull requests, code review and drop-in GitHub Actions YAML on Workers, Durable Objects, R2 and Containers.

314 lines · 16.7 KBRaw History
1import { Api, ApiError } from "../api.js";
2import { Ctx, str, type Command, type Group } from "../cli.js";
3import { DEFAULT_URL, normalizeUrl, readConfig, resolveConfig, writeConfig } from "../config.js";
4import { spawn } from "node:child_process";
5import { gitCapture } from "../git.js";
6import { CliError, readAll } from "../io.js";
7import { browserLikely, browserLogin, deviceLogin, revokeCliToken, type Scope } from "../login.js";
8import { json } from "../output.js";
9import { agentSetup, ghEnvToken, setupRepo } from "./agent-setup.js";
10import { setupClaudePlugins } from "./claude-plugins.js";
11
12interface User {
13 login: string;
14 name?: string | null;
15 type?: string;
16 email?: string | null;
17 html_url?: string;
18}
19
20const SCOPES = ["read", "write", "admin"] as const;
21
22const login: Command = {
23 name: "login",
24 summary: "Sign in through your browser (or with a token)",
25 description: `Opens your browser on the server's authorize page; approve the sign-in there and the CLI
26gets its own token, valid for 90 days and listed under Settings → Access tokens.
27
28On a machine without a browser (over SSH, in a container), --device prints a short code to
29enter at <server>/login/device from any browser; the CLI picks this by itself when it sees no
30display. For scripts and CI, pass a token with --token, or pipe one in with --with-token
31(piping into a plain \`diffinery login\` still works). The config file is written with mode 0600.`,
32 options: {
33 url: { type: "string", desc: "Server URL (default: DIFFINERY_URL, the saved URL, or https://diffinery.com)", arg: "URL" },
34 scope: { type: "string", desc: "Access to ask for: read, write (default) or admin. You can change it on the authorize page", arg: "SCOPE" },
35 web: { type: "boolean", desc: "Sign in through the browser on this computer (the default in a terminal)" },
36 device: { type: "boolean", desc: "Sign in with a code you enter in a browser on any device" },
37 token: { type: "string", desc: "Use this token (dfy_...) instead of signing in through the browser", arg: "TOKEN" },
38 "with-token": { type: "boolean", desc: "Read a token from stdin" },
39 },
40 maxArgs: 0,
41 async run(ctx, o) {
42 const stored = await readConfig(ctx.io.env);
43 const cfg = await resolveConfig(ctx.io);
44 const url = str(o, "url") ? normalizeUrl(str(o, "url")!) : cfg.url;
45 const scope = (str(o, "scope") ?? "write") as Scope;
46 if (!SCOPES.includes(scope)) throw new CliError(`--scope must be one of ${SCOPES.join(", ")}`, 2);
47 const modes = (["web", "device", "with-token"] as const).filter((k) => o[k] === true);
48 if (modes.length + (str(o, "token") !== undefined ? 1 : 0) > 1) throw new CliError("use only one of --web, --device, --token and --with-token", 2);
49
50 let token: string;
51 let note = "";
52 if (str(o, "token") !== undefined || o["with-token"] || (!modes.length && !ctx.io.stdin.isTTY)) {
53 token = (str(o, "token") ?? (await readAll(ctx.io.stdin)).replace(/\r?\n$/, "")).trim();
54 if (!token) throw new CliError(o["with-token"] || str(o, "token") !== undefined ? "no token given" : "no token on stdin; run `diffinery login` in a terminal to sign in through your browser, or pass --token");
55 } else {
56 const device = o.device === true || (o.web !== true && !browserLikely(ctx.io));
57 const grant = device ? await deviceLogin(ctx, url, scope) : await browserLogin(ctx, url, scope);
58 token = grant.access_token;
59 note = ` with ${grant.scope} access until ${new Date(grant.expires_at).toLocaleDateString("en-US", { dateStyle: "medium" })}`;
60 }
61 const me = await new Api(url, token).get<User>("/user");
62 const file = await writeConfig(ctx.io.env, { ...stored, url, token });
63 // The token this one replaces: revoke it if a CLI sign-in made it (never a token someone pasted, which may be used elsewhere).
64 if (stored.token && stored.token !== token) await revokeCliToken(stored.url ? normalizeUrl(stored.url) : url, stored.token);
65 ctx.out(`${ctx.c.green("✓")} Logged in to ${url} as ${ctx.c.bold(me.login)}${me.type === "Bot" ? " (agent)" : ""}${note}`);
66 ctx.err(ctx.c.dim(`Saved to ${file}`));
67 if (ctx.io.env.DIFFINERY_TOKEN) ctx.err(ctx.c.yellow("note: DIFFINERY_TOKEN is set and overrides the saved token"));
68 },
69};
70
71const logout: Command = {
72 name: "logout",
73 summary: "Sign out: forget the saved token, and revoke it if a browser sign-in created it",
74 maxArgs: 0,
75 async run(ctx) {
76 const stored = await readConfig(ctx.io.env);
77 if (!stored.token) ctx.out("Not logged in.");
78 else {
79 const url = stored.url ? normalizeUrl(stored.url) : DEFAULT_URL;
80 const revoked = await revokeCliToken(url, stored.token);
81 await writeConfig(ctx.io.env, { url: stored.url });
82 ctx.out(`Logged out of ${url}${revoked ? " and revoked the CLI's token" : ""}.`);
83 }
84 if (ctx.io.env.DIFFINERY_TOKEN) ctx.err(ctx.c.yellow("note: DIFFINERY_TOKEN is still set in your environment"));
85 },
86};
87
88const whoami: Command = {
89 name: "whoami",
90 summary: "Show the account the current token acts as",
91 json: true,
92 maxArgs: 0,
93 async run(ctx) {
94 const cfg = await ctx.config();
95 const me = await (await ctx.authedApi()).get<User>("/user");
96 if (ctx.json) return json(ctx.io, me);
97 ctx.out(`${ctx.c.bold(me.login)}${me.name && me.name !== me.login ? ` (${me.name})` : ""}${me.type === "Bot" ? " [agent]" : ""}`);
98 ctx.out(ctx.c.dim(`${cfg.url} · token from ${cfg.tokenSource === "env" ? "DIFFINERY_TOKEN" : cfg.file}`));
99 },
100};
101
102const setupGit: Command = {
103 name: "auth setup-git",
104 summary: "Make git use your Diffinery token for HTTPS remotes",
105 description: `Runs: git config --global credential.<url>.helper "!diffinery auth git-credential"
106(after resetting other helpers for that URL), so clone/fetch/push to the Diffinery host
107authenticate with the token from the config file or DIFFINERY_TOKEN.`,
108 maxArgs: 0,
109 async run(ctx) {
110 const cfg = await ctx.config();
111 const key = `credential.${cfg.url}.helper`;
112 await gitCapture(ctx.io, ["config", "--global", "--unset-all", key]);
113 // An empty helper resets the list so a generic helper (e.g. a keychain) does not answer first.
114 for (const value of ["", "!diffinery auth git-credential"]) {
115 const r = await gitCapture(ctx.io, ["config", "--global", "--add", key, value]);
116 if (r.code !== 0) throw new CliError(`git config failed: ${r.stderr.trim()}`);
117 }
118 ctx.out(`${ctx.c.green("✓")} git will use diffinery for ${cfg.url}`);
119 },
120};
121
122/** Runs gh with `input` on stdin; output is captured, so a token on stdin never reaches the terminal. */
123function ghCapture(env: NodeJS.ProcessEnv, args: string[], input: string): Promise<{ code: number; stderr: string }> {
124 return new Promise((resolve) => {
125 let child;
126 try {
127 child = spawn("gh", args, { env, stdio: ["pipe", "pipe", "pipe"] });
128 } catch (e) {
129 return resolve({ code: 127, stderr: String((e as Error).message) });
130 }
131 let stderr = "";
132 child.stdout.on("data", () => {});
133 child.stderr.on("data", (d: Buffer) => (stderr += d.toString()));
134 child.on("error", (e) => resolve({ code: 127, stderr: (e as NodeJS.ErrnoException).code === "ENOENT" ? "gh is not installed (https://cli.github.com)" : e.message }));
135 child.on("close", (code) => resolve({ code: code ?? 1, stderr }));
136 child.stdin.on("error", () => {});
137 child.stdin.end(input);
138 });
139}
140
141const setupGh: Command = {
142 name: "auth setup-gh",
143 summary: "Sign the GitHub CLI (gh) in to Diffinery with your token",
144 description: `Runs: gh auth login --hostname <host> --with-token --git-protocol https, with the token
145from the config file or DIFFINERY_TOKEN on its standard input. gh then treats the Diffinery host
146like GitHub Enterprise Server: gh pr create, view, checks, status, merge and the rest work in
147clones of Diffinery repositories, and so does the pull request badge of Claude Code, which
148asks gh for its token.`,
149 maxArgs: 0,
150 async run(ctx) {
151 const cfg = await ctx.config();
152 if (!cfg.token) throw new CliError("not logged in: run `diffinery login` or set DIFFINERY_TOKEN");
153 const url = new URL(cfg.url);
154 if (url.protocol !== "https:") throw new CliError(`gh only talks to hosts over HTTPS; ${cfg.url} is ${url.protocol.replace(/:$/, "")}`);
155 // gh refuses to sign in while a token for the host is in its environment, and uses that one instead.
156 const fromEnv = ghEnvToken(ctx.io.env, url.host);
157 if (fromEnv) {
158 if (fromEnv.value !== cfg.token) throw new CliError(`gh uses ${fromEnv.name} from the environment for ${url.host}, which isn't your Diffinery token: set it to the same token, or unset it`);
159 ctx.out(`${ctx.c.green("✓")} gh uses ${fromEnv.name} for ${url.host}${ctx.io.env.GH_HOST === url.host ? "" : ` (set GH_HOST=${url.host} too, so gh finds it in clones)`}`);
160 return;
161 }
162 const r = await ghCapture(ctx.io.env, ["auth", "login", "--hostname", url.host, "--with-token", "--git-protocol", "https"], `${cfg.token}\n`);
163 if (r.code !== 0) throw new CliError(`gh auth login failed: ${r.stderr.trim() || `exit ${r.code}`}`);
164 ctx.out(`${ctx.c.green("✓")} gh is signed in to ${url.host}`);
165 },
166};
167
168/** Parses the git credential helper protocol's key=value lines. */
169export function parseCredentialInput(text: string): Record<string, string> {
170 const out: Record<string, string> = {};
171 for (const line of text.split(/\r?\n/)) {
172 if (!line) break;
173 const i = line.indexOf("=");
174 if (i > 0) out[line.slice(0, i)] = line.slice(i + 1);
175 }
176 return out;
177}
178
179const gitCredential: Command = {
180 name: "auth git-credential",
181 summary: "Git credential helper (used by 'auth setup-git')",
182 args: "<get|store|erase>",
183 minArgs: 1,
184 maxArgs: 1,
185 async run(ctx, _o, [op]) {
186 const input = parseCredentialInput(await readAll(ctx.io.stdin));
187 if (op !== "get") return; // store/erase: the token lives in the config file
188 const cfg = await ctx.config();
189 if (!cfg.token) return;
190 const want = new URL(cfg.url);
191 const proto = (input.protocol ?? "").toLowerCase();
192 const host = (input.host ?? "").toLowerCase();
193 if (proto !== want.protocol.replace(/:$/, "") || host !== want.host.toLowerCase()) return;
194 ctx.io.stdout.write(`protocol=${proto}\nhost=${input.host}\nusername=x-token\npassword=${cfg.token}\n`);
195 },
196};
197
198const mcpConfig: Command = {
199 name: "mcp-config",
200 summary: "Print an MCP server config snippet for Claude Code and other MCP clients",
201 description: `By default the token is written as \${DIFFINERY_TOKEN} (expanded by clients such as
202Claude Code from the environment). Pass --show-token to embed the saved token instead.`,
203 options: { "show-token": { type: "boolean", desc: "Embed the actual token in the snippet" } },
204 maxArgs: 0,
205 async run(ctx, o) {
206 const cfg = await ctx.config();
207 let token = "${DIFFINERY_TOKEN}";
208 if (o["show-token"]) {
209 if (!cfg.token) throw new CliError("not logged in: run `diffinery login` or set DIFFINERY_TOKEN");
210 token = cfg.token;
211 }
212 json(ctx.io, { mcpServers: { diffinery: { type: "http", url: `${cfg.url}/mcp`, headers: { Authorization: `Bearer ${token}` } } } });
213 },
214};
215
216/** The signed-in account, or null when there is no token or the server turns it down. */
217async function signedInAs(url: string, token: string | null): Promise<User | null> {
218 if (!token) return null;
219 try {
220 return await new Api(url, token).get<User>("/user");
221 } catch (e) {
222 if (e instanceof ApiError && e.status === 401) return null;
223 throw e;
224 }
225}
226
227const setup: Command = {
228 name: "setup",
229 summary: "Set up this computer in one go: sign in, then git and gh",
230 description: `Signs in through your browser (or with a code, on a machine without one) unless the CLI is
231signed in already, then runs \`diffinery auth setup-git\` so git clone, fetch and push use the
232sign-in, and \`diffinery auth setup-gh\` when the GitHub CLI (gh) is installed. Where Claude Code is
233installed, it also adds Claude Code's Diffinery plugins (diffinery and diffinery-ci): they're saved in
234~/.claude/diffinery-plugins and named in ~/.claude/settings.json, so every new Claude Code session loads
235them. Skip that with --no-claude-plugins (or DIFFINERY_NO_CLAUDE_PLUGINS=1). Safe to run again; it
236brings the plugins up to date.
237
238With --repo OWNER/NAME it sets up an agent environment instead (a Claude Code cloud environment,
239Codex, a CI runner), with no browser and no prompt: git and gh use the token in DIFFINERY_TOKEN
240(and GH_ENTERPRISE_TOKEN with GH_HOST for gh) straight from the environment, so no token is written
241to disk; the repository is cloned unless it's there already; then a self-test prints one line per
242check, saying what to change when one fails, and reports the result to the repository's Agent setup
243page. Exits 1 when a check fails. This is what <server>/OWNER/NAME/agent-setup.sh runs.`,
244 options: {
245 url: login.options!.url!,
246 scope: login.options!.scope!,
247 web: login.options!.web!,
248 device: login.options!.device!,
249 repo: { type: "string", desc: "Set up an agent environment for this repository instead, with the token in DIFFINERY_TOKEN (what <server>/OWNER/NAME/agent-setup.sh runs)", arg: "OWNER/NAME" },
250 "no-clone": { type: "boolean", desc: "With --repo: don't clone the repository (also DIFFINERY_NO_CLONE=1)" },
251 "clone-dir": { type: "string", desc: "With --repo: where the clone goes (default: DIFFINERY_CLONE_DIR, /home/user in a Claude Code cloud environment, else the current directory)", arg: "DIR" },
252 "no-report": { type: "boolean", desc: "With --repo: don't report the result to the repository's Agent setup page" },
253 "no-claude-plugins": { type: "boolean", desc: "Don't add Claude Code's Diffinery plugins (also DIFFINERY_NO_CLAUDE_PLUGINS=1)" },
254 },
255 maxArgs: 0,
256 async run(ctx, o) {
257 if (str(o, "repo") !== undefined) {
258 // Run by a setup script: never a browser, never a prompt.
259 const cfg = await ctx.config();
260 const url = str(o, "url") ? normalizeUrl(str(o, "url")!) : cfg.url;
261 let next = ctx;
262 if (url !== cfg.url) {
263 if (cfg.urlSource === "env") throw new CliError(`DIFFINERY_URL is ${cfg.url}, but this sets up ${url}: unset DIFFINERY_URL or set it to ${url}`, 2);
264 // The server is saved (its URL only: a saved token belongs to the other server), so git's credential
265 // helper and later commands use it in sessions that don't set DIFFINERY_URL.
266 await writeConfig(ctx.io.env, { url });
267 next = new Ctx(ctx.io, ctx.opts);
268 }
269 return agentSetup(next, { repo: setupRepo(str(o, "repo")!), url, clone: o["no-clone"] !== true && !ctx.io.env.DIFFINERY_NO_CLONE, cloneDir: str(o, "clone-dir"), report: o["no-report"] !== true, claudePlugins: o["no-claude-plugins"] !== true }, (c) => setupGit.run(new Ctx(c.io, {}), {}, []) as Promise<void>);
270 }
271 const cfg = await ctx.config();
272 const url = str(o, "url") ? normalizeUrl(str(o, "url")!) : cfg.url;
273 const me = url === cfg.url ? await signedInAs(url, cfg.token) : null;
274 if (me) ctx.out(`${ctx.c.green("✓")} Signed in to ${url} as ${ctx.c.bold(me.login)}${me.type === "Bot" ? " (agent)" : ""}`);
275 else {
276 // Unlike login, setup never reads a token from stdin: run by an agent or a script, it still signs in a person.
277 const how = o.web === true || o.device === true ? {} : browserLikely(ctx.io) ? { web: true } : { device: true };
278 await login.run(ctx, { ...o, ...how }, []);
279 }
280 // A fresh context, so the next steps read the sign-in just saved.
281 const next = new Ctx(ctx.io, {});
282 await setupGit.run(next, {}, []);
283 let failed = false;
284 if (new URL(url).protocol !== "https:") ctx.err(ctx.c.dim("Skipped gh: it only talks to hosts over HTTPS."));
285 else if ((await ghCapture(ctx.io.env, ["--version"], "")).code !== 0) ctx.err(ctx.c.dim("Skipped gh, which isn't installed. Run `diffinery auth setup-gh` after installing it (https://cli.github.com)."));
286 else
287 try {
288 await setupGh.run(next, {}, []);
289 } catch (e) {
290 if (!(e instanceof CliError)) throw e;
291 ctx.err(`${ctx.c.yellow("warning:")} ${e.message}`);
292 failed = true;
293 }
294 if (o["no-claude-plugins"] !== true) {
295 try {
296 const p = await setupClaudePlugins(ctx.io.env, url);
297 if (p?.ok) ctx.out(`${ctx.c.green("✓")} Claude Code plugins: ${p.message}`);
298 else if (p) {
299 ctx.err(`${ctx.c.yellow("warning:")} Claude Code plugins: ${p.message}`);
300 failed = true;
301 }
302 } catch (e) {
303 ctx.err(`${ctx.c.yellow("warning:")} Claude Code plugins: ${(e as Error).message}`);
304 failed = true;
305 }
306 }
307 ctx.out("");
308 ctx.out(`Connect Claude Code, Codex, Cursor and other AI apps: ${url}/docs/connect`);
309 return failed ? 1 : 0;
310 },
311};
312
313export const authCommands: Command[] = [login, logout, whoami, setup, mcpConfig];
314export const authGroup: Group = { name: "auth", summary: "Git and GitHub CLI integration", commands: [setupGit, setupGh, gitCredential] };