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.

1457 lines · 94.6 KBRaw History
1import { Hono } from "hono";
2import { fromUtf8 } from "@diffinery/git-core";
3import type { Env } from "../env.js";
4import { callerFor, parseScopes, requireAccount, requireAccountScope, requireBrowserSession, requireRecentSignIn, requireUnlimitedToken, tokenRepos, type AppContext, type AppVars } from "../auth/principal.js";
5import { baseRole, type Account, type Directory, type Repo, type TokenScope } from "../lib/directory.js";
6import { encryptSecret } from "../lib/crypto.js";
7import { monthStart, quotasFor, setQuotas, usageOf } from "../lib/quotas.js";
8import { changePause, changeSuspension, cleanReason, computePause, killSwitches, suspensionOf, type Stopped } from "../lib/killswitch.js";
9import { publicJwk } from "../lib/jwt.js";
10import { HttpError, b64, fromB64 } from "../lib/util.js";
11import { atLeast, ROLE_LEVEL, type ProtectionRules, type Role } from "../repo/types.js";
12import type { JobInfo, RunInfo } from "../repo/actions.js";
13import type { CommitInfo } from "../repo/RepoDO.js";
14import type { QueueEntry } from "../repo/queue.js";
15import { imports } from "./imports.js";
16import { schedulerStub } from "../lib/schedules.js";
17import { agenticApi } from "../agentic/api.js";
18import { auditRepo, loadRepo, refuseAgent, repoStub } from "./common.js";
19import { repoCreated } from "../mail/notify.js";
20import { actionsRest } from "./actions-runtime.js";
21import { compat } from "./compat.js";
22import { baseOf, encPath, ghAutoMerge, ghCheckRun, ghComment, ghCommit, ghGitCommit, ghJob, ghRef, ghRun, ghFile, ghLabel, ghReview, ghReviewComment, ghUser, isoSeconds, nodeId, numericId, pageOf, paginate, repoApi, repoHtml, setLinks } from "./gh.js";
23import { decodePath, issueCtx, issuesOut, pullDetail, pullsOut, repoOut } from "./ghctx.js";
24
25/**
26 * REST API. Paths and payloads follow GitHub's REST API v3 where practical so
27 * existing scripts and tools work; Diffinery-only endpoints live under /api/v3/diffinery.
28 */
29export const api = new Hono<{ Bindings: Env; Variables: AppVars }>().basePath("/api/v3");
30
31// GitHub-compatible endpoints that live in their own files (releases, statuses, Git data, ...).
32// Mounted first: some of their paths (like /issues/comments) would otherwise match routes below.
33api.route("/", compat);
34
35const userJson = (c: AppContext, a: Pick<Account, "id" | "login" | "kind" | "name">) => ({ ...ghUser(baseOf(c), a)!, name: a.name || null });
36
37const repoJson = repoOut;
38
39async function body<T>(c: AppContext): Promise<T> {
40 try {
41 return (await c.req.json()) as T;
42 } catch {
43 throw new HttpError(400, "request body must be JSON");
44 }
45}
46
47/** Called with an access token (scripts, the CLI, agents) rather than from a browser. */
48const viaToken = (c: AppContext) => {
49 const p = c.get("principal");
50 return p.type === "account" && p.via === "token";
51};
52const P = (c: AppContext) => ({ owner: c.req.param("owner")!, repo: c.req.param("repo")! });
53const num = (c: AppContext, name = "number") => {
54 const n = Number(c.req.param(name));
55 if (!Number.isInteger(n) || n < 1) throw new HttpError(404, "not found");
56 return n;
57};
58
59// GitHub imports, milestones, organization variables and linked accounts.
60api.route("/", imports);
61// Agentic work: the Today view (agentic/).
62api.route("/", agenticApi);
63
64// ---------------------------------------------------------------- meta & users
65
66api.get("/", (c) => c.json({ name: "Diffinery", api: "v3", docs: `${c.env.PUBLIC_URL}/docs/api`, mcp: `${c.env.PUBLIC_URL}/mcp` }));
67api.get("/meta", (c) => c.json({ name: "Diffinery", oidc: !!c.env.OIDC_PRIVATE_KEY }));
68/** Site admin: the workflow scheduler's state, to tell a scheduler that stopped ticking from a run that failed to start. */
69api.get("/diffinery/admin/scheduler", async (c) => {
70 if (!requireAccount(c).site_admin) throw new HttpError(403, "site administrators only");
71 return c.json(await schedulerStub(c.env).status());
72});
73api.get("/user", (c) => {
74 const a = requireAccount(c);
75 return c.json({ ...userJson(c, a), email: a.email, site_admin: !!a.site_admin });
76});
77api.get("/users/:login", async (c) => {
78 requireAccount(c);
79 const a = await c.get("dir").accountByLogin(c.req.param("login"));
80 if (!a) throw new HttpError(404, "not found");
81 return c.json(userJson(c, a));
82});
83// Quotas and what an account uses of them (lib/quotas.ts): your own, an organization's for its owners
84// and admins, and any account's for site administrators, who can also change them.
85const usageJson = async (c: AppContext, account: Account) => {
86 const [q, u] = await Promise.all([quotasFor(c.env, account.id), usageOf(c.env, account.id)]);
87 return {
88 account: account.login,
89 exempt: q.exempt,
90 period_start: monthStart(),
91 hosted_minutes: { used: u.hosted_minutes, limit: q.hosted_minutes },
92 hosted_jobs: { running: u.hosted_jobs, limit: q.hosted_jobs },
93 sandboxes: { open: u.sandboxes, limit: q.sandboxes },
94 repositories: { count: u.repositories, limit: q.repositories },
95 };
96};
97api.get("/user/usage", async (c) => {
98 requireAccountScope(c, "read");
99 const me = requireAccount(c);
100 return c.json(await usageJson(c, me.kind === "agent" && me.owner_id ? ((await c.get("dir").account(me.owner_id)) ?? me) : me));
101});
102api.get("/orgs/:org/usage", async (c) => {
103 requireAccountScope(c, "read");
104 const a = requireAccount(c);
105 const dir = c.get("dir");
106 const org = await dir.accountByLogin(c.req.param("org"));
107 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
108 const role = await dir.orgRole(org.id, a.id);
109 if (!role && !a.site_admin) throw new HttpError(404, "not found");
110 if (role !== "owner" && role !== "admin" && !a.site_admin) throw new HttpError(403, "only organization owners and admins can see its usage");
111 return c.json(await usageJson(c, org));
112});
113const quotaTarget = async (c: AppContext) => {
114 const a = requireAccount(c);
115 if (!a.site_admin) throw new HttpError(403, "only site administrators can see and change quotas");
116 const account = await c.get("dir").accountByLogin(c.req.param("login") ?? "");
117 if (!account || account.kind === "agent") throw new HttpError(404, "no person or organization with that name");
118 return { a, account };
119};
120api.get("/admin/accounts/:login/quotas", async (c) => {
121 requireAccountScope(c, "read");
122 const { account } = await quotaTarget(c);
123 return c.json(await usageJson(c, account));
124});
125api.patch("/admin/accounts/:login/quotas", async (c) => {
126 requireAccountScope(c, "admin");
127 requireUnlimitedToken(c, "change quotas");
128 const { a, account } = await quotaTarget(c);
129 const b = await body<Record<string, number | null>>(c);
130 if (!b || typeof b !== "object" || Array.isArray(b)) throw new HttpError(422, "send the quotas to change, e.g. {\"hosted_minutes\": 6000}");
131 await setQuotas(c.env, account.id, b, a.login);
132 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: a.id, actorLogin: a.login, action: "account.quotas.set", target: account.login, detail: b }));
133 return c.json(await usageJson(c, account));
134});
135// Kill switches (lib/killswitch.ts): site administrators suspend Actions for a repository or an
136// account, or pause hosted compute on the whole instance. Same checks as the quotas above.
137const siteAdmin = (c: AppContext, what: string) => {
138 const a = requireAccount(c);
139 if (!a.site_admin) throw new HttpError(403, `only site administrators can ${what}`);
140 return a;
141};
142const stoppedJson = (s: Stopped | null) => (s ? { stopped: { repositories: s.repositories, runs: s.runs, jobs: s.jobs, sandboxes: s.sandboxes, failed: s.failed } } : {});
143const repoSuspension = async (c: AppContext, write: boolean) => {
144 if (write) {
145 requireAccountScope(c, "admin");
146 requireUnlimitedToken(c, "suspend Actions");
147 } else requireAccountScope(c, "read");
148 const a = siteAdmin(c, "see or change Actions suspensions");
149 const repo = await c.get("dir").repo(c.req.param("owner") ?? "", c.req.param("repo") ?? "");
150 if (!repo) throw new HttpError(404, "no repository with that name");
151 return { a, repo, json: async (stopped: Stopped | null = null) => {
152 const k = await killSwitches(c.env, repo.id);
153 return { repository: `${repo.owner_login}/${repo.name}`, suspended: !!k.repo, reason: k.repo?.reason ?? null, suspended_by: k.repo?.by ?? null, suspended_at: k.repo?.at ?? null, owner_suspended: !!k.account, ...stoppedJson(stopped) };
154 } };
155};
156api.get("/admin/repos/:owner/:repo/actions-suspension", async (c) => c.json(await (await repoSuspension(c, false)).json()));
157api.put("/admin/repos/:owner/:repo/actions-suspension", async (c) => {
158 const { a, repo, json } = await repoSuspension(c, true);
159 const reason = cleanReason((await body<{ reason?: unknown }>(c).catch(() => ({}) as { reason?: unknown }))?.reason);
160 const stopped = await changeSuspension(c.env, (e) => c.get("dir").audit(e), a, { kind: "repo", id: repo.id, name: `${repo.owner_login}/${repo.name}` }, reason, "api");
161 return c.json(await json(stopped));
162});
163api.delete("/admin/repos/:owner/:repo/actions-suspension", async (c) => {
164 const { a, repo, json } = await repoSuspension(c, true);
165 await changeSuspension(c.env, (e) => c.get("dir").audit(e), a, { kind: "repo", id: repo.id, name: `${repo.owner_login}/${repo.name}` }, null, "api");
166 return c.json(await json());
167});
168const accountSuspension = async (c: AppContext, write: boolean) => {
169 if (write) {
170 requireAccountScope(c, "admin");
171 requireUnlimitedToken(c, "suspend Actions");
172 } else requireAccountScope(c, "read");
173 const a = siteAdmin(c, "see or change Actions suspensions");
174 const account = await c.get("dir").accountByLogin(c.req.param("login") ?? "");
175 if (!account || account.kind === "agent") throw new HttpError(404, "no person or organization with that name");
176 return { a, account, json: async (stopped: Stopped | null = null) => {
177 const s = await suspensionOf(c.env, { accountId: account.id });
178 return { account: account.login, suspended: !!s, reason: s?.reason ?? null, suspended_by: s?.by ?? null, suspended_at: s?.at ?? null, ...stoppedJson(stopped) };
179 } };
180};
181api.get("/admin/accounts/:login/actions-suspension", async (c) => c.json(await (await accountSuspension(c, false)).json()));
182api.put("/admin/accounts/:login/actions-suspension", async (c) => {
183 const { a, account, json } = await accountSuspension(c, true);
184 const reason = cleanReason((await body<{ reason?: unknown }>(c).catch(() => ({}) as { reason?: unknown }))?.reason);
185 const stopped = await changeSuspension(c.env, (e) => c.get("dir").audit(e), a, { kind: "account", id: account.id, login: account.login }, reason, "api");
186 return c.json(await json(stopped));
187});
188api.delete("/admin/accounts/:login/actions-suspension", async (c) => {
189 const { a, account, json } = await accountSuspension(c, true);
190 await changeSuspension(c.env, (e) => c.get("dir").audit(e), a, { kind: "account", id: account.id, login: account.login }, null, "api");
191 return c.json(await json());
192});
193const pauseJson = async (c: AppContext, stopped: Stopped | null = null) => {
194 const p = await computePause(c.env);
195 return { paused: !!p, reason: p?.reason ?? null, paused_by: p?.by ?? null, paused_at: p?.at ?? null, ...stoppedJson(stopped) };
196};
197const pauseAdmin = (c: AppContext, write: boolean) => {
198 if (write) {
199 requireAccountScope(c, "admin");
200 requireUnlimitedToken(c, "pause hosted compute");
201 } else requireAccountScope(c, "read");
202 return siteAdmin(c, "see or change the hosted compute pause");
203};
204api.get("/admin/hosted-compute-pause", async (c) => {
205 pauseAdmin(c, false);
206 return c.json(await pauseJson(c));
207});
208api.put("/admin/hosted-compute-pause", async (c) => {
209 const a = pauseAdmin(c, true);
210 const reason = cleanReason((await body<{ reason?: unknown }>(c).catch(() => ({}) as { reason?: unknown }))?.reason);
211 return c.json(await pauseJson(c, await changePause(c.env, (e) => c.get("dir").audit(e), a, reason, "api")));
212});
213api.delete("/admin/hosted-compute-pause", async (c) => {
214 const a = pauseAdmin(c, true);
215 await changePause(c.env, (e) => c.get("dir").audit(e), a, null, "api");
216 return c.json(await pauseJson(c));
217});
218api.get("/user/orgs", async (c) => c.json((await c.get("dir").orgsFor(requireAccount(c).id)).map((o) => ({ ...userJson(c, o), role: o.role }))));
219api.post("/user/orgs", async (c) => {
220 requireAccountScope(c, "admin");
221 const a = requireAccount(c);
222 const b = await body<{ login: string; name?: unknown }>(c);
223 if (typeof b.login !== "string") throw new HttpError(422, "login is required", { errors: [{ resource: "Organization", code: "missing_field", field: "login" }] });
224 if (b.name !== undefined && b.name !== null && typeof b.name !== "string") throw new HttpError(422, "name must be a string", { errors: [{ resource: "Organization", code: "invalid", field: "name" }] });
225 return c.json(userJson(c, await c.get("dir").createOrg(b.login, (b.name as string | null | undefined) || b.login, a)), 201);
226});
227// GitHub's organization object; members and their agents also see the base permission (default_repository_permission).
228const orgJson = async (c: AppContext, org: Account, me: Account) => ({ ...userJson(c, org), ...((await c.get("dir").inOrg(org.id, me)) ? { default_repository_permission: baseRole(org) } : {}) });
229api.get("/orgs/:org", async (c) => {
230 const a = requireAccount(c);
231 const org = await c.get("dir").accountByLogin(c.req.param("org"));
232 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
233 return c.json(await orgJson(c, org, a));
234});
235api.patch("/orgs/:org", async (c) => {
236 requireAccountScope(c, "admin");
237 const a = requireAccount(c);
238 const dir = c.get("dir");
239 const org = await dir.accountByLogin(c.req.param("org"));
240 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
241 const role = await dir.orgRole(org.id, a.id);
242 if (!role && !a.site_admin) throw new HttpError(404, "not found");
243 if (role !== "owner" && !a.site_admin) throw new HttpError(403, "only organization owners can change its settings");
244 const b = await body<{ name?: unknown; default_repository_permission?: unknown }>(c);
245 await dir.updateAccount(org.id, { name: b.name, baseRole: b.default_repository_permission });
246 c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "org.update", target: org.login, detail: { name: b.name, base_role: b.default_repository_permission } }));
247 return c.json(await orgJson(c, (await dir.account(org.id))!, a));
248});
249// Owners only. Refused while the organization still owns repositories (see Directory.deleteOrg).
250api.delete("/orgs/:org", async (c) => {
251 requireAccountScope(c, "admin");
252 const a = requireAccount(c);
253 const dir = c.get("dir");
254 const org = await dir.accountByLogin(c.req.param("org"));
255 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
256 const role = await dir.orgRole(org.id, a.id);
257 if (!role && !a.site_admin) throw new HttpError(404, "not found");
258 if (role !== "owner" && !a.site_admin) throw new HttpError(403, "only organization owners can delete it");
259 requireRecentSignIn(c, `/${org.login}?tab=settings`);
260 await dir.deleteOrg(org);
261 c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "org.delete", target: org.login }));
262 return c.json({}, 202);
263});
264api.get("/orgs/:org/members", async (c) => {
265 const a = requireAccount(c);
266 const dir = c.get("dir");
267 const org = await dir.accountByLogin(c.req.param("org"));
268 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
269 if (!(await dir.orgRole(org.id, a.id)) && !a.site_admin) throw new HttpError(404, "not found");
270 return c.json((await dir.orgMembers(org.id)).map((m) => ({ ...userJson(c, m), role: m.role })));
271});
272api.post("/orgs/:org/invitations", async (c) => {
273 requireAccountScope(c, "admin");
274 const a = requireAccount(c);
275 const dir = c.get("dir");
276 const org = await dir.accountByLogin(c.req.param("org"));
277 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
278 const role = await dir.orgRole(org.id, a.id);
279 if (role !== "owner" && role !== "admin" && !a.site_admin) throw new HttpError(403, "only organization owners and admins can invite");
280 const b = await body<{ email: string; role?: "member" | "admin" | "owner" }>(c);
281 if (!/^[^@\s]+@[^@\s]+$/.test(b.email ?? "")) throw new HttpError(422, "a valid email is required");
282 const inv = await dir.createInvite(a, { email: b.email, orgId: org.id, role: b.role ?? "member" });
283 c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "org.invite", target: org.login, detail: { email: b.email, role: b.role ?? "member" } }));
284 return c.json({ id: inv.id, url: inv.url }, 201);
285});
286
287// Site-wide invitation (no organization): site admins only.
288api.post("/invitations", async (c) => {
289 requireAccountScope(c, "admin");
290 const a = requireAccount(c);
291 if (!a.site_admin) throw new HttpError(403, "only site admins can invite people without an organization");
292 const b = await body<{ email: string }>(c);
293 if (!/^[^@\s]+@[^@\s]+$/.test(b.email ?? "")) throw new HttpError(422, "a valid email is required");
294 const dir = c.get("dir");
295 const inv = await dir.createInvite(a, { email: b.email, role: "member" });
296 c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "site.invite", detail: { email: b.email } }));
297 return c.json({ id: inv.id, url: inv.url }, 201);
298});
299
300// Pending invitations: list and revoke, for an organization's owners and admins, a repository's admins,
301// and site admins (invitations to the site itself).
302const inviteJson = (i: Awaited<ReturnType<Directory["invites"]>>[number]) => ({ id: i.id, email: i.email, login: i.login, role: i.role, inviter: i.invitedBy ? { login: i.invitedBy } : null, created_at: i.createdAt, expires_at: i.expiresAt });
303const orgForInvites = async (c: AppContext) => {
304 requireAccountScope(c, "read");
305 const a = requireAccount(c);
306 const dir = c.get("dir");
307 const org = await dir.accountByLogin(c.req.param("org") ?? "");
308 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
309 const role = await dir.orgRole(org.id, a.id);
310 if (!role && !a.site_admin) throw new HttpError(404, "not found");
311 if (role !== "owner" && role !== "admin" && !a.site_admin) throw new HttpError(403, "only organization owners and admins can manage invitations");
312 return { a, dir, org };
313};
314const revoked = async (c: AppContext, ok: boolean, action: string, target?: string) => {
315 if (!ok) throw new HttpError(404, "no pending invitation with this id");
316 const a = requireAccount(c);
317 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: a.id, actorLogin: a.login, action, target, detail: { id: c.req.param("id"), via: "api" } }));
318 return c.body(null, 204);
319};
320api.get("/orgs/:org/invitations", async (c) => {
321 const { dir, org } = await orgForInvites(c);
322 return c.json((await dir.invites({ orgId: org.id, pending: true })).map(inviteJson));
323});
324api.delete("/orgs/:org/invitations/:id", async (c) => {
325 requireAccountScope(c, "admin");
326 const { dir, org } = await orgForInvites(c);
327 return revoked(c, await dir.revokeInvite(c.req.param("id"), { orgId: org.id }), "org.invite.revoke", org.login);
328});
329api.get("/repos/:owner/:repo/invitations", async (c) => {
330 const { repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
331 return c.json((await c.get("dir").invites({ repoId: repo.id, pending: true })).map(inviteJson));
332});
333api.delete("/repos/:owner/:repo/invitations/:id", async (c) => {
334 const { repo, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
335 if (!(await c.get("dir").revokeInvite(c.req.param("id"), { repoId: repo.id }))) throw new HttpError(404, "no pending invitation with this id");
336 auditRepo(c, caller, repo, "repo.invite.revoke", { id: c.req.param("id") });
337 return c.body(null, 204);
338});
339api.get("/invitations", async (c) => {
340 requireAccountScope(c, "read");
341 if (!requireAccount(c).site_admin) throw new HttpError(403, "only site admins can list site invitations");
342 return c.json((await c.get("dir").invites({ site: true, pending: true })).map(inviteJson));
343});
344api.delete("/invitations/:id", async (c) => {
345 requireAccountScope(c, "admin");
346 if (!requireAccount(c).site_admin) throw new HttpError(403, "only site admins can revoke site invitations");
347 return revoked(c, await c.get("dir").revokeInvite(c.req.param("id"), {}), "invite.revoke");
348});
349
350// ---------------------------------------------------------------- repositories
351
352api.get("/user/repos", async (c) => c.json(paginate(c, tokenRepos(c, await c.get("dir").reposVisibleTo(requireAccount(c))).map((r) => repoJson(c, r)))));
353api.post("/user/repos", async (c) => {
354 requireAccountScope(c, "write");
355 const a = requireAccount(c);
356 const b = await body<{ name: string; description?: string; private?: boolean; visibility?: string; default_branch?: string }>(c);
357 const owner = a.kind === "agent" ? (await c.get("dir").account(a.owner_id!))! : a;
358 const r = await c.get("dir").createRepo(owner, a, { name: b.name, description: b.description, visibility: b.visibility ?? (b.private === false ? "public" : "private"), defaultBranch: b.default_branch });
359 c.executionCtx.waitUntil(repoCreated(c.env, c.get("dir"), r, a, { viaToken: viaToken(c) }));
360 return c.json(repoJson(c, r), 201);
361});
362api.get("/users/:login/repos", async (c) => {
363 const a = requireAccount(c);
364 const owner = await c.get("dir").accountByLogin(c.req.param("login"));
365 if (!owner) throw new HttpError(404, "not found");
366 return c.json(paginate(c, tokenRepos(c, await c.get("dir").reposVisibleTo(a, owner.id)).map((r) => repoJson(c, r))));
367});
368api.get("/orgs/:org/repos", async (c) => {
369 const a = requireAccount(c);
370 const org = await c.get("dir").accountByLogin(c.req.param("org"));
371 if (!org) throw new HttpError(404, "not found");
372 return c.json(paginate(c, tokenRepos(c, await c.get("dir").reposVisibleTo(a, org.id)).map((r) => repoJson(c, r))));
373});
374api.post("/orgs/:org/repos", async (c) => {
375 requireAccountScope(c, "write");
376 const a = requireAccount(c);
377 const org = await c.get("dir").accountByLogin(c.req.param("org"));
378 if (!org || org.kind !== "org") throw new HttpError(404, "organization not found");
379 const b = await body<{ name: string; description?: string; private?: boolean; visibility?: string; default_branch?: string }>(c);
380 const r = await c.get("dir").createRepo(org, a, { name: b.name, description: b.description, visibility: b.visibility ?? (b.private === false ? "public" : "private"), defaultBranch: b.default_branch });
381 c.executionCtx.waitUntil(repoCreated(c.env, c.get("dir"), r, a, { viaToken: viaToken(c) }));
382 return c.json(repoJson(c, r), 201);
383});
384api.get("/repos/:owner/:repo", async (c) => {
385 const { repo, caller, stub } = await loadRepo(c, P(c).owner, P(c).repo);
386 const stats = await stub.stats();
387 return c.json({ ...repoOut(c, repo, caller.role), open_issues_count: stats.openIssues + stats.openPulls, open_issues: stats.openIssues + stats.openPulls, stats });
388});
389api.patch("/repos/:owner/:repo", async (c) => {
390 const { repo, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin", { whileArchived: true });
391 const b = await body<{ name?: string; description?: string; private?: boolean; visibility?: Repo["visibility"]; default_branch?: string; archived?: boolean }>(c);
392 if (b.private !== undefined && typeof b.private !== "boolean") throw new HttpError(422, "private must be a boolean", { errors: [{ resource: "Repository", code: "invalid", field: "private" }] });
393 // GitHub's `private: false` makes the repository public.
394 const visibility = b.visibility ?? (b.private === true ? "private" : b.private === false ? "public" : undefined);
395 const updated = await c.get("dir").updateRepo(repo, { name: b.name, description: b.description, visibility, defaultBranch: b.default_branch, archived: b.archived });
396 const changed = Object.fromEntries(Object.entries({ name: b.name, description: b.description, visibility, default_branch: b.default_branch, archived: b.archived }).filter(([, v]) => v !== undefined));
397 if (b.archived !== undefined && b.archived !== !!repo.archived) auditRepo(c, caller, repo, b.archived ? "repo.archive" : "repo.unarchive");
398 if (Object.keys(changed).some((k) => k !== "archived")) auditRepo(c, caller, repo, "repo.update", changed);
399 return c.json(repoOut(c, updated, caller.role));
400});
401// Delete every object no ref, open pull request, merge queue entry or unfinished run reaches (after force-pushing a secret away).
402api.post("/repos/:owner/:repo/diffinery/purge-unreachable", async (c) => {
403 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
404 requireRecentSignIn(c, `/${repo.owner_login}/${repo.name}/settings`);
405 const r = await stub.purgeUnreachable(caller);
406 auditRepo(c, caller, repo, "repo.purge_unreachable", { objects: r.objects, bytes: r.bytes, via: "api" });
407 return c.json({ objects: r.objects, bytes: r.bytes });
408});
409api.delete("/repos/:owner/:repo", async (c) => {
410 const { repo, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin", { whileArchived: true });
411 if (caller.kind === "agent") throw new HttpError(403, "agents cannot delete repositories");
412 requireRecentSignIn(c, `/${repo.owner_login}/${repo.name}/settings`);
413 await c.get("dir").deleteRepo(repo);
414 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: caller.id, actorLogin: caller.login, action: "repo.delete", target: `${repo.owner_login}/${repo.name}` }));
415 return c.body(null, 204);
416});
417// GitHub's transfer: to the caller's own account or an organization they own or administer, optionally
418// under a new name. People only: never agents, job tokens (GITHUB_TOKEN) or sandbox tokens.
419api.post("/repos/:owner/:repo/transfer", async (c) => {
420 const { repo, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin", { whileArchived: true });
421 const p = c.get("principal");
422 if (p.type !== "account" || caller.kind !== "user" || caller.permissions) throw new HttpError(403, "agents and workflow tokens cannot transfer repositories");
423 requireAccountScope(c, "admin");
424 requireRecentSignIn(c, `/${repo.owner_login}/${repo.name}/settings`);
425 const b = await body<{ new_owner?: unknown; new_name?: unknown }>(c);
426 if (typeof b.new_owner !== "string" || !b.new_owner.trim()) throw new HttpError(422, "new_owner is required", { errors: [{ resource: "Repository", code: "missing_field", field: "new_owner" }] });
427 if (b.new_name !== undefined && b.new_name !== null && typeof b.new_name !== "string") throw new HttpError(422, "new_name must be a string", { errors: [{ resource: "Repository", code: "invalid", field: "new_name" }] });
428 const dir = c.get("dir");
429 const target = await dir.accountByLogin(b.new_owner.trim());
430 if (!target) throw new HttpError(422, `no user or organization named ${b.new_owner.trim()}`, { errors: [{ resource: "Repository", code: "invalid", field: "new_owner" }] });
431 const moved = await dir.transferRepo(repo, p.account, target, (b.new_name as string | null | undefined) ?? undefined);
432 auditRepo(c, caller, moved, "repo.transfer", { from: `${repo.owner_login}/${repo.name}`, to: `${moved.owner_login}/${moved.name}` });
433 return c.json(repoOut(c, moved, (await dir.roleFor(p.account, moved)) ?? "read"), 202);
434});
435api.get("/repos/:owner/:repo/collaborators", async (c) => {
436 const { repo } = await loadRepo(c, P(c).owner, P(c).repo);
437 return c.json(paginate(c, (await c.get("dir").collaborators(repo.id)).map((x) => ({ ...userJson(c, x.account), permissions: permissionsOf(x.role), role_name: x.role }))));
438});
439api.put("/repos/:owner/:repo/collaborators/:login", async (c) => {
440 const { repo, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
441 const who = await c.get("dir").accountByLogin(c.req.param("login"));
442 if (!who) throw new HttpError(404, "user not found");
443 if (who.kind === "org") throw new HttpError(422, "an organization can't be a collaborator: add its members, or transfer the repository to it");
444 const b = await body<{ permission?: Role | "pull" | "push" }>(c).catch(() => ({ permission: "write" as Role }));
445 const map: Record<string, Role> = { pull: "read", push: "write" };
446 const role = map[b.permission ?? ""] ?? (b.permission as Role) ?? "write";
447 if (!(role in ROLE_LEVEL)) throw new HttpError(422, "permission must be pull, triage, push, maintain or admin");
448 // As on GitHub: someone new gets an invitation (201) and has access once they accept it; an
449 // existing collaborator's role changes at once (204).
450 const r = await c.get("dir").grantRepoAccess(repo, requireAccount(c), who, role);
451 if ("invitedUser" in r) {
452 auditRepo(c, caller, repo, "repo.invite", { login: who.login, role });
453 const inv = (await c.get("dir").invites({ repoId: repo.id, pending: true })).find((i) => i.id === r.id);
454 return c.json({ id: r.id, repository: { full_name: `${repo.owner_login}/${repo.name}`, name: repo.name, owner: { login: repo.owner_login } }, invitee: userJson(c, who), inviter: inv?.invitedBy ? { login: inv.invitedBy } : null, permissions: role, created_at: inv?.createdAt, expires_at: inv?.expiresAt, html_url: `${baseOf(c)}/settings/invitations` }, 201);
455 }
456 auditRepo(c, caller, repo, "repo.collaborator.set", { login: who.login, role });
457 return c.body(null, 204);
458});
459
460// Invitations to the caller, as on GitHub: repository invitations, and organization memberships
461// (pending until accepted). Accepting one gives access, so it needs a write token that isn't limited
462// to repositories.
463const myInvites = async (c: AppContext) => {
464 requireAccountScope(c, "read");
465 requireUnlimitedToken(c, "list invitations");
466 return c.get("dir").invitesFor(requireAccount(c));
467};
468const answer = async (c: AppContext, id: string, accept: boolean) => {
469 requireAccountScope(c, "write");
470 requireUnlimitedToken(c, accept ? "accept invitations" : "decline invitations");
471 const me = requireAccount(c);
472 const dir = c.get("dir");
473 await dir.answerInvite(id, me, accept);
474 c.executionCtx.waitUntil(dir.audit({ actorId: me.id, actorLogin: me.login, action: accept ? "invite.accept" : "invite.decline", detail: { id, via: "api" } }));
475};
476const repoInvitationJson = (c: AppContext, me: Account, i: Awaited<ReturnType<Directory["invitesFor"]>>[number]) => {
477 const [owner, name] = (i.repo ?? "/").split("/");
478 return { id: i.id, repository: { full_name: i.repo, name, owner: { login: owner } }, invitee: userJson(c, me), inviter: i.invitedBy ? { login: i.invitedBy } : null, permissions: i.role, created_at: i.createdAt, expires_at: i.expiresAt, html_url: `${baseOf(c)}/settings/invitations` };
479};
480api.get("/user/repository_invitations", async (c) => {
481 const me = requireAccount(c);
482 return c.json((await myInvites(c)).filter((i) => i.repoId && i.repo).map((i) => repoInvitationJson(c, me, i)));
483});
484api.patch("/user/repository_invitations/:id", async (c) => {
485 await answer(c, c.req.param("id"), true);
486 return c.body(null, 204);
487});
488api.delete("/user/repository_invitations/:id", async (c) => {
489 await answer(c, c.req.param("id"), false);
490 return c.body(null, 204);
491});
492const membershipJson = (c: AppContext, me: Account, org: string, role: string, state: "active" | "pending") => ({
493 url: `${baseOf(c)}/api/v3/user/memberships/orgs/${org}`,
494 state,
495 role: role === "owner" ? "admin" : role,
496 diffinery_role: role,
497 organization: { login: org, url: `${baseOf(c)}/api/v3/orgs/${org}` },
498 user: userJson(c, me),
499});
500const myMemberships = (c: AppContext) => {
501 requireAccountScope(c, "read");
502 requireUnlimitedToken(c, "list organization memberships");
503 return requireAccount(c);
504};
505api.get("/user/memberships/orgs", async (c) => {
506 const me = myMemberships(c);
507 const state = c.req.query("state");
508 const active = state === "pending" ? [] : (await c.get("dir").orgsFor(me.id)).map((o) => membershipJson(c, me, o.login, o.role, "active"));
509 const pending = state === "active" ? [] : (await myInvites(c)).filter((i) => i.org).map((i) => membershipJson(c, me, i.org!, i.role, "pending"));
510 return c.json([...pending, ...active]);
511});
512api.get("/user/memberships/orgs/:org", async (c) => {
513 const me = myMemberships(c);
514 const org = c.req.param("org").toLowerCase();
515 const active = (await c.get("dir").orgsFor(me.id)).find((o) => o.login.toLowerCase() === org);
516 if (active) return c.json(membershipJson(c, me, active.login, active.role, "active"));
517 const pending = (await myInvites(c)).find((i) => i.org?.toLowerCase() === org);
518 if (pending) return c.json(membershipJson(c, me, pending.org!, pending.role, "pending"));
519 throw new HttpError(404, "not found");
520});
521api.patch("/user/memberships/orgs/:org", async (c) => {
522 requireAccountScope(c, "write");
523 const me = myMemberships(c);
524 const b = await body<{ state?: string }>(c).catch(() => ({ state: undefined }));
525 if (b.state !== "active") throw new HttpError(422, 'state must be "active"');
526 const org = c.req.param("org").toLowerCase();
527 const pending = (await myInvites(c)).find((i) => i.org?.toLowerCase() === org);
528 if (!pending) {
529 const active = (await c.get("dir").orgsFor(me.id)).find((o) => o.login.toLowerCase() === org);
530 if (active) return c.json(membershipJson(c, me, active.login, active.role, "active"));
531 throw new HttpError(404, "no pending invitation to this organization");
532 }
533 await answer(c, pending.id, true);
534 return c.json(membershipJson(c, me, pending.org!, pending.role, "active"));
535});
536api.delete("/repos/:owner/:repo/collaborators/:login", async (c) => {
537 const { repo, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
538 const who = await c.get("dir").accountByLogin(c.req.param("login"));
539 if (who) {
540 await c.get("dir").setCollaborator(repo.id, who.id, null);
541 auditRepo(c, caller, repo, "repo.collaborator.remove", { login: who.login });
542 }
543 return c.body(null, 204);
544});
545
546// ---------------------------------------------------------------- git data
547
548api.get("/repos/:owner/:repo/branches", async (c) => {
549 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
550 const api = repoApi(baseOf(c), P(c).owner, P(c).repo);
551 let list = await stub.branches();
552 if (c.req.query("protected") !== undefined) list = list.filter((b) => b.protected === (c.req.query("protected") === "true"));
553 return c.json(paginate(c, list.map((b) => ({ name: b.name, commit: { sha: b.sha, url: `${api}/commits/${b.sha}` }, protected: b.protected, default: b.isDefault }))));
554});
555api.get("/repos/:owner/:repo/branches/:branch", async (c) => {
556 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
557 const name = c.req.param("branch");
558 const b = (await stub.branches()).find((x) => x.name === name);
559 if (!b) throw new HttpError(404, "Branch not found");
560 const api = repoApi(baseOf(c), P(c).owner, P(c).repo);
561 return c.json({
562 name,
563 commit: ghCommit(baseOf(c), P(c).owner, P(c).repo, await stub.commitInfo(b.sha)),
564 _links: { self: `${api}/branches/${encPath(name)}`, html: `${repoHtml(baseOf(c), P(c).owner, P(c).repo)}/tree/${encPath(name)}` },
565 protected: b.protected,
566 protection: { enabled: b.protected, required_status_checks: { enforcement_level: b.protected ? "non_admins" : "off", contexts: [], checks: [] } },
567 protection_url: `${api}/branches/${encPath(name)}/protection`,
568 });
569});
570api.get("/repos/:owner/:repo/tags", async (c) => {
571 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
572 const api = repoApi(baseOf(c), P(c).owner, P(c).repo);
573 const tags = (await stub.tags()).reverse();
574 return c.json(paginate(c, tags.map((t) => ({ name: t.name, zipball_url: `${api}/zipball/refs/tags/${encPath(t.name)}`, tarball_url: `${api}/tarball/refs/tags/${encPath(t.name)}`, commit: { sha: t.target, url: `${api}/commits/${t.target}` }, node_id: nodeId("Ref", `${P(c).owner}/${P(c).repo}/refs/tags/${t.name}`) }))));
575});
576// GET /git/refs/<ref>: one ref when the path names it exactly, else every ref under it (GitHub's legacy form).
577api.get("/repos/:owner/:repo/git/refs/*", async (c) => {
578 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
579 const name = `refs/${decodePath(c.req.path.split("/git/refs/")[1] ?? "")}`.replace(/\/$/, "");
580 const all = await stub.refsWithTypes("refs/");
581 const exact = all.find((r) => r.ref === name);
582 if (exact) return c.json(refJson(c, exact));
583 const matches = all.filter((r) => r.ref.startsWith(`${name}/`) && !r.ref.startsWith("refs/pull/"));
584 if (!matches.length) throw new HttpError(404, "Not Found");
585 return c.json(paginate(c, matches.map((r) => refJson(c, r)), 100));
586});
587api.post("/repos/:owner/:repo/git/refs", async (c) => {
588 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
589 const b = await body<{ ref: string; sha: string }>(c);
590 if (typeof b.ref !== "string" || !b.ref.startsWith("refs/") || b.ref.split("/").length < 3) throw new HttpError(422, "Reference name must start with 'refs/' and have at least two slashes.", { errors: [{ resource: "Reference", code: "invalid", field: "ref" }] });
591 if (typeof b.sha !== "string") throw new HttpError(422, "sha is required", { errors: [{ resource: "Reference", code: "missing_field", field: "sha" }] });
592 await stub.createRef(b.ref, b.sha, caller);
593 return c.json(refJson(c, { ref: b.ref, sha: b.sha, type: (await stub.objectType(b.sha)) ?? "commit" }), 201);
594});
595api.patch("/repos/:owner/:repo/git/refs/*", async (c) => {
596 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
597 const ref = `refs/${decodePath(c.req.path.split("/git/refs/")[1] ?? "")}`;
598 const b = await body<{ sha: string; force?: boolean }>(c);
599 if (typeof b.sha !== "string") throw new HttpError(422, "sha is required", { errors: [{ resource: "Reference", code: "missing_field", field: "sha" }] });
600 await stub.updateRef(ref, b.sha, !!b.force, caller);
601 return c.json(refJson(c, { ref, sha: b.sha, type: (await stub.objectType(b.sha)) ?? "commit" }));
602});
603api.delete("/repos/:owner/:repo/git/refs/*", async (c) => {
604 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
605 await stub.deleteRef(`refs/${decodePath(c.req.path.split("/git/refs/")[1] ?? "")}`, caller);
606 return c.body(null, 204);
607});
608api.get("/repos/:owner/:repo/commits", async (c) => {
609 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
610 const p = pageOf(c);
611 const rev = c.req.query("sha") ?? "HEAD";
612 if (!(await stub.resolve(rev))) {
613 if (!(await stub.resolve("HEAD"))) throw new HttpError(409, "Git Repository is empty.");
614 throw new HttpError(404, `No commit found for SHA: ${rev}`);
615 }
616 let list = await stub.log(rev, { path: c.req.query("path"), limit: p.perPage + 1, skip: p.offset });
617 const author = c.req.query("author")?.toLowerCase();
618 if (author) list = list.filter((x) => x.author.email.toLowerCase() === author || x.author.name.toLowerCase() === author || x.author.email.toLowerCase().startsWith(`${author}@`));
619 const since = c.req.query("since") ? Date.parse(c.req.query("since")!) / 1000 : null;
620 const until = c.req.query("until") ? Date.parse(c.req.query("until")!) / 1000 : null;
621 if (since) list = list.filter((x) => x.committer.timestamp >= since);
622 if (until) list = list.filter((x) => x.committer.timestamp <= until);
623 setLinks(c, p, null, list.length > p.perPage);
624 return c.json(list.slice(0, p.perPage).map((x) => ghCommit(baseOf(c), P(c).owner, P(c).repo, x)));
625});
626api.get("/repos/:owner/:repo/commits/:ref", async (c) => {
627 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
628 const sha = await stub.resolve(c.req.param("ref"));
629 if (!sha) throw new HttpError(422, `No commit found for SHA: ${c.req.param("ref")}`);
630 const x = await stub.commitWithDiff(sha);
631 const files = x.files.map((f) => ghFile(baseOf(c), P(c).owner, P(c).repo, sha, f));
632 return c.json({ ...ghCommit(baseOf(c), P(c).owner, P(c).repo, x), stats: { total: x.additions + x.deletions, additions: x.additions, deletions: x.deletions }, files, truncated: x.truncated, total_files: x.totalFiles });
633});
634api.get("/repos/:owner/:repo/compare/:spec{.+}", async (c) => {
635 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
636 const spec = c.req.param("spec");
637 const [base, head] = spec.includes("...") ? spec.split("...") : spec.split("..");
638 if (!base || !head) throw new HttpError(422, "use base...head");
639 const r = await stub.compare(base.includes(":") ? base.split(":")[1]! : base, head.includes(":") ? head.split(":")[1]! : head);
640 const b = baseOf(c);
641 const { owner, repo } = P(c);
642 const api = repoApi(b, owner, repo);
643 const html = repoHtml(b, owner, repo);
644 const commits = paginate(c, r.commits, 250);
645 return c.json({
646 url: `${api}/compare/${spec}`,
647 html_url: `${html}/compare/${spec}`,
648 permalink_url: `${html}/compare/${r.baseSha}...${r.headSha}`,
649 diff_url: `${html}/compare/${spec}.diff`,
650 patch_url: `${html}/compare/${spec}.patch`,
651 base_commit: ghCommit(b, owner, repo, await stub.commitInfo(r.baseSha)),
652 merge_base_commit: r.mergeBase ? ghCommit(b, owner, repo, await stub.commitInfo(r.mergeBase)) : null,
653 status: r.aheadBy && r.behindBy ? "diverged" : r.aheadBy ? "ahead" : r.behindBy ? "behind" : "identical",
654 ahead_by: r.aheadBy,
655 behind_by: r.behindBy,
656 total_commits: r.aheadBy,
657 commits: commits.map((x) => ghCommit(b, owner, repo, x)),
658 files: r.files.map((f) => ghFile(b, owner, repo, r.headSha, f)),
659 // Diffinery: the same comparison in its own words.
660 base_sha: r.baseSha,
661 head_sha: r.headSha,
662 merge_base: r.mergeBase,
663 });
664});
665// Contents: files come back base64-encoded with GitHub's links; `Accept: application/vnd.github.raw` returns the bytes.
666async function getContents(c: AppContext) {
667 const { stub, repo } = await loadRepo(c, P(c).owner, P(c).repo);
668 const path = decodePath(c.req.path.split("/contents/")[1] ?? "").replace(/^\/+|\/+$/g, "");
669 const ref = c.req.query("ref") || repo.default_branch;
670 const sha = await stub.resolve(ref);
671 if (!sha) throw new HttpError(404, `No commit found for the ref ${ref}`);
672 const tree = await stub.tree(sha, path);
673 if (tree) return c.json(tree.items.map((i) => contentJson(c, ref, i.path, i.oid, i.size ?? 0, i.type === "tree" ? "dir" : i.type === "commit" ? "submodule" : i.mode === "120000" ? "symlink" : "file")));
674 const blob = await stub.blob(sha, path);
675 if (!blob) throw new HttpError(404, "Not Found");
676 if (/application\/vnd\.github(\.v3)?\.raw/.test(c.req.header("accept") ?? "")) {
677 return new Response(blob.content, { headers: { "content-type": "text/plain; charset=utf-8", "x-content-type-options": "nosniff", "content-security-policy": "sandbox", etag: `"${blob.oid}"` } });
678 }
679 const type = blob.mode === "120000" ? "symlink" : "file";
680 return c.json({ ...contentJson(c, ref, path, blob.oid, blob.size, type), ...(type === "symlink" ? { target: new TextDecoder().decode(blob.content) } : {}), encoding: "base64", content: b64(blob.content).replace(/(.{60})/g, "$1\n"), commit: blob.sha });
681}
682api.get("/repos/:owner/:repo/contents/*", getContents);
683api.get("/repos/:owner/:repo/contents", getContents);
684api.put("/repos/:owner/:repo/contents/*", async (c) => {
685 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
686 const path = decodeURIComponent(c.req.path.split("/contents/")[1] ?? "");
687 const b = await body<{ message: string; content: string; branch?: string; sha?: string; committer?: { name: string; email: string }; author?: { name: string; email: string } }>(c);
688 if (typeof b.content !== "string") throw new HttpError(422, "content is required (base64)", { errors: [{ resource: "Contents", code: "missing_field", field: "content" }] });
689 let bytes: Uint8Array;
690 try {
691 bytes = fromB64(b.content.replace(/\s+/g, ""));
692 } catch {
693 throw new HttpError(422, "content is not valid Base64", { errors: [{ resource: "Contents", code: "invalid", field: "content" }] });
694 }
695 const sig = (s?: { name: string; email: string }) => (s && typeof s.name === "string" && typeof s.email === "string" ? { name: s.name, email: s.email } : undefined);
696 const res = await stub.putContents({ path, content: bytes, message: b.message, branch: b.branch, sha: b.sha, author: sig(b.author), committer: sig(b.committer) ?? sig(b.author) }, caller);
697 const ref = b.branch || (await loadRepo(c, P(c).owner, P(c).repo)).repo.default_branch;
698 return c.json({ content: contentJson(c, ref, path, res.blob.sha, res.blob.size, "file"), commit: gitCommitJson(c, res.commit) }, res.created ? 201 : 200);
699});
700api.delete("/repos/:owner/:repo/contents/*", async (c) => {
701 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
702 const path = decodeURIComponent(c.req.path.split("/contents/")[1] ?? "");
703 const b = await body<{ message: string; branch?: string; sha?: string; committer?: { name: string; email: string }; author?: { name: string; email: string } }>(c);
704 const commit = await stub.deleteContents({ path, message: b.message, branch: b.branch, sha: b.sha, author: b.author, committer: b.committer ?? b.author }, caller);
705 return c.json({ content: null, commit: gitCommitJson(c, commit) });
706});
707
708/** Agent-friendly multi-file commit without a Git client. */
709api.post("/repos/:owner/:repo/diffinery/commits", async (c) => {
710 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
711 const b = await body<{ branch: string; message: string; base?: string; expected_head_sha?: string; allow_secrets?: string; files: Array<{ path: string; content?: string; encoding?: "utf-8" | "base64"; delete?: boolean; mode?: "100644" | "100755" }> }>(c);
712 if (!Array.isArray(b.files) || b.files.length === 0) throw new HttpError(422, "files is required");
713 const changes = b.files.map((f) => (f.delete ? { path: f.path, delete: true } : { path: f.path, mode: f.mode, content: f.encoding === "base64" ? fromB64(f.content ?? "") : new TextEncoder().encode(f.content ?? "") }));
714 return c.json(await stub.commitFiles({ branch: b.branch, message: b.message, changes, createBranchFrom: b.base, expectedHeadSha: b.expected_head_sha, allowSecrets: typeof b.allow_secrets === "string" ? b.allow_secrets : undefined }, caller), 201);
715});
716
717api.get("/repos/:owner/:repo/raw/:ref/*", async (c) => {
718 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
719 const path = decodeURIComponent(c.req.path.split(`/raw/${c.req.param("ref")}/`)[1] ?? "");
720 const blob = await stub.blob(c.req.param("ref"), path);
721 if (!blob) throw new HttpError(404, "not found");
722 return new Response(blob.content, { headers: { "content-type": blob.binary ? "application/octet-stream" : "text/plain; charset=utf-8", "x-content-type-options": "nosniff", "content-security-policy": "sandbox" } });
723});
724
725// ---------------------------------------------------------------- branch protection
726
727api.get("/repos/:owner/:repo/branches/:branch/protection", async (c) => {
728 const { stub } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
729 const rule = (await stub.listProtections()).find((p) => p.pattern === c.req.param("branch"));
730 if (!rule) throw new HttpError(404, "branch not protected");
731 return c.json(rule);
732});
733api.put("/repos/:owner/:repo/branches/:branch/protection", async (c) => {
734 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
735 if (caller.kind === "agent") throw new HttpError(403, "agents cannot change branch protection");
736 const rules = await body<ProtectionRules>(c);
737 await stub.setProtection(c.req.param("branch"), rules, caller);
738 auditRepo(c, caller, repo, "repo.protection.set", { pattern: c.req.param("branch") });
739 return c.json({ pattern: c.req.param("branch"), rules });
740});
741api.delete("/repos/:owner/:repo/branches/:branch/protection", async (c) => {
742 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
743 if (caller.kind === "agent") throw new HttpError(403, "agents cannot change branch protection");
744 await stub.setProtection(c.req.param("branch"), null, caller);
745 auditRepo(c, caller, repo, "repo.protection.delete", { pattern: c.req.param("branch") });
746 return c.body(null, 204);
747});
748
749// ---------------------------------------------------------------- issues & pulls
750
751/** Label names from a GitHub payload (strings or `{ name }` objects). */
752const labelNames = (v: unknown): string[] | undefined => (Array.isArray(v) ? v.map((l) => (typeof l === "string" ? l : String((l as { name?: unknown })?.name ?? ""))).filter(Boolean) : undefined);
753/** Assignee logins from `assignees` or the older singular `assignee`. */
754const assigneeLogins = (b: { assignees?: unknown; assignee?: unknown }): string[] | undefined =>
755 Array.isArray(b.assignees) ? b.assignees.map(String) : b.assignee === null ? [] : typeof b.assignee === "string" ? [b.assignee] : undefined;
756const sortParam = (v: string | undefined) => (v === "updated" || v === "comments" || v === "created" ? v : undefined);
757
758for (const kind of ["issues", "pulls"] as const) {
759 api.get(`/repos/:owner/:repo/${kind}`, async (c) => {
760 const { stub, repo } = await loadRepo(c, P(c).owner, P(c).repo);
761 const p = pageOf(c);
762 const q = (k: string) => c.req.query(k) || undefined;
763 const labels = q("labels")?.split(",").map((l) => l.trim()).filter(Boolean);
764 const head = q("head");
765 // `milestone`: a milestone number, `none` or `*` (any), as on GitHub.
766 const ms = q("milestone");
767 if (ms && !/^(\d+|none|\*)$/.test(ms)) throw new HttpError(422, "milestone must be a milestone number, none or *");
768 const res = await stub.issues({
769 milestone: ms === "none" || ms === "*" ? ms : ms ? Number(ms) : undefined,
770 kind: kind === "pulls" ? "pull" : undefined,
771 state: (q("state") as "open" | "closed" | "all") ?? "open",
772 labels,
773 author: q("creator"),
774 assignee: q("assignee"),
775 since: q("since"),
776 head: head?.includes(":") ? head.slice(head.indexOf(":") + 1) : head,
777 base: q("base"),
778 sort: kind === "pulls" && q("sort") === "popularity" ? "comments" : sortParam(q("sort")),
779 direction: q("direction") === "asc" ? "asc" : q("direction") === "desc" ? "desc" : undefined,
780 q: q("q"),
781 limit: p.perPage,
782 offset: p.offset,
783 });
784 c.header("x-total-count", String(res.total));
785 setLinks(c, p, res.total);
786 return c.json(kind === "pulls" ? await pullsOut(c, repo, stub, res.items) : await issuesOut(c, repo, stub, res.items));
787 });
788}
789api.post("/repos/:owner/:repo/issues", async (c) => {
790 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
791 const b = await body<{ title: string; body?: string; labels?: unknown; assignees?: unknown; assignee?: unknown }>(c);
792 if (typeof b.title !== "string" && typeof b.title !== "number") throw new HttpError(422, "title is required", { errors: [{ resource: "Issue", code: "missing_field", field: "title" }] });
793 const issue = await stub.createIssue({ title: String(b.title), body: b.body ?? undefined, labels: labelNames(b.labels), assignees: assigneeLogins(b) }, caller);
794 return c.json((await issuesOut(c, repo, stub, [issue]))[0], 201);
795});
796api.get("/repos/:owner/:repo/issues/:number", async (c) => {
797 const { stub, repo } = await loadRepo(c, P(c).owner, P(c).repo);
798 return c.json((await issuesOut(c, repo, stub, [(await stub.issue(num(c))).issue]))[0]);
799});
800api.patch("/repos/:owner/:repo/issues/:number", async (c) => {
801 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
802 const b = await body<{ title?: string; body?: string | null; state?: "open" | "closed"; state_reason?: string | null; labels?: unknown; assignees?: unknown; assignee?: unknown; milestone?: unknown }>(c);
803 // `milestone` (a number or null) is checked before anything is saved. As with labels and assignees,
804 // it is silently dropped for people without triage access.
805 if (b.milestone !== undefined && b.milestone !== null && (typeof b.milestone !== "number" || !Number.isInteger(b.milestone))) throw new HttpError(422, "milestone must be a milestone number or null");
806 const milestone = atLeast(caller.role, "triage") ? (b.milestone as number | null | undefined) : undefined;
807 if (typeof milestone === "number" && !(await stub.milestones("all")).some((m) => m.number === milestone)) throw new HttpError(422, "Validation Failed", { errors: [{ resource: "Issue", code: "invalid", field: "milestone" }] });
808 let issue = await stub.updateIssue(num(c), { title: b.title, body: b.body ?? undefined, state: b.state, stateReason: b.state_reason ?? undefined, labels: labelNames(b.labels), assignees: assigneeLogins(b) }, caller);
809 if (milestone !== undefined) {
810 await stub.setIssueMilestone(num(c), milestone);
811 issue = (await stub.issue(num(c))).issue;
812 }
813 return c.json((await issuesOut(c, repo, stub, [issue]))[0]);
814});
815api.get("/repos/:owner/:repo/issues/:number/comments", async (c) => {
816 const { stub, repo } = await loadRepo(c, P(c).owner, P(c).repo);
817 const n = num(c);
818 const { issue, comments } = await stub.issue(n);
819 const since = c.req.query("since");
820 const list = paginate(c, comments.filter((x) => !x.reviewId && (!since || x.updatedAt >= since)));
821 const x = await issueCtx(c, repo, stub, [], list.map((cm) => `comment:${cm.id}`));
822 return c.json(list.map((cm) => ghComment(x, n, issue.kind === "pull", cm)));
823});
824api.post("/repos/:owner/:repo/issues/:number/comments", async (c) => {
825 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
826 const n = num(c);
827 const b = await body<{ body: string }>(c);
828 if (typeof b.body !== "string") throw new HttpError(422, "body is required", { errors: [{ resource: "IssueComment", code: "missing_field", field: "body" }] });
829 const cm = await stub.addComment(n, b.body, caller);
830 const { issue } = await stub.issue(n);
831 return c.json(ghComment(await issueCtx(c, repo, stub, []), n, issue.kind === "pull", cm), 201);
832});
833api.patch("/repos/:owner/:repo/issues/comments/:id", async (c) => {
834 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
835 const b = await body<{ body: string }>(c);
836 if (typeof b.body !== "string" || !b.body.trim()) throw new HttpError(422, "body is required", { errors: [{ resource: "IssueComment", code: "missing_field", field: "body" }] });
837 await stub.editComment(c.req.param("id"), b.body, caller);
838 const found = await stub.comment(c.req.param("id"));
839 return c.json(ghComment(await issueCtx(c, repo, stub, [], [`comment:${found.comment.id}`]), found.number, found.isPull, found.comment));
840});
841api.get("/repos/:owner/:repo/labels", async (c) => {
842 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
843 return c.json(paginate(c, (await stub.labelRows()).map((l) => ghLabel(baseOf(c), P(c).owner, P(c).repo, l))));
844});
845api.post("/repos/:owner/:repo/labels", async (c) => {
846 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "triage");
847 const b = await body<{ name: string; color?: string; description?: string }>(c);
848 return c.json(ghLabel(baseOf(c), P(c).owner, P(c).repo, await stub.createLabel(b, caller)), 201);
849});
850
851api.post("/repos/:owner/:repo/pulls", async (c) => {
852 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "write");
853 const b = await body<{ title: string; body?: string; head: string; base?: string; draft?: boolean; intent?: string; reviewers?: string[] }>(c);
854 if (typeof b.head !== "string" || !b.head) throw new HttpError(422, "head is required", { errors: [{ resource: "PullRequest", code: "missing_field", field: "head" }] });
855 const issue = await stub.createPull({ ...b, head: b.head.includes(":") ? b.head.split(":")[1]! : b.head }, caller);
856 return c.json((await pullsOut(c, repo, stub, [issue]))[0], 201);
857});
858api.get("/repos/:owner/:repo/pulls/:number", async (c) => {
859 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
860 return c.json(await pullDetail(c, repo, stub, num(c), caller));
861});
862api.patch("/repos/:owner/:repo/pulls/:number", async (c) => {
863 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
864 const b = await body<{ title?: string; body?: string | null; state?: "open" | "closed"; draft?: boolean }>(c);
865 // `draft` is a Diffinery extension (GitHub only offers it through GraphQL).
866 if (typeof b.draft === "boolean") await stub.setPullDraft(num(c), b.draft, caller);
867 const issue = b.title !== undefined || b.body !== undefined || b.state !== undefined ? await stub.updateIssue(num(c), { title: b.title, body: b.body ?? undefined, state: b.state }, caller) : (await stub.issue(num(c))).issue;
868 if (issue.kind !== "pull") throw new HttpError(404, "not a pull request");
869 return c.json((await pullsOut(c, repo, stub, [issue]))[0]);
870});
871api.get("/repos/:owner/:repo/pulls/:number/files", async (c) => {
872 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
873 const res = await stub.pullFiles(num(c));
874 return c.json(paginate(c, res.files.map((f) => ({ ...ghFile(baseOf(c), P(c).owner, P(c).repo, res.headSha, f), binary: f.binary }))));
875});
876api.get("/repos/:owner/:repo/pulls/:number/commits", async (c) => {
877 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
878 return c.json(paginate(c, (await stub.pullCommits(num(c))).map((x) => ghCommit(baseOf(c), P(c).owner, P(c).repo, x)), 250));
879});
880// GitHub clients (Accept: application/vnd.github...) get GitHub's "is it merged" answer: 204 or 404.
881// Other clients get Diffinery's mergeability report: blockers, approvals, checks and the merge queue.
882api.get("/repos/:owner/:repo/pulls/:number/merge", async (c) => {
883 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo);
884 const n = num(c);
885 if ((c.req.header("accept") ?? "").includes("application/vnd.github")) {
886 const { issue } = await stub.issue(n);
887 if (issue.pull?.merged) return c.body(null, 204);
888 throw new HttpError(404, "Not Found");
889 }
890 return c.json(await stub.mergeability(n, caller));
891});
892api.put("/repos/:owner/:repo/pulls/:number/merge", async (c) => {
893 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
894 const b = await body<{ merge_method?: "merge" | "squash" | "rebase"; commit_title?: string; commit_message?: string; sha?: string; delete_branch?: boolean; bypass_merge_queue?: boolean; bypass_rules?: boolean }>(c).catch(() => ({}) as Record<string, undefined>);
895 const r = await stub.mergePull(num(c), { method: b.merge_method, title: b.commit_title, message: b.commit_message, expectedHeadSha: b.sha, deleteBranch: b.delete_branch, bypassMergeQueue: b.bypass_merge_queue, bypassRules: b.bypass_rules }, caller);
896 return c.json({ ...r, message: "Pull Request successfully merged" });
897});
898
899// Merge queue (GitHub exposes it through GraphQL only; these follow its REST conventions).
900const queueJson = (e: QueueEntry) => ({
901 number: e.number,
902 title: e.title,
903 base_ref: e.base,
904 position: e.position,
905 state: e.state,
906 head_sha: e.headSha,
907 merge_method: e.method,
908 delete_branch: e.deleteBranch,
909 enqueued_by: { login: e.enqueuedBy.login },
910 enqueued_at: e.enqueuedAt,
911 merge_group: e.groupSha ? { head_sha: e.groupSha, head_ref: e.groupRef, base_sha: e.parentSha, built_at: e.builtAt } : null,
912 checks: e.checks,
913});
914api.get("/repos/:owner/:repo/merge-queue/:branch{.+}", async (c) => {
915 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
916 const branch = c.req.param("branch");
917 const settings = await stub.mergeQueueSettings(branch);
918 return c.json({ branch, enabled: !!settings, settings, entries: (await stub.mergeQueue(branch)).map(queueJson) });
919});
920api.put("/repos/:owner/:repo/pulls/:number/merge-queue", async (c) => {
921 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
922 const b = await body<{ merge_method?: "merge" | "squash" | "rebase"; delete_branch?: boolean }>(c).catch(() => ({}) as Record<string, undefined>);
923 const r = await stub.enqueuePull(num(c), { method: b.merge_method, deleteBranch: b.delete_branch }, caller);
924 return c.json({ state: r.state, entry: r.entry ? queueJson(r.entry) : null, merge_commit_sha: r.mergeCommit ?? null, reason: r.reason ?? null }, r.state === "queued" ? 201 : 200);
925});
926api.delete("/repos/:owner/:repo/pulls/:number/merge-queue", async (c) => {
927 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
928 await stub.dequeuePull(num(c), caller);
929 return c.body(null, 204);
930});
931// Auto-merge (GitHub's enablePullRequestAutoMerge and disablePullRequestAutoMerge, which it exposes through GraphQL only).
932api.put("/repos/:owner/:repo/pulls/:number/auto-merge", async (c) => {
933 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
934 const b = await body<{ merge_method?: string; commit_title?: string; commit_message?: string; delete_branch?: unknown; sha?: unknown }>(c).catch(() => ({}) as Record<string, undefined>);
935 if (b.delete_branch !== undefined && typeof b.delete_branch !== "boolean") throw new HttpError(422, "delete_branch must be a boolean", { errors: [{ resource: "PullRequest", code: "invalid", field: "delete_branch" }] });
936 if (b.sha !== undefined && typeof b.sha !== "string") throw new HttpError(422, "sha must be a string", { errors: [{ resource: "PullRequest", code: "invalid", field: "sha" }] });
937 const r = await stub.enableAutoMerge(num(c), { method: b.merge_method, commitTitle: b.commit_title, commitMessage: b.commit_message, deleteBranch: b.delete_branch, expectedHeadSha: b.sha || undefined }, caller);
938 return c.json({ state: r.state, auto_merge: ghAutoMerge(baseOf(c), r.autoMerge), merge_commit_sha: r.mergeCommit ?? null });
939});
940api.delete("/repos/:owner/:repo/pulls/:number/auto-merge", async (c) => {
941 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
942 await stub.disableAutoMerge(num(c), caller);
943 return c.body(null, 204);
944});
945api.get("/repos/:owner/:repo/pulls/:number/reviews", async (c) => {
946 const { stub, repo } = await loadRepo(c, P(c).owner, P(c).repo);
947 const n = num(c);
948 const x = await issueCtx(c, repo, stub, []);
949 return c.json(paginate(c, (await stub.issue(n)).reviews.map((r) => ghReview(x, n, r))));
950});
951api.post("/repos/:owner/:repo/pulls/:number/reviews", async (c) => {
952 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
953 const n = num(c);
954 const b = await body<{ event?: "APPROVE" | "REQUEST_CHANGES" | "COMMENT"; body?: string; commit_id?: string; comments?: Array<{ path: string; line?: number; position?: number; side?: "LEFT" | "RIGHT"; body: string }> }>(c);
955 if (b.event && !["APPROVE", "REQUEST_CHANGES", "COMMENT"].includes(b.event)) throw new HttpError(422, "event must be APPROVE, REQUEST_CHANGES or COMMENT", { errors: [{ resource: "PullRequestReview", code: "invalid", field: "event" }] });
956 const comments = Array.isArray(b.comments) ? b.comments.map((cm) => ({ path: String(cm.path), line: Number(cm.line ?? cm.position), side: cm.side, body: String(cm.body ?? "") })) : undefined;
957 if (comments?.some((cm) => !cm.path || !Number.isInteger(cm.line) || cm.line < 1 || !cm.body)) throw new HttpError(422, "each review comment needs a path, a line and a body", { errors: [{ resource: "PullRequestReviewComment", code: "invalid", field: "comments" }] });
958 const r = await stub.submitReview(n, { event: b.event ?? "COMMENT", body: b.body, comments }, caller);
959 return c.json(ghReview(await issueCtx(c, repo, stub, []), n, r), 201);
960});
961api.get("/repos/:owner/:repo/pulls/:number/comments", async (c) => {
962 const { stub, repo } = await loadRepo(c, P(c).owner, P(c).repo);
963 const n = num(c);
964 const list = paginate(c, (await stub.issue(n)).comments.filter((x) => x.reviewId));
965 const x = await issueCtx(c, repo, stub, [], list.map((cm) => `review_comment:${cm.id}`));
966 return c.json(list.map((cm) => ghReviewComment(x, n, cm)));
967});
968api.post("/repos/:owner/:repo/pulls/:number/requested_reviewers", async (c) => {
969 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
970 const n = num(c);
971 const b = await body<{ reviewers?: string[]; team_reviewers?: string[] }>(c);
972 if (b.team_reviewers?.length) throw new HttpError(422, "team reviewers are not supported; request people by login");
973 await stub.requestReviewers(n, (b.reviewers ?? []).map(String), caller);
974 return c.json((await pullsOut(c, repo, stub, [(await stub.issue(n)).issue]))[0], 201);
975});
976
977// ---------------------------------------------------------------- checks (for plugins and external CI)
978
979api.get("/repos/:owner/:repo/commits/:ref/check-runs", async (c) => {
980 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
981 const sha = await stub.resolve(c.req.param("ref"));
982 if (!sha) throw new HttpError(404, "ref not found");
983 let runs = await stub.checks(sha);
984 const name = c.req.query("check_name");
985 const status = c.req.query("status");
986 if (name) runs = runs.filter((r) => r.name === name);
987 if (status) runs = runs.filter((r) => r.status === status);
988 const page = paginate(c, runs);
989 return c.json({ total_count: runs.length, check_runs: page.map((r) => checkRunJson(c, r)) });
990});
991api.post("/repos/:owner/:repo/check-runs", async (c) => {
992 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
993 const b = await body<{ name: string; head_sha: string; status?: "queued" | "in_progress" | "completed"; conclusion?: string; details_url?: string; external_id?: string; started_at?: string; completed_at?: string; output?: { title?: string; summary?: string; text?: string; annotations?: unknown[] } }>(c);
994 if (typeof b.name !== "string" || !b.name || b.name.length > 255) throw new HttpError(422, "name is required", { errors: [{ resource: "CheckRun", code: "missing_field", field: "name" }] });
995 if (/^diffinery-(actions|agent-review)/i.test(caller.login)) throw new HttpError(403, "this account can't report check runs");
996 const sha = typeof b.head_sha === "string" ? await stub.resolve(b.head_sha) : null;
997 if (!sha) throw new HttpError(422, "head_sha is not a commit in this repository", { errors: [{ resource: "CheckRun", code: "invalid", field: "head_sha" }] });
998 // Shown as a link on the pull request, so only web addresses (as the web UI already insists).
999 if (b.details_url !== undefined && b.details_url !== null && (typeof b.details_url !== "string" || b.details_url.length > 2000 || !/^https?:\/\/[^\s]+$/i.test(b.details_url))) throw new HttpError(422, "details_url must be an http or https URL", { errors: [{ resource: "CheckRun", code: "invalid", field: "details_url" }] });
1000 const status = b.conclusion ? "completed" : (b.status ?? "queued");
1001 const { annotations: _a, text: _t, ...output } = b.output ?? {};
1002 let check = await stub.upsertCheck({ sha, name: b.name, status, conclusion: b.conclusion, detailsUrl: b.details_url, output: b.output ? output : undefined, app: caller.login, creator: { id: caller.id, login: caller.login, kind: caller.kind } });
1003 if (b.external_id !== undefined || b.output?.text !== undefined || Array.isArray(b.output?.annotations)) check = await stub.updateCheckRun(check.id, { external_id: b.external_id, output: b.output }, caller);
1004 return c.json(checkRunJson(c, check), 201);
1005});
1006
1007// ---------------------------------------------------------------- actions
1008
1009const runJson = (c: AppContext, owner: string, repo: string, r: RunInfo) => ghRun(baseOf(c), owner, repo, r);
1010
1011api.get("/repos/:owner/:repo/actions/workflows", async (c) => {
1012 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
1013 const wfs = await stub.workflows();
1014 return c.json({ total_count: wfs.length, workflows: wfs.map((w) => ({ id: w.path, name: w.name, path: w.path, state: w.errors.length ? "invalid" : "active", errors: w.errors, triggers: w.triggers })) });
1015});
1016api.post("/repos/:owner/:repo/actions/workflows/:workflow/dispatches", async (c) => {
1017 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
1018 const b = await body<{ ref: string; inputs?: Record<string, unknown> }>(c);
1019 const run = await stub.dispatchWorkflow(decodeURIComponent(c.req.param("workflow")), b.ref, b.inputs ?? {}, caller);
1020 return c.json({ run_id: run.id, html_url: `${c.env.PUBLIC_URL}/${P(c).owner}/${P(c).repo}/actions/runs/${run.id}` }, 201);
1021});
1022// Self-hosted runners poll this to pick up `runs-on: [self-hosted, ...]` jobs (see `diffinery runner`).
1023// Only a registered runner claims, with its own token and the labels it registered with. A person's
1024// token can't: it would sit on the runner machine where the jobs it runs could read it.
1025api.post("/repos/:owner/:repo/actions/runners/claim", async (c) => {
1026 const p = c.get("principal");
1027 if (p.type === "repo-token" && p.token.startsWith("drn_")) {
1028 const repo = await c.get("dir").repo(P(c).owner, P(c).repo);
1029 if (!repo || repo.id !== p.repoId) throw new HttpError(401, "this runner token belongs to another repository");
1030 const job = await repoStub(c.env, repo.id).claimJobAsRunner(p.token);
1031 if (!job) return c.body(null, 204);
1032 return c.json({ job_id: job.jobId, run_id: job.runId, name: job.name, token: job.token, api_url: new URL(c.req.url).origin });
1033 }
1034 await loadRepo(c, P(c).owner, P(c).repo, "admin");
1035 throw new HttpError(403, `personal tokens can't claim jobs; register this runner: run \`diffinery runner -R ${P(c).owner}/${P(c).repo}\` signed in with an up-to-date CLI, or pass --registration-token (see /docs/actions/runners)`);
1036});
1037// GitHub's runner registration token: an hour to register runners (`diffinery runner --registration-token`).
1038api.post("/repos/:owner/:repo/actions/runners/registration-token", async (c) => {
1039 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
1040 if (c.get("principal").type !== "account") throw new HttpError(403, "only repository admins can add self-hosted runners");
1041 const t = await stub.runnerRegistrationToken(caller);
1042 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: caller.id, actorLogin: caller.login, action: "runner.registration_token", target: `${P(c).owner}/${P(c).repo}` }));
1043 return c.json(t, 201);
1044});
1045// A machine trades a registration token for its own runner token. The registration token is the only credential.
1046api.post("/repos/:owner/:repo/actions/runners/register", async (c) => {
1047 const b = await body<{ registration_token?: unknown; name?: unknown; labels?: unknown; ephemeral?: unknown }>(c);
1048 if (typeof b.registration_token !== "string" || !b.registration_token.startsWith("drg_")) throw new HttpError(401, "invalid or expired registration token");
1049 // A repository that doesn't exist answers like a wrong token, so the endpoint can't probe for private names.
1050 const repo = await c.get("dir").repo(P(c).owner, P(c).repo);
1051 if (!repo) throw new HttpError(401, "invalid or expired registration token");
1052 const labels = Array.isArray(b.labels) ? b.labels.map(String) : [];
1053 const { registeredBy, ...runner } = await repoStub(c.env, repo.id).registerRunner(b.registration_token, typeof b.name === "string" ? b.name : "runner", labels, b.ephemeral === true);
1054 c.executionCtx.waitUntil(c.get("dir").audit({ actorLogin: registeredBy, action: "runner.register", target: `${repo.owner_login}/${repo.name}`, detail: { id: runner.id, name: runner.name, labels: runner.labels, ephemeral: runner.ephemeral } }));
1055 return c.json(runner, 201);
1056});
1057api.get("/repos/:owner/:repo/actions/runners", async (c) => {
1058 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
1059 const runners = await stub.runners(caller);
1060 return c.json({ total_count: runners.length, runners });
1061});
1062api.delete("/repos/:owner/:repo/actions/runners/:id", async (c) => {
1063 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
1064 await stub.deleteRunner(Number(c.req.param("id")), caller);
1065 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: caller.id, actorLogin: caller.login, action: "runner.remove", target: `${P(c).owner}/${P(c).repo}`, detail: { id: Number(c.req.param("id")) } }));
1066 return c.body(null, 204);
1067});
1068api.get("/repos/:owner/:repo/actions/runs", async (c) => {
1069 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
1070 const perPage = Math.min(Math.max(Math.trunc(Number(c.req.query("per_page") ?? 25)) || 25, 1), 100);
1071 const page = Math.min(Math.max(Math.trunc(Number(c.req.query("page") ?? 1)) || 1, 1), 1000);
1072 const res = await stub.runs({ workflow: c.req.query("workflow"), branch: c.req.query("branch"), status: c.req.query("status"), event: c.req.query("event"), sha: c.req.query("head_sha"), limit: perPage, offset: (page - 1) * perPage });
1073 setLinks(c, { page, perPage, offset: (page - 1) * perPage }, res.total);
1074 return c.json({ total_count: res.total, workflow_runs: res.runs.map((r) => runJson(c, P(c).owner, P(c).repo, r)) });
1075});
1076api.get("/repos/:owner/:repo/actions/runs/:id", async (c) => {
1077 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
1078 const r = await stub.run(c.req.param("id"));
1079 return c.json({ ...runJson(c, P(c).owner, P(c).repo, r), jobs: r.jobs });
1080});
1081api.get("/repos/:owner/:repo/actions/runs/:id/jobs", async (c) => {
1082 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
1083 const run = await stub.run(c.req.param("id"));
1084 const jobs = (await stub.runJobs(c.req.param("id"))) as unknown as JobInfo[];
1085 return c.json({ total_count: jobs.length, jobs: paginate(c, jobs).map((j) => jobJson(c, P(c).owner, P(c).repo, run, j)) });
1086});
1087api.post("/repos/:owner/:repo/actions/runs/:id/cancel", async (c) => {
1088 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
1089 await stub.cancelRun(c.req.param("id"), caller);
1090 return c.json({}, 202);
1091});
1092for (const path of ["rerun", "rerun-failed-jobs"]) {
1093 api.post(`/repos/:owner/:repo/actions/runs/:id/${path}`, async (c) => {
1094 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
1095 const r = await stub.rerun(c.req.param("id"), caller);
1096 return c.json({ run_id: r.id }, 201);
1097 });
1098}
1099api.get("/repos/:owner/:repo/actions/jobs/:id", async (c) => {
1100 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
1101 const job = (await stub.job(c.req.param("id"))) as unknown as JobInfo;
1102 return c.json(jobJson(c, P(c).owner, P(c).repo, await stub.run(job.runId), job));
1103});
1104api.get("/repos/:owner/:repo/actions/jobs/:id/logs", async (c) => {
1105 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
1106 const { lines } = await stub.jobLogs(c.req.param("id"), Number(c.req.query("after") ?? -1));
1107 if (c.req.query("format") === "json") return c.json(lines);
1108 return c.text(lines.map((l) => `${l.t} ${l.text}`).join("\n"));
1109});
1110api.route("/", actionsRest);
1111api.get("/repos/:owner/:repo/actions/secrets", async (c) => {
1112 const { stub } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
1113 const s = await stub.secretNames();
1114 return c.json({ total_count: s.length, secrets: s.map((x) => ({ name: x.name, updated_at: x.updatedAt })) });
1115});
1116api.put("/repos/:owner/:repo/actions/secrets/:name", async (c) => {
1117 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
1118 if (caller.kind === "agent") throw new HttpError(403, "agents cannot manage secrets");
1119 const b = await body<{ value: string; encrypted_value?: string }>(c);
1120 if (typeof b.value !== "string" && typeof b.encrypted_value === "string") throw new HttpError(422, "encrypted_value (sealed box) is not supported yet: send the secret as `value` over HTTPS; it is encrypted at rest");
1121 if (typeof b.value !== "string") throw new HttpError(422, "value is required (send it over HTTPS; it is encrypted at rest)");
1122 await stub.setSecret(c.req.param("name"), b.value);
1123 auditRepo(c, caller, repo, "repo.secret.set", { name: c.req.param("name").toUpperCase() });
1124 return c.body(null, 204);
1125});
1126api.delete("/repos/:owner/:repo/actions/secrets/:name", async (c) => {
1127 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
1128 refuseAgent(caller, "secrets");
1129 await stub.deleteSecret(c.req.param("name"));
1130 auditRepo(c, caller, repo, "repo.secret.delete", { name: c.req.param("name").toUpperCase() });
1131 return c.body(null, 204);
1132});
1133api.get("/repos/:owner/:repo/actions/variables", async (c) => {
1134 const { stub } = await loadRepo(c, P(c).owner, P(c).repo, "write");
1135 // The repository's own variables; organization variables are listed under /orgs/:org/actions/variables.
1136 const all = Object.entries(await stub.variables(false)).map(([name, value]) => ({ name, value }));
1137 return c.json({ total_count: all.length, variables: paginate(c, all) });
1138});
1139api.delete("/repos/:owner/:repo/actions/variables/:name", async (c) => {
1140 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
1141 refuseAgent(caller, "variables");
1142 await stub.setVariable(c.req.param("name"), null);
1143 auditRepo(c, caller, repo, "repo.variable.delete", { name: c.req.param("name").toUpperCase() });
1144 return c.body(null, 204);
1145});
1146api.put("/repos/:owner/:repo/actions/variables/:name", async (c) => {
1147 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
1148 refuseAgent(caller, "variables");
1149 await stub.setVariable(c.req.param("name"), (await body<{ value: string }>(c)).value);
1150 auditRepo(c, caller, repo, "repo.variable.set", { name: c.req.param("name").toUpperCase() });
1151 return c.body(null, 204);
1152});
1153async function orgAdmin(c: AppContext) {
1154 requireAccountScope(c, "admin");
1155 const a = requireAccount(c);
1156 if (a.kind === "agent") throw new HttpError(403, "agents cannot manage secrets");
1157 const dir = c.get("dir");
1158 const org = await dir.accountByLogin(c.req.param("org")!);
1159 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
1160 const role = await dir.orgRole(org.id, a.id);
1161 if (role !== "owner" && role !== "admin" && !a.site_admin) throw new HttpError(403, "organization admins only");
1162 return { a, org };
1163}
1164type OrgSecretRow = { name: string; updated_at: string; visibility: "all" | "private" | "selected" };
1165const ORG_SECRET_VISIBILITY = ["all", "private", "selected"] as const;
1166const orgSecretJson = (c: AppContext, org: Account, s: OrgSecretRow) => ({
1167 name: s.name,
1168 created_at: s.updated_at,
1169 updated_at: s.updated_at,
1170 visibility: s.visibility,
1171 ...(s.visibility === "selected" ? { selected_repository_ids_url: `${c.env.PUBLIC_URL}/api/v3/orgs/${org.login}/actions/secrets/${s.name}/repositories`, selected_repositories_url: `${c.env.PUBLIC_URL}/api/v3/orgs/${org.login}/actions/secrets/${s.name}/repositories` } : {}),
1172});
1173/** The organization's repositories with the given numeric (GitHub) ids; 422 for any id that isn't one of them. */
1174async function orgReposById(c: AppContext, org: Account, ids: unknown): Promise<Repo[]> {
1175 if (!Array.isArray(ids) || ids.some((x) => typeof x !== "number" && typeof x !== "string")) throw new HttpError(422, "selected_repository_ids must be a list of repository ids");
1176 if (ids.length > 1000) throw new HttpError(422, "at most 1000 repositories can be selected");
1177 const repos = await c.get("dir").reposVisibleTo(requireAccount(c), org.id);
1178 const byId = new Map(repos.map((r) => [String(numericId(r.id)), r]));
1179 return ids.map((x) => {
1180 const r = byId.get(String(x));
1181 if (!r) throw new HttpError(422, `${x} isn't a repository of ${org.login}`);
1182 return r;
1183 });
1184}
1185async function orgSecret(c: AppContext, org: Account, name: string): Promise<OrgSecretRow> {
1186 const s = await c.env.DB.prepare("SELECT name, updated_at, visibility FROM org_secrets WHERE org_id = ? AND name = ?").bind(org.id, name.toUpperCase()).first<OrgSecretRow>();
1187 if (!s) throw new HttpError(404, "secret not found");
1188 return s;
1189}
1190async function setSecretRepos(c: AppContext, org: Account, name: string, repos: Repo[]): Promise<void> {
1191 await c.env.DB.batch([
1192 c.env.DB.prepare("DELETE FROM org_secret_repos WHERE org_id = ? AND name = ?").bind(org.id, name),
1193 ...repos.map((r) => c.env.DB.prepare("INSERT OR IGNORE INTO org_secret_repos (org_id, name, repo_id) VALUES (?, ?, ?)").bind(org.id, name, r.id)),
1194 ]);
1195}
1196api.get("/orgs/:org/actions/secrets", async (c) => {
1197 const { org } = await orgAdmin(c);
1198 const { results } = await c.env.DB.prepare("SELECT name, updated_at, visibility FROM org_secrets WHERE org_id = ? ORDER BY name").bind(org.id).all<OrgSecretRow>();
1199 return c.json({ total_count: results.length, secrets: results.map((s) => orgSecretJson(c, org, s)) });
1200});
1201api.get("/orgs/:org/actions/secrets/:name", async (c) => {
1202 const { org } = await orgAdmin(c);
1203 return c.json(orgSecretJson(c, org, await orgSecret(c, org, c.req.param("name"))));
1204});
1205// GitHub's repository selection for a secret with `visibility: selected`.
1206api.get("/orgs/:org/actions/secrets/:name/repositories", async (c) => {
1207 const { org } = await orgAdmin(c);
1208 const s = await orgSecret(c, org, c.req.param("name"));
1209 const { results } = await c.env.DB.prepare("SELECT r.* FROM org_secret_repos x JOIN repos r ON r.id = x.repo_id WHERE x.org_id = ? AND x.name = ? ORDER BY r.name").bind(org.id, s.name).all<{ id: string }>();
1210 const repos = (await Promise.all(results.map((r) => c.get("dir").repoById(r.id)))).filter((r): r is Repo => !!r);
1211 return c.json({ total_count: repos.length, repositories: repos.map((r) => repoJson(c, r)) });
1212});
1213api.put("/orgs/:org/actions/secrets/:name/repositories", async (c) => {
1214 const { a, org } = await orgAdmin(c);
1215 const s = await orgSecret(c, org, c.req.param("name"));
1216 if (s.visibility !== "selected") throw new HttpError(409, "the secret's visibility isn't selected");
1217 const repos = await orgReposById(c, org, (await body<{ selected_repository_ids?: unknown }>(c)).selected_repository_ids);
1218 await setSecretRepos(c, org, s.name, repos);
1219 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: a.id, actorLogin: a.login, action: "org.secret.repositories", target: org.login, detail: { name: s.name, repositories: repos.map((r) => r.name), via: "api" } }));
1220 return c.body(null, 204);
1221});
1222for (const method of ["put", "delete"] as const) {
1223 api[method]("/orgs/:org/actions/secrets/:name/repositories/:repoId", async (c) => {
1224 const { a, org } = await orgAdmin(c);
1225 const s = await orgSecret(c, org, c.req.param("name"));
1226 if (s.visibility !== "selected") throw new HttpError(409, "the secret's visibility isn't selected");
1227 const [repo] = await orgReposById(c, org, [c.req.param("repoId")]);
1228 if (method === "put") await c.env.DB.prepare("INSERT OR IGNORE INTO org_secret_repos (org_id, name, repo_id) VALUES (?, ?, ?)").bind(org.id, s.name, repo!.id).run();
1229 else await c.env.DB.prepare("DELETE FROM org_secret_repos WHERE org_id = ? AND name = ? AND repo_id = ?").bind(org.id, s.name, repo!.id).run();
1230 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: a.id, actorLogin: a.login, action: method === "put" ? "org.secret.repository.add" : "org.secret.repository.remove", target: org.login, detail: { name: s.name, repository: repo!.name, via: "api" } }));
1231 return c.body(null, 204);
1232 });
1233}
1234api.delete("/orgs/:org/actions/secrets/:name", async (c) => {
1235 const { a, org } = await orgAdmin(c);
1236 const r = await c.env.DB.prepare("DELETE FROM org_secrets WHERE org_id = ? AND name = ?").bind(org.id, c.req.param("name").toUpperCase()).run();
1237 await c.env.DB.prepare("DELETE FROM org_secret_repos WHERE org_id = ? AND name = ?").bind(org.id, c.req.param("name").toUpperCase()).run();
1238 // Like GitHub: deleting a secret that doesn't exist is a 404, and nothing is audited.
1239 if (!r.meta?.changes) throw new HttpError(404, "secret not found");
1240 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: a.id, actorLogin: a.login, action: "org.secret.delete", target: org.login, detail: { name: c.req.param("name").toUpperCase(), via: "api" } }));
1241 return c.body(null, 204);
1242});
1243api.put("/orgs/:org/actions/secrets/:name", async (c) => {
1244 const { a, org } = await orgAdmin(c);
1245 const name = c.req.param("name").toUpperCase();
1246 if (!/^[A-Z_][A-Z0-9_]*$/.test(name)) throw new HttpError(422, "invalid secret name");
1247 const b = await body<{ value: string; visibility?: unknown; selected_repository_ids?: unknown }>(c);
1248 if (b.visibility !== undefined && !ORG_SECRET_VISIBILITY.includes(b.visibility as OrgSecretRow["visibility"])) throw new HttpError(422, "visibility must be all, private or selected");
1249 if (b.selected_repository_ids !== undefined && b.visibility !== "selected") throw new HttpError(422, "selected_repository_ids needs visibility selected");
1250 const existing = await c.env.DB.prepare("SELECT visibility FROM org_secrets WHERE org_id = ? AND name = ?").bind(org.id, name).first<{ visibility: OrgSecretRow["visibility"] }>();
1251 // A new secret reaches every repository unless the request says otherwise; an update keeps its selection.
1252 const visibility = (b.visibility as OrgSecretRow["visibility"] | undefined) ?? existing?.visibility ?? "all";
1253 const repos = b.selected_repository_ids !== undefined ? await orgReposById(c, org, b.selected_repository_ids) : null;
1254 await c.env.DB.prepare("INSERT OR REPLACE INTO org_secrets (org_id, name, ciphertext, updated_at, visibility) VALUES (?, ?, ?, ?, ?)").bind(org.id, name, await encryptSecret(c.env.MASTER_KEY, `org:${org.id}`, b.value), new Date().toISOString(), visibility).run();
1255 if (repos) await setSecretRepos(c, org, name, repos);
1256 else if (visibility !== "selected") await c.env.DB.prepare("DELETE FROM org_secret_repos WHERE org_id = ? AND name = ?").bind(org.id, name).run();
1257 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: a.id, actorLogin: a.login, action: "org.secret.set", target: org.login, detail: { name, visibility, ...(repos ? { repositories: repos.map((r) => r.name) } : {}), via: "api" } }));
1258 return c.body(null, 204);
1259});
1260
1261// ---------------------------------------------------------------- webhooks
1262
1263api.get("/repos/:owner/:repo/hooks", async (c) => {
1264 const { stub } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
1265 return c.json(paginate(c, (await stub.webhooks()).map(({ secret: _s, ...h }) => hookJson(c, h))));
1266});
1267api.post("/repos/:owner/:repo/hooks", async (c) => {
1268 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
1269 const b = await body<{ config: { url: string; secret?: string }; events?: string[] }>(c);
1270 if (typeof b.config?.url !== "string") throw new HttpError(422, "config.url is required", { errors: [{ resource: "Hook", code: "missing_field", field: "config.url" }] });
1271 const created = await stub.createWebhook(b.config.url, Array.isArray(b.events) ? b.events.map(String) : ["*"], b.config.secret);
1272 const hook = (await stub.webhooks()).find((h) => h.id === created.id)!;
1273 auditRepo(c, caller, repo, "repo.webhook.create", { id: created.id, url: b.config.url });
1274 // The generated secret is shown once, here (GitHub never returns secrets; Diffinery makes one when none is given).
1275 return c.json({ ...hookJson(c, { ...hook, secret: undefined }), secret: b.config.secret ? undefined : created.secret }, 201);
1276});
1277api.delete("/repos/:owner/:repo/hooks/:id", async (c) => {
1278 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
1279 await stub.deleteWebhook(c.req.param("id"));
1280 auditRepo(c, caller, repo, "repo.webhook.delete", { id: c.req.param("id") });
1281 return c.body(null, 204);
1282});
1283
1284// ---------------------------------------------------------------- Diffinery: tokens, agents, sandboxes, notifications
1285
1286api.get("/diffinery/tokens", async (c) => c.json(await c.get("dir").tokens(requireAccount(c).id)));
1287api.post("/diffinery/tokens", async (c) => {
1288 // Minting a token needs a browser session: no token (however wide) can create another.
1289 const a = requireBrowserSession(c);
1290 const b = await body<{ name: string; scopes?: TokenScope[]; repositories?: string[]; expires_in_days?: number }>(c);
1291 const scopes = parseScopes(b.scopes);
1292 let repoIds: string[] | null = null;
1293 if (b.repositories?.length) {
1294 repoIds = [];
1295 for (const full of b.repositories) {
1296 const [o, n] = full.split("/");
1297 const r = o && n ? ((await c.get("dir").repo(o, n)) ?? (await c.get("dir").movedRepo(o, n))) : null;
1298 // Repositories the account can't see are "unknown", so this doesn't reveal private ones.
1299 if (!r || !(await callerFor(c, r))) throw new HttpError(422, `unknown repository ${full}`);
1300 repoIds.push(r.id);
1301 }
1302 }
1303 const t = await c.get("dir").createToken(a, { name: b.name, scopes, repoIds, expiresInDays: b.expires_in_days });
1304 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: a.id, actorLogin: a.login, action: "token.create", detail: { name: b.name, scopes } }));
1305 return c.json(t, 201);
1306});
1307api.delete("/diffinery/tokens/:id", async (c) => {
1308 requireAccountScope(c, "admin");
1309 const a = requireAccount(c);
1310 await c.get("dir").revokeToken(a.id, c.req.param("id"));
1311 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: a.id, actorLogin: a.login, action: "token.revoke", target: c.req.param("id"), detail: { via: "api" } }));
1312 return c.body(null, 204);
1313});
1314api.get("/diffinery/agents", async (c) => {
1315 const a = requireAccount(c);
1316 const orgs = (await c.get("dir").orgsFor(a.id)).filter((o) => o.role !== "member").map((o) => o.id);
1317 return c.json((await c.get("dir").agentsOwnedBy([a.id, ...orgs])).map((x) => ({ ...userJson(c, x), owner_id: x.owner_id, policy: x.agent_policy ? JSON.parse(x.agent_policy) : {} })));
1318});
1319api.post("/diffinery/agents", async (c) => {
1320 // Creating an agent mints its first token, so it needs a browser session too.
1321 const a = requireBrowserSession(c);
1322 if (a.kind !== "user") throw new HttpError(403, "only people can create agents");
1323 const b = await body<{ login: string; name?: string; org?: string; policy?: Record<string, unknown>; token?: { scopes?: TokenScope[]; expires_in_days?: number } }>(c);
1324 const dir = c.get("dir");
1325 const org = b.org ? await dir.accountByLogin(b.org) : null;
1326 const agent = await dir.createAgent(a, { login: b.login, name: b.name, orgId: org?.id, policy: b.policy });
1327 const token = await dir.createToken(agent, { name: "default", scopes: parseScopes(b.token?.scopes), expiresInDays: b.token?.expires_in_days ?? 90 });
1328 c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "agent.create", target: agent.login }));
1329 return c.json({ agent: userJson(c, agent), token }, 201);
1330});
1331api.post("/diffinery/agents/:login/tokens", async (c) => {
1332 const a = requireBrowserSession(c);
1333 const dir = c.get("dir");
1334 const agent = await dir.accountByLogin(c.req.param("login"));
1335 if (!agent || agent.kind !== "agent") throw new HttpError(404, "agent not found");
1336 const orgRole = agent.owner_id && agent.owner_id !== a.id ? await dir.orgRole(agent.owner_id, a.id) : null;
1337 if (agent.owner_id !== a.id && orgRole !== "owner" && orgRole !== "admin") throw new HttpError(403, "not your agent");
1338 const b = await body<{ name?: string; scopes?: TokenScope[]; expires_in_days?: number }>(c).catch(() => ({}) as Record<string, undefined>);
1339 const scopes = parseScopes(b.scopes);
1340 const t = await dir.createToken(agent, { name: b.name ?? "token", scopes, expiresInDays: b.expires_in_days });
1341 c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "agent.token.create", target: agent.login, detail: { scopes } }));
1342 return c.json(t, 201);
1343});
1344api.delete("/diffinery/agents/:login", async (c) => {
1345 requireAccountScope(c, "admin");
1346 const a = requireAccount(c);
1347 const dir = c.get("dir");
1348 const agent = await dir.accountByLogin(c.req.param("login"));
1349 if (!agent || agent.kind !== "agent") throw new HttpError(404, "agent not found");
1350 const orgRole = agent.owner_id && agent.owner_id !== a.id ? await dir.orgRole(agent.owner_id, a.id) : null;
1351 if (agent.owner_id !== a.id && orgRole !== "owner" && orgRole !== "admin" && !a.site_admin) throw new HttpError(403, "not your agent");
1352 await dir.setStatus(agent.id, "disabled");
1353 c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "agent.disable", target: agent.login }));
1354 return c.body(null, 204);
1355});
1356
1357api.post("/repos/:owner/:repo/diffinery/sandboxes", async (c) => {
1358 // A sandbox's token outlives the job that would start it, so job and sandbox tokens can't start one.
1359 if (c.get("principal").type === "repo-token") throw new HttpError(403, "job and sandbox tokens can't start sandboxes");
1360 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
1361 const b = await body<{ ref?: string }>(c).catch(() => ({}) as { ref?: string });
1362 return c.json(await stub.createSandbox(caller, b.ref), 201);
1363});
1364api.post("/repos/:owner/:repo/diffinery/sandboxes/:id/:action", async (c) => {
1365 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
1366 const id = c.req.param("id");
1367 const action = c.req.param("action");
1368 await stub.sandbox(id, caller);
1369 if (action === "close") {
1370 await stub.closeSandbox(id, caller);
1371 return c.body(null, 204);
1372 }
1373 const map: Record<string, string> = { exec: "/exec", read: "/files/read", write: "/files/write" };
1374 if (!map[action]) throw new HttpError(404, "unknown sandbox action");
1375 const res = await c.env.SANDBOX.get(c.env.SANDBOX.idFromName(id)).call(map[action]!, JSON.stringify(await c.req.json().catch(() => ({}))));
1376 return new Response(res.body, { status: res.status, headers: { "content-type": res.json ? "application/json" : "text/plain; charset=utf-8" } });
1377});
1378
1379api.get("/notifications", async (c) => {
1380 requireUnlimitedToken(c, "read notifications");
1381 return c.json(await c.get("dir").notifications(requireAccount(c).id, c.req.query("all") !== "true"));
1382});
1383api.put("/notifications", async (c) => {
1384 requireAccountScope(c, "write");
1385 await c.get("dir").markRead(requireAccount(c).id);
1386 return c.body(null, 205);
1387});
1388
1389// OIDC discovery for workflow id tokens.
1390export const wellKnown = new Hono<{ Bindings: Env; Variables: AppVars }>();
1391wellKnown.get("/.well-known/openid-configuration", (c) =>
1392 c.json({ issuer: c.env.PUBLIC_URL, jwks_uri: `${c.env.PUBLIC_URL}/.well-known/jwks`, response_types_supported: ["id_token"], subject_types_supported: ["public"], id_token_signing_alg_values_supported: ["ES256"], claims_supported: ["sub", "aud", "iss", "repository", "repository_id", "repository_owner", "repository_owner_id", "environment", "ref", "ref_type", "sha", "workflow", "event_name", "actor", "actor_id", "run_id"] }),
1393);
1394wellKnown.get("/.well-known/jwks", (c) => c.json({ keys: c.env.OIDC_PRIVATE_KEY ? [publicJwk(JSON.parse(c.env.OIDC_PRIVATE_KEY))] : [] }));
1395
1396// ---------------------------------------------------------------- GitHub JSON helpers used above
1397
1398function permissionsOf(role: Role) {
1399 return { admin: role === "admin", maintain: role === "admin" || role === "maintain", push: role !== "read" && role !== "triage", triage: role !== "read", pull: true };
1400}
1401
1402function refJson(c: AppContext, r: { ref: string; sha: string; type: string }) {
1403 return ghRef(baseOf(c), P(c).owner, P(c).repo, r);
1404}
1405
1406function contentJson(c: AppContext, ref: string, path: string, sha: string, size: number, type: string) {
1407 const b = baseOf(c);
1408 const api = repoApi(b, P(c).owner, P(c).repo);
1409 const html = repoHtml(b, P(c).owner, P(c).repo);
1410 const self = `${api}/contents/${encPath(path)}?ref=${encodeURIComponent(ref)}`;
1411 const git = `${api}/git/${type === "dir" ? "trees" : "blobs"}/${sha}`;
1412 const htmlUrl = `${html}/${type === "dir" ? "tree" : "blob"}/${encPath(ref)}/${encPath(path)}`;
1413 return {
1414 type,
1415 size: type === "dir" ? 0 : size,
1416 name: path.split("/").pop() ?? path,
1417 path,
1418 sha,
1419 url: self,
1420 git_url: git,
1421 html_url: htmlUrl,
1422 download_url: type === "file" || type === "symlink" ? `${html}/raw/${encPath(ref)}/${encPath(path)}` : null,
1423 _links: { self, git, html: htmlUrl },
1424 };
1425}
1426
1427function gitCommitJson(c: AppContext, x: CommitInfo) {
1428 return ghGitCommit(baseOf(c), P(c).owner, P(c).repo, x);
1429}
1430
1431function checkRunJson(c: AppContext, r: Parameters<typeof ghCheckRun>[3]) {
1432 return ghCheckRun(baseOf(c), P(c).owner, P(c).repo, r);
1433}
1434
1435function jobJson(c: AppContext, owner: string, repo: string, run: RunInfo, j: JobInfo): Record<string, unknown> {
1436 return ghJob(baseOf(c), owner, repo, run, j);
1437}
1438
1439function hookJson(c: AppContext, h: { id: string; url: string; events: string[]; active: boolean; createdAt: string; lastStatus: number | null; lastDeliveryAt: string | null; secret?: string }) {
1440 const api = repoApi(baseOf(c), P(c).owner, P(c).repo);
1441 return {
1442 type: "Repository",
1443 id: h.id,
1444 name: "web",
1445 active: h.active,
1446 events: h.events,
1447 config: { url: h.url, content_type: "json", insecure_ssl: "0", ...(h.secret ? { secret: "********" } : {}) },
1448 updated_at: isoSeconds(h.lastDeliveryAt ?? h.createdAt),
1449 created_at: isoSeconds(h.createdAt),
1450 url: `${api}/hooks/${h.id}`,
1451 ping_url: `${api}/hooks/${h.id}/pings`,
1452 deliveries_url: `${api}/hooks/${h.id}/deliveries`,
1453 last_response: { code: h.lastStatus, status: h.lastStatus === null ? "unused" : h.lastStatus >= 200 && h.lastStatus < 300 ? "active" : "failed", message: null },
1454 };
1455}
1456
1457export { fromUtf8 };