Diffinery

homeflare/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.

245 lines · 11.3 KBRaw History
1import type { Env } from "../env.js";
2import { b64url, fromB64, hmacSha256Hex, safeEqual } from "../lib/util.js";
3
4/**
5 * The instance's GitHub App, which lets GitHub repositories run jobs on Diffinery runners
6 * (docs/actions/github-runners.md). It needs these repository permissions: Administration (read and
7 * write), to register a just-in-time runner for one job; Actions (read); Metadata (read). It subscribes
8 * to the Workflow job event; GitHub sends installation events to every app.
9 */
10export interface GitHubAppConfig {
11 appId: string;
12 slug: string;
13 clientId: string;
14 clientSecret: string;
15 privateKey: string;
16 webhookSecret: string;
17 /** https://github.com, or a GitHub Enterprise Server origin. */
18 webUrl: string;
19 /** https://api.github.com, or <webUrl>/api/v3 on GitHub Enterprise Server. */
20 apiUrl: string;
21}
22
23/** The app's settings, or null when this Diffinery has no GitHub App (the feature is then off). */
24export function githubApp(env: Env): GitHubAppConfig | null {
25 const { GITHUB_APP_ID: appId, GITHUB_APP_SLUG: slug, GITHUB_APP_CLIENT_ID: clientId, GITHUB_APP_CLIENT_SECRET: clientSecret, GITHUB_APP_PRIVATE_KEY: privateKey, GITHUB_APP_WEBHOOK_SECRET: webhookSecret } = env;
26 if (!appId || !slug || !clientId || !clientSecret || !privateKey || !webhookSecret) return null;
27 const webUrl = (env.GITHUB_APP_URL || "https://github.com").replace(/\/+$/, "");
28 const apiUrl = webUrl === "https://github.com" ? "https://api.github.com" : `${webUrl}/api/v3`;
29 return { appId, slug, clientId, clientSecret, privateKey, webhookSecret, webUrl, apiUrl };
30}
31
32/** Whether a webhook body carries GitHub's signature (X-Hub-Signature-256) made with the app's webhook secret. */
33export async function webhookSigned(secret: string, header: string | undefined, body: string): Promise<boolean> {
34 if (!header?.startsWith("sha256=")) return false;
35 return safeEqual(header.slice(7).toLowerCase(), await hmacSha256Hex(secret, body));
36}
37
38// ---------------------------------------------------------------- the app's JWT
39
40/** DER length bytes. */
41function derLength(n: number): number[] {
42 if (n < 0x80) return [n];
43 const out: number[] = [];
44 for (let v = n; v > 0; v >>= 8) out.unshift(v & 0xff);
45 return [0x80 | out.length, ...out];
46}
47
48function der(tag: number, body: Uint8Array): Uint8Array {
49 const len = derLength(body.length);
50 const out = new Uint8Array(1 + len.length + body.length);
51 out[0] = tag;
52 out.set(len, 1);
53 out.set(body, 1 + len.length);
54 return out;
55}
56
57/** rsaEncryption's AlgorithmIdentifier: SEQUENCE { OID 1.2.840.113549.1.1.1, NULL }. */
58const RSA_ALGORITHM = new Uint8Array([0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00]);
59
60/**
61 * A PEM private key as PKCS#8 DER. GitHub gives an app's key as PKCS#1 ("BEGIN RSA PRIVATE KEY"), which
62 * Web Crypto doesn't read, so that one is wrapped: SEQUENCE { INTEGER 0, rsaEncryption, OCTET STRING key }.
63 * Escaped newlines (a key pasted into one line of a secret) are accepted.
64 */
65export function pkcs8FromPem(pem: string): Uint8Array {
66 const text = pem.replace(/\\n/g, "\n").trim();
67 const m = /-----BEGIN (RSA )?PRIVATE KEY-----([\s\S]+?)-----END (RSA )?PRIVATE KEY-----/.exec(text);
68 if (!m) throw new Error("GITHUB_APP_PRIVATE_KEY is not a PEM private key");
69 const body = fromB64(m[2]!.replace(/\s+/g, ""));
70 if (!m[1]) return body;
71 const version = new Uint8Array([0x02, 0x01, 0x00]);
72 const key = der(0x04, body);
73 const inner = new Uint8Array(version.length + RSA_ALGORITHM.length + key.length);
74 inner.set(version, 0);
75 inner.set(RSA_ALGORITHM, version.length);
76 inner.set(key, version.length + RSA_ALGORITHM.length);
77 return der(0x30, inner);
78}
79
80/** The app's JWT (RS256), valid for 9 minutes; issued a minute in the past for clock drift, as GitHub suggests. */
81export async function appJwt(app: Pick<GitHubAppConfig, "appId" | "privateKey">, nowSeconds = Math.floor(Date.now() / 1000)): Promise<string> {
82 const key = await crypto.subtle.importKey("pkcs8", pkcs8FromPem(app.privateKey) as BufferSource, { name: "RSASSA-PKCS1-v1_5", hash: "SHA-256" }, false, ["sign"]);
83 const enc = (o: unknown) => b64url(new TextEncoder().encode(JSON.stringify(o)));
84 const head = enc({ alg: "RS256", typ: "JWT" });
85 const body = enc({ iat: nowSeconds - 60, exp: nowSeconds + 540, iss: app.appId });
86 const sig = new Uint8Array(await crypto.subtle.sign("RSASSA-PKCS1-v1_5", key, new TextEncoder().encode(`${head}.${body}`)));
87 return `${head}.${body}.${b64url(sig)}`;
88}
89
90// ---------------------------------------------------------------- API calls
91
92export class GitHubApiError extends Error {
93 constructor(
94 readonly status: number,
95 message: string,
96 ) {
97 super(message);
98 }
99}
100
101export interface JitRunner {
102 runnerId: number;
103 /** The runner's whole configuration and credentials: never logged or stored. */
104 encodedJitConfig: string;
105}
106
107export interface GitHubInstallation {
108 id: number;
109 login: string;
110 type: string;
111}
112
113export interface GitHubRunnerState {
114 busy: boolean;
115 status: string;
116}
117
118/** The calls Diffinery makes to GitHub for runners. One per Durable Object, which keeps installation tokens for their hour. */
119export class GitHubAppClient {
120 private tokens = new Map<number, { token: string; expires: number }>();
121
122 constructor(
123 readonly app: GitHubAppConfig,
124 private readonly fetcher: typeof fetch = (input, init) => fetch(input, init),
125 ) {}
126
127 private async call<T>(method: string, path: string, auth: string, body?: unknown): Promise<T> {
128 const res = await this.fetcher(`${this.app.apiUrl}/${path.replace(/^\//, "")}`, {
129 method,
130 headers: {
131 accept: "application/vnd.github+json",
132 authorization: auth,
133 "x-github-api-version": "2022-11-28",
134 "user-agent": "Diffinery",
135 ...(body === undefined ? {} : { "content-type": "application/json" }),
136 },
137 body: body === undefined ? undefined : JSON.stringify(body),
138 signal: AbortSignal.timeout(30_000),
139 });
140 if (res.status === 204) return undefined as T;
141 const text = await res.text();
142 if (!res.ok) {
143 let message = text.slice(0, 300);
144 try {
145 message = (JSON.parse(text) as { message?: string }).message ?? message;
146 } catch {
147 /* not JSON */
148 }
149 throw new GitHubApiError(res.status, `GitHub answered ${res.status} to ${method} ${path.split("?")[0]}: ${message}`);
150 }
151 return JSON.parse(text) as T;
152 }
153
154 private async asApp<T>(method: string, path: string, body?: unknown): Promise<T> {
155 return this.call<T>(method, path, `Bearer ${await appJwt(this.app)}`, body);
156 }
157
158 /** An installation token, reused until 5 minutes before it expires. */
159 private async installationToken(installationId: number): Promise<string> {
160 const kept = this.tokens.get(installationId);
161 if (kept && kept.expires - Date.now() > 5 * 60_000) return kept.token;
162 const r = await this.asApp<{ token: string; expires_at: string }>("POST", `app/installations/${installationId}/access_tokens`, {});
163 this.tokens.set(installationId, { token: r.token, expires: Date.parse(r.expires_at) || Date.now() + 50 * 60_000 });
164 return r.token;
165 }
166
167 private async asInstallation<T>(installationId: number, method: string, path: string, body?: unknown): Promise<T> {
168 return this.call<T>(method, path, `Bearer ${await this.installationToken(installationId)}`, body);
169 }
170
171 /** The GitHub account an installation is on. */
172 async installation(installationId: number): Promise<GitHubInstallation> {
173 const r = await this.asApp<{ id: number; account: { login: string; type: string } | null }>("GET", `app/installations/${installationId}`);
174 return { id: r.id, login: r.account?.login ?? "", type: r.account?.type ?? "User" };
175 }
176
177 /**
178 * Registers a just-in-time runner in the repository for one job: GitHub gives it to a queued job whose
179 * labels it has, and removes it once that job ends. Runner group 1 is a repository's default group.
180 */
181 async jitRunner(installationId: number, repo: string, name: string, labels: string[]): Promise<JitRunner> {
182 const r = await this.asInstallation<{ runner: { id: number }; encoded_jit_config: string }>(installationId, "POST", `repos/${repo}/actions/runners/generate-jitconfig`, { name, runner_group_id: 1, labels });
183 return { runnerId: r.runner.id, encodedJitConfig: r.encoded_jit_config };
184 }
185
186 /** Whether a registered runner is running a job; null once GitHub no longer has it. */
187 async runner(installationId: number, repo: string, runnerId: number): Promise<GitHubRunnerState | null> {
188 try {
189 return await this.asInstallation<GitHubRunnerState>(installationId, "GET", `repos/${repo}/actions/runners/${runnerId}`);
190 } catch (e) {
191 if (e instanceof GitHubApiError && e.status === 404) return null;
192 throw e;
193 }
194 }
195
196 /** Removes a runner that never took a job (one that did removes itself). */
197 async removeRunner(installationId: number, repo: string, runnerId: number): Promise<void> {
198 try {
199 await this.asInstallation<void>(installationId, "DELETE", `repos/${repo}/actions/runners/${runnerId}`);
200 } catch (e) {
201 if (!(e instanceof GitHubApiError && e.status === 404)) throw e;
202 }
203 }
204
205 // ---------------------------------------------------------------- a person's GitHub sign-in, to link an installation
206
207 /** Where a person authorizes the app, which proves which installations they can manage. */
208 authorizeUrl(redirectUri: string, state: string): string {
209 const u = new URL(`${this.app.webUrl}/login/oauth/authorize`);
210 u.searchParams.set("client_id", this.app.clientId);
211 u.searchParams.set("redirect_uri", redirectUri);
212 u.searchParams.set("state", state);
213 u.searchParams.set("allow_signup", "false");
214 return u.toString();
215 }
216
217 /** Where a person installs the app; GitHub passes `state` on to the app's setup URL. */
218 installUrl(state: string): string {
219 return `${this.app.webUrl}/apps/${encodeURIComponent(this.app.slug)}/installations/new?state=${encodeURIComponent(state)}`;
220 }
221
222 /** Trades the code GitHub sent back for the person's user token (used at once, never kept). */
223 async userToken(code: string, redirectUri: string): Promise<string> {
224 const res = await this.fetcher(`${this.app.webUrl}/login/oauth/access_token`, {
225 method: "POST",
226 headers: { accept: "application/json", "content-type": "application/json", "user-agent": "Diffinery" },
227 body: JSON.stringify({ client_id: this.app.clientId, client_secret: this.app.clientSecret, code, redirect_uri: redirectUri }),
228 signal: AbortSignal.timeout(30_000),
229 });
230 const r = (await res.json().catch(() => ({}))) as { access_token?: string; error_description?: string };
231 if (!r.access_token) throw new GitHubApiError(422, `GitHub did not sign you in: ${r.error_description ?? "no access token"}`);
232 return r.access_token;
233 }
234
235 /** The app's installations the signed-in GitHub user can manage (at most 500). */
236 async userInstallations(userToken: string): Promise<GitHubInstallation[]> {
237 const out: GitHubInstallation[] = [];
238 for (let page = 1; page <= 5; page++) {
239 const r = await this.call<{ installations: Array<{ id: number; account: { login: string; type: string } | null }> }>("GET", `user/installations?per_page=100&page=${page}`, `Bearer ${userToken}`);
240 out.push(...r.installations.map((i) => ({ id: i.id, login: i.account?.login ?? "", type: i.account?.type ?? "User" })));
241 if (r.installations.length < 100) break;
242 }
243 return out;
244 }
245}