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.

1100 lines · 70.7 KBRaw History
1import { Hono } from "hono";
2import { fromUtf8 } from "@diffinery/git-core";
3import type { Env } from "../env.js";
4import { callerFor, parseScopes, requireAccount, requireAccountScope, requireBrowserSession, 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 { publicJwk } from "../lib/jwt.js";
8import { HttpError, b64, fromB64 } from "../lib/util.js";
9import { atLeast, type ProtectionRules, type Role } from "../repo/types.js";
10import type { JobInfo, RunInfo } from "../repo/actions.js";
11import type { CommitInfo } from "../repo/RepoDO.js";
12import type { QueueEntry } from "../repo/queue.js";
13import { imports } from "./imports.js";
14import { agenticApi } from "../agentic/api.js";
15import { auditRepo, loadRepo, refuseAgent, repoStub } from "./common.js";
16import { repoCreated } from "../mail/notify.js";
17import { actionsRest } from "./actions-runtime.js";
18import { compat } from "./compat.js";
19import { baseOf, encPath, ghAutoMerge, ghCheckRun, ghComment, ghCommit, ghGitCommit, ghJob, ghRef, ghRun, ghFile, ghLabel, ghReview, ghReviewComment, ghUser, isoSeconds, nodeId, pageOf, paginate, repoApi, repoHtml, setLinks } from "./gh.js";
20import { decodePath, issueCtx, issuesOut, pullDetail, pullsOut, repoOut } from "./ghctx.js";
21
22/**
23 * REST API. Paths and payloads follow GitHub's REST API v3 where practical so
24 * existing scripts and tools work; Diffinery-only endpoints live under /api/v3/diffinery.
25 */
26export const api = new Hono<{ Bindings: Env; Variables: AppVars }>().basePath("/api/v3");
27
28// GitHub-compatible endpoints that live in their own files (releases, statuses, Git data, ...).
29// Mounted first: some of their paths (like /issues/comments) would otherwise match routes below.
30api.route("/", compat);
31
32const userJson = (c: AppContext, a: Pick<Account, "id" | "login" | "kind" | "name">) => ({ ...ghUser(baseOf(c), a)!, name: a.name || null });
33
34const repoJson = repoOut;
35
36async function body<T>(c: AppContext): Promise<T> {
37 try {
38 return (await c.req.json()) as T;
39 } catch {
40 throw new HttpError(400, "request body must be JSON");
41 }
42}
43
44/** Called with an access token (scripts, the CLI, agents) rather than from a browser. */
45const viaToken = (c: AppContext) => {
46 const p = c.get("principal");
47 return p.type === "account" && p.via === "token";
48};
49const P = (c: AppContext) => ({ owner: c.req.param("owner")!, repo: c.req.param("repo")! });
50const num = (c: AppContext, name = "number") => {
51 const n = Number(c.req.param(name));
52 if (!Number.isInteger(n) || n < 1) throw new HttpError(404, "not found");
53 return n;
54};
55
56// GitHub imports, milestones, organization variables and linked accounts.
57api.route("/", imports);
58// Agentic work: the Today view (agentic/).
59api.route("/", agenticApi);
60
61// ---------------------------------------------------------------- meta & users
62
63api.get("/", (c) => c.json({ name: "Diffinery", api: "v3", docs: `${c.env.PUBLIC_URL}/docs/api`, mcp: `${c.env.PUBLIC_URL}/mcp` }));
64api.get("/meta", (c) => c.json({ name: "Diffinery", oidc: !!c.env.OIDC_PRIVATE_KEY }));
65api.get("/user", (c) => {
66 const a = requireAccount(c);
67 return c.json({ ...userJson(c, a), email: a.email, site_admin: !!a.site_admin });
68});
69api.get("/users/:login", async (c) => {
70 requireAccount(c);
71 const a = await c.get("dir").accountByLogin(c.req.param("login"));
72 if (!a) throw new HttpError(404, "not found");
73 return c.json(userJson(c, a));
74});
75api.get("/user/orgs", async (c) => c.json((await c.get("dir").orgsFor(requireAccount(c).id)).map((o) => ({ ...userJson(c, o), role: o.role }))));
76api.post("/user/orgs", async (c) => {
77 requireAccountScope(c, "admin");
78 const a = requireAccount(c);
79 const b = await body<{ login: string; name?: unknown }>(c);
80 if (typeof b.login !== "string") throw new HttpError(422, "login is required", { errors: [{ resource: "Organization", code: "missing_field", field: "login" }] });
81 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" }] });
82 return c.json(userJson(c, await c.get("dir").createOrg(b.login, (b.name as string | null | undefined) || b.login, a)), 201);
83});
84// GitHub's organization object; members and their agents also see the base permission (default_repository_permission).
85const orgJson = async (c: AppContext, org: Account, me: Account) => ({ ...userJson(c, org), ...((await c.get("dir").inOrg(org.id, me)) ? { default_repository_permission: baseRole(org) } : {}) });
86api.get("/orgs/:org", async (c) => {
87 const a = requireAccount(c);
88 const org = await c.get("dir").accountByLogin(c.req.param("org"));
89 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
90 return c.json(await orgJson(c, org, a));
91});
92api.patch("/orgs/:org", async (c) => {
93 requireAccountScope(c, "admin");
94 const a = requireAccount(c);
95 const dir = c.get("dir");
96 const org = await dir.accountByLogin(c.req.param("org"));
97 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
98 const role = await dir.orgRole(org.id, a.id);
99 if (!role && !a.site_admin) throw new HttpError(404, "not found");
100 if (role !== "owner" && !a.site_admin) throw new HttpError(403, "only organization owners can change its settings");
101 const b = await body<{ name?: unknown; default_repository_permission?: unknown }>(c);
102 await dir.updateAccount(org.id, { name: b.name, baseRole: b.default_repository_permission });
103 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 } }));
104 return c.json(await orgJson(c, (await dir.account(org.id))!, a));
105});
106// Owners only. Refused while the organization still owns repositories (see Directory.deleteOrg).
107api.delete("/orgs/:org", async (c) => {
108 requireAccountScope(c, "admin");
109 const a = requireAccount(c);
110 const dir = c.get("dir");
111 const org = await dir.accountByLogin(c.req.param("org"));
112 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
113 const role = await dir.orgRole(org.id, a.id);
114 if (!role && !a.site_admin) throw new HttpError(404, "not found");
115 if (role !== "owner" && !a.site_admin) throw new HttpError(403, "only organization owners can delete it");
116 await dir.deleteOrg(org);
117 c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "org.delete", target: org.login }));
118 return c.json({}, 202);
119});
120api.get("/orgs/:org/members", async (c) => {
121 const a = requireAccount(c);
122 const dir = c.get("dir");
123 const org = await dir.accountByLogin(c.req.param("org"));
124 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
125 if (!(await dir.orgRole(org.id, a.id)) && !a.site_admin) throw new HttpError(404, "not found");
126 return c.json((await dir.orgMembers(org.id)).map((m) => ({ ...userJson(c, m), role: m.role })));
127});
128api.post("/orgs/:org/invitations", async (c) => {
129 requireAccountScope(c, "admin");
130 const a = requireAccount(c);
131 const dir = c.get("dir");
132 const org = await dir.accountByLogin(c.req.param("org"));
133 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
134 const role = await dir.orgRole(org.id, a.id);
135 if (role !== "owner" && role !== "admin" && !a.site_admin) throw new HttpError(403, "only organization owners and admins can invite");
136 const b = await body<{ email: string; role?: "member" | "admin" | "owner" }>(c);
137 if (!/^[^@\s]+@[^@\s]+$/.test(b.email ?? "")) throw new HttpError(422, "a valid email is required");
138 const inv = await dir.createInvite(a, { email: b.email, orgId: org.id, role: b.role ?? "member" });
139 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" } }));
140 return c.json({ id: inv.id, url: inv.url }, 201);
141});
142
143// Site-wide invitation (no organization): site admins only.
144api.post("/invitations", async (c) => {
145 requireAccountScope(c, "admin");
146 const a = requireAccount(c);
147 if (!a.site_admin) throw new HttpError(403, "only site admins can invite people without an organization");
148 const b = await body<{ email: string }>(c);
149 if (!/^[^@\s]+@[^@\s]+$/.test(b.email ?? "")) throw new HttpError(422, "a valid email is required");
150 const dir = c.get("dir");
151 const inv = await dir.createInvite(a, { email: b.email, role: "member" });
152 c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "site.invite", detail: { email: b.email } }));
153 return c.json({ id: inv.id, url: inv.url }, 201);
154});
155
156// Pending invitations: list and revoke, for an organization's owners and admins, a repository's admins,
157// and site admins (invitations to the site itself).
158const inviteJson = (i: Awaited<ReturnType<Directory["invites"]>>[number]) => ({ id: i.id, email: i.email, role: i.role, inviter: i.invitedBy ? { login: i.invitedBy } : null, created_at: i.createdAt, expires_at: i.expiresAt });
159const orgForInvites = async (c: AppContext) => {
160 requireAccountScope(c, "read");
161 const a = requireAccount(c);
162 const dir = c.get("dir");
163 const org = await dir.accountByLogin(c.req.param("org") ?? "");
164 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
165 const role = await dir.orgRole(org.id, a.id);
166 if (!role && !a.site_admin) throw new HttpError(404, "not found");
167 if (role !== "owner" && role !== "admin" && !a.site_admin) throw new HttpError(403, "only organization owners and admins can manage invitations");
168 return { a, dir, org };
169};
170const revoked = async (c: AppContext, ok: boolean, action: string, target?: string) => {
171 if (!ok) throw new HttpError(404, "no pending invitation with this id");
172 const a = requireAccount(c);
173 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: a.id, actorLogin: a.login, action, target, detail: { id: c.req.param("id"), via: "api" } }));
174 return c.body(null, 204);
175};
176api.get("/orgs/:org/invitations", async (c) => {
177 const { dir, org } = await orgForInvites(c);
178 return c.json((await dir.invites({ orgId: org.id, pending: true })).map(inviteJson));
179});
180api.delete("/orgs/:org/invitations/:id", async (c) => {
181 requireAccountScope(c, "admin");
182 const { dir, org } = await orgForInvites(c);
183 return revoked(c, await dir.revokeInvite(c.req.param("id"), { orgId: org.id }), "org.invite.revoke", org.login);
184});
185api.get("/repos/:owner/:repo/invitations", async (c) => {
186 const { repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
187 return c.json((await c.get("dir").invites({ repoId: repo.id, pending: true })).map(inviteJson));
188});
189api.delete("/repos/:owner/:repo/invitations/:id", async (c) => {
190 const { repo, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
191 if (!(await c.get("dir").revokeInvite(c.req.param("id"), { repoId: repo.id }))) throw new HttpError(404, "no pending invitation with this id");
192 auditRepo(c, caller, repo, "repo.invite.revoke", { id: c.req.param("id") });
193 return c.body(null, 204);
194});
195api.get("/invitations", async (c) => {
196 requireAccountScope(c, "read");
197 if (!requireAccount(c).site_admin) throw new HttpError(403, "only site admins can list site invitations");
198 return c.json((await c.get("dir").invites({ site: true, pending: true })).map(inviteJson));
199});
200api.delete("/invitations/:id", async (c) => {
201 requireAccountScope(c, "admin");
202 if (!requireAccount(c).site_admin) throw new HttpError(403, "only site admins can revoke site invitations");
203 return revoked(c, await c.get("dir").revokeInvite(c.req.param("id"), {}), "invite.revoke");
204});
205
206// ---------------------------------------------------------------- repositories
207
208api.get("/user/repos", async (c) => c.json(paginate(c, (await c.get("dir").reposVisibleTo(requireAccount(c))).map((r) => repoJson(c, r)))));
209api.post("/user/repos", async (c) => {
210 requireAccountScope(c, "write");
211 const a = requireAccount(c);
212 const b = await body<{ name: string; description?: string; private?: boolean; visibility?: string; default_branch?: string }>(c);
213 const owner = a.kind === "agent" ? (await c.get("dir").account(a.owner_id!))! : a;
214 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 });
215 c.executionCtx.waitUntil(repoCreated(c.env, c.get("dir"), r, a, { viaToken: viaToken(c) }));
216 return c.json(repoJson(c, r), 201);
217});
218api.get("/users/:login/repos", async (c) => {
219 const a = requireAccount(c);
220 const owner = await c.get("dir").accountByLogin(c.req.param("login"));
221 if (!owner) throw new HttpError(404, "not found");
222 return c.json(paginate(c, (await c.get("dir").reposVisibleTo(a, owner.id)).map((r) => repoJson(c, r))));
223});
224api.get("/orgs/:org/repos", async (c) => {
225 const a = requireAccount(c);
226 const org = await c.get("dir").accountByLogin(c.req.param("org"));
227 if (!org) throw new HttpError(404, "not found");
228 return c.json(paginate(c, (await c.get("dir").reposVisibleTo(a, org.id)).map((r) => repoJson(c, r))));
229});
230api.post("/orgs/:org/repos", async (c) => {
231 requireAccountScope(c, "write");
232 const a = requireAccount(c);
233 const org = await c.get("dir").accountByLogin(c.req.param("org"));
234 if (!org || org.kind !== "org") throw new HttpError(404, "organization not found");
235 const b = await body<{ name: string; description?: string; private?: boolean; visibility?: string; default_branch?: string }>(c);
236 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 });
237 c.executionCtx.waitUntil(repoCreated(c.env, c.get("dir"), r, a, { viaToken: viaToken(c) }));
238 return c.json(repoJson(c, r), 201);
239});
240api.get("/repos/:owner/:repo", async (c) => {
241 const { repo, caller, stub } = await loadRepo(c, P(c).owner, P(c).repo);
242 const stats = await stub.stats();
243 return c.json({ ...repoOut(c, repo, caller.role), open_issues_count: stats.openIssues + stats.openPulls, open_issues: stats.openIssues + stats.openPulls, stats });
244});
245api.patch("/repos/:owner/:repo", async (c) => {
246 const { repo, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin", { whileArchived: true });
247 const b = await body<{ name?: string; description?: string; private?: boolean; visibility?: Repo["visibility"]; default_branch?: string; archived?: boolean }>(c);
248 if (b.private !== undefined && typeof b.private !== "boolean") throw new HttpError(422, "private must be a boolean", { errors: [{ resource: "Repository", code: "invalid", field: "private" }] });
249 // GitHub's `private: false` makes the repository public.
250 const visibility = b.visibility ?? (b.private === true ? "private" : b.private === false ? "public" : undefined);
251 const updated = await c.get("dir").updateRepo(repo, { name: b.name, description: b.description, visibility, defaultBranch: b.default_branch, archived: b.archived });
252 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));
253 if (b.archived !== undefined && b.archived !== !!repo.archived) auditRepo(c, caller, repo, b.archived ? "repo.archive" : "repo.unarchive");
254 if (Object.keys(changed).some((k) => k !== "archived")) auditRepo(c, caller, repo, "repo.update", changed);
255 return c.json(repoOut(c, updated, caller.role));
256});
257api.delete("/repos/:owner/:repo", async (c) => {
258 const { repo, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin", { whileArchived: true });
259 if (caller.kind === "agent") throw new HttpError(403, "agents cannot delete repositories");
260 await c.get("dir").deleteRepo(repo);
261 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: caller.id, actorLogin: caller.login, action: "repo.delete", target: `${repo.owner_login}/${repo.name}` }));
262 return c.body(null, 204);
263});
264// GitHub's transfer: to the caller's own account or an organization they own or administer, optionally
265// under a new name. People only: never agents, job tokens (GITHUB_TOKEN) or sandbox tokens.
266api.post("/repos/:owner/:repo/transfer", async (c) => {
267 const { repo, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin", { whileArchived: true });
268 const p = c.get("principal");
269 if (p.type !== "account" || caller.kind !== "user" || caller.permissions) throw new HttpError(403, "agents and workflow tokens cannot transfer repositories");
270 requireAccountScope(c, "admin");
271 const b = await body<{ new_owner?: unknown; new_name?: unknown }>(c);
272 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" }] });
273 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" }] });
274 const dir = c.get("dir");
275 const target = await dir.accountByLogin(b.new_owner.trim());
276 if (!target) throw new HttpError(422, `no user or organization named ${b.new_owner.trim()}`, { errors: [{ resource: "Repository", code: "invalid", field: "new_owner" }] });
277 const moved = await dir.transferRepo(repo, p.account, target, (b.new_name as string | null | undefined) ?? undefined);
278 auditRepo(c, caller, moved, "repo.transfer", { from: `${repo.owner_login}/${repo.name}`, to: `${moved.owner_login}/${moved.name}` });
279 return c.json(repoOut(c, moved, (await dir.roleFor(p.account, moved)) ?? "read"), 202);
280});
281api.get("/repos/:owner/:repo/collaborators", async (c) => {
282 const { repo } = await loadRepo(c, P(c).owner, P(c).repo);
283 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 }))));
284});
285api.put("/repos/:owner/:repo/collaborators/:login", async (c) => {
286 const { repo, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
287 const who = await c.get("dir").accountByLogin(c.req.param("login"));
288 if (!who) throw new HttpError(404, "user not found");
289 const b = await body<{ permission?: Role | "pull" | "push" }>(c).catch(() => ({ permission: "write" as Role }));
290 const map: Record<string, Role> = { pull: "read", push: "write" };
291 const role = map[b.permission ?? ""] ?? (b.permission as Role) ?? "write";
292 await c.get("dir").setCollaborator(repo.id, who.id, role);
293 auditRepo(c, caller, repo, "repo.collaborator.set", { login: who.login, role });
294 return c.body(null, 204);
295});
296api.delete("/repos/:owner/:repo/collaborators/:login", async (c) => {
297 const { repo, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
298 const who = await c.get("dir").accountByLogin(c.req.param("login"));
299 if (who) {
300 await c.get("dir").setCollaborator(repo.id, who.id, null);
301 auditRepo(c, caller, repo, "repo.collaborator.remove", { login: who.login });
302 }
303 return c.body(null, 204);
304});
305
306// ---------------------------------------------------------------- git data
307
308api.get("/repos/:owner/:repo/branches", async (c) => {
309 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
310 const api = repoApi(baseOf(c), P(c).owner, P(c).repo);
311 let list = await stub.branches();
312 if (c.req.query("protected") !== undefined) list = list.filter((b) => b.protected === (c.req.query("protected") === "true"));
313 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 }))));
314});
315api.get("/repos/:owner/:repo/branches/:branch", async (c) => {
316 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
317 const name = c.req.param("branch");
318 const b = (await stub.branches()).find((x) => x.name === name);
319 if (!b) throw new HttpError(404, "Branch not found");
320 const api = repoApi(baseOf(c), P(c).owner, P(c).repo);
321 return c.json({
322 name,
323 commit: ghCommit(baseOf(c), P(c).owner, P(c).repo, await stub.commitInfo(b.sha)),
324 _links: { self: `${api}/branches/${encPath(name)}`, html: `${repoHtml(baseOf(c), P(c).owner, P(c).repo)}/tree/${encPath(name)}` },
325 protected: b.protected,
326 protection: { enabled: b.protected, required_status_checks: { enforcement_level: b.protected ? "non_admins" : "off", contexts: [], checks: [] } },
327 protection_url: `${api}/branches/${encPath(name)}/protection`,
328 });
329});
330api.get("/repos/:owner/:repo/tags", async (c) => {
331 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
332 const api = repoApi(baseOf(c), P(c).owner, P(c).repo);
333 const tags = (await stub.tags()).reverse();
334 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}`) }))));
335});
336// GET /git/refs/<ref>: one ref when the path names it exactly, else every ref under it (GitHub's legacy form).
337api.get("/repos/:owner/:repo/git/refs/*", async (c) => {
338 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
339 const name = `refs/${decodePath(c.req.path.split("/git/refs/")[1] ?? "")}`.replace(/\/$/, "");
340 const all = await stub.refsWithTypes("refs/");
341 const exact = all.find((r) => r.ref === name);
342 if (exact) return c.json(refJson(c, exact));
343 const matches = all.filter((r) => r.ref.startsWith(`${name}/`) && !r.ref.startsWith("refs/pull/"));
344 if (!matches.length) throw new HttpError(404, "Not Found");
345 return c.json(paginate(c, matches.map((r) => refJson(c, r)), 100));
346});
347api.post("/repos/:owner/:repo/git/refs", async (c) => {
348 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
349 const b = await body<{ ref: string; sha: string }>(c);
350 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" }] });
351 if (typeof b.sha !== "string") throw new HttpError(422, "sha is required", { errors: [{ resource: "Reference", code: "missing_field", field: "sha" }] });
352 await stub.createRef(b.ref, b.sha, caller);
353 return c.json(refJson(c, { ref: b.ref, sha: b.sha, type: (await stub.objectType(b.sha)) ?? "commit" }), 201);
354});
355api.patch("/repos/:owner/:repo/git/refs/*", async (c) => {
356 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
357 const ref = `refs/${decodePath(c.req.path.split("/git/refs/")[1] ?? "")}`;
358 const b = await body<{ sha: string; force?: boolean }>(c);
359 if (typeof b.sha !== "string") throw new HttpError(422, "sha is required", { errors: [{ resource: "Reference", code: "missing_field", field: "sha" }] });
360 await stub.updateRef(ref, b.sha, !!b.force, caller);
361 return c.json(refJson(c, { ref, sha: b.sha, type: (await stub.objectType(b.sha)) ?? "commit" }));
362});
363api.delete("/repos/:owner/:repo/git/refs/*", async (c) => {
364 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
365 await stub.deleteRef(`refs/${decodePath(c.req.path.split("/git/refs/")[1] ?? "")}`, caller);
366 return c.body(null, 204);
367});
368api.get("/repos/:owner/:repo/commits", async (c) => {
369 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
370 const p = pageOf(c);
371 const rev = c.req.query("sha") ?? "HEAD";
372 if (!(await stub.resolve(rev))) {
373 if (!(await stub.resolve("HEAD"))) throw new HttpError(409, "Git Repository is empty.");
374 throw new HttpError(404, `No commit found for SHA: ${rev}`);
375 }
376 let list = await stub.log(rev, { path: c.req.query("path"), limit: p.perPage + 1, skip: p.offset });
377 const author = c.req.query("author")?.toLowerCase();
378 if (author) list = list.filter((x) => x.author.email.toLowerCase() === author || x.author.name.toLowerCase() === author || x.author.email.toLowerCase().startsWith(`${author}@`));
379 const since = c.req.query("since") ? Date.parse(c.req.query("since")!) / 1000 : null;
380 const until = c.req.query("until") ? Date.parse(c.req.query("until")!) / 1000 : null;
381 if (since) list = list.filter((x) => x.committer.timestamp >= since);
382 if (until) list = list.filter((x) => x.committer.timestamp <= until);
383 setLinks(c, p, null, list.length > p.perPage);
384 return c.json(list.slice(0, p.perPage).map((x) => ghCommit(baseOf(c), P(c).owner, P(c).repo, x)));
385});
386api.get("/repos/:owner/:repo/commits/:ref", async (c) => {
387 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
388 const sha = await stub.resolve(c.req.param("ref"));
389 if (!sha) throw new HttpError(422, `No commit found for SHA: ${c.req.param("ref")}`);
390 const x = await stub.commitWithDiff(sha);
391 const files = x.files.map((f) => ghFile(baseOf(c), P(c).owner, P(c).repo, sha, f));
392 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 });
393});
394api.get("/repos/:owner/:repo/compare/:spec{.+}", async (c) => {
395 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
396 const spec = c.req.param("spec");
397 const [base, head] = spec.includes("...") ? spec.split("...") : spec.split("..");
398 if (!base || !head) throw new HttpError(422, "use base...head");
399 const r = await stub.compare(base.includes(":") ? base.split(":")[1]! : base, head.includes(":") ? head.split(":")[1]! : head);
400 const b = baseOf(c);
401 const { owner, repo } = P(c);
402 const api = repoApi(b, owner, repo);
403 const html = repoHtml(b, owner, repo);
404 const commits = paginate(c, r.commits, 250);
405 return c.json({
406 url: `${api}/compare/${spec}`,
407 html_url: `${html}/compare/${spec}`,
408 permalink_url: `${html}/compare/${r.baseSha}...${r.headSha}`,
409 diff_url: `${html}/compare/${spec}.diff`,
410 patch_url: `${html}/compare/${spec}.patch`,
411 base_commit: ghCommit(b, owner, repo, await stub.commitInfo(r.baseSha)),
412 merge_base_commit: r.mergeBase ? ghCommit(b, owner, repo, await stub.commitInfo(r.mergeBase)) : null,
413 status: r.aheadBy && r.behindBy ? "diverged" : r.aheadBy ? "ahead" : r.behindBy ? "behind" : "identical",
414 ahead_by: r.aheadBy,
415 behind_by: r.behindBy,
416 total_commits: r.aheadBy,
417 commits: commits.map((x) => ghCommit(b, owner, repo, x)),
418 files: r.files.map((f) => ghFile(b, owner, repo, r.headSha, f)),
419 // Diffinery: the same comparison in its own words.
420 base_sha: r.baseSha,
421 head_sha: r.headSha,
422 merge_base: r.mergeBase,
423 });
424});
425// Contents: files come back base64-encoded with GitHub's links; `Accept: application/vnd.github.raw` returns the bytes.
426async function getContents(c: AppContext) {
427 const { stub, repo } = await loadRepo(c, P(c).owner, P(c).repo);
428 const path = decodePath(c.req.path.split("/contents/")[1] ?? "").replace(/^\/+|\/+$/g, "");
429 const ref = c.req.query("ref") || repo.default_branch;
430 const sha = await stub.resolve(ref);
431 if (!sha) throw new HttpError(404, `No commit found for the ref ${ref}`);
432 const tree = await stub.tree(sha, path);
433 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")));
434 const blob = await stub.blob(sha, path);
435 if (!blob) throw new HttpError(404, "Not Found");
436 if (/application\/vnd\.github(\.v3)?\.raw/.test(c.req.header("accept") ?? "")) {
437 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}"` } });
438 }
439 const type = blob.mode === "120000" ? "symlink" : "file";
440 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 });
441}
442api.get("/repos/:owner/:repo/contents/*", getContents);
443api.get("/repos/:owner/:repo/contents", getContents);
444api.put("/repos/:owner/:repo/contents/*", async (c) => {
445 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
446 const path = decodeURIComponent(c.req.path.split("/contents/")[1] ?? "");
447 const b = await body<{ message: string; content: string; branch?: string; sha?: string; committer?: { name: string; email: string }; author?: { name: string; email: string } }>(c);
448 if (typeof b.content !== "string") throw new HttpError(422, "content is required (base64)", { errors: [{ resource: "Contents", code: "missing_field", field: "content" }] });
449 let bytes: Uint8Array;
450 try {
451 bytes = fromB64(b.content.replace(/\s+/g, ""));
452 } catch {
453 throw new HttpError(422, "content is not valid Base64", { errors: [{ resource: "Contents", code: "invalid", field: "content" }] });
454 }
455 const sig = (s?: { name: string; email: string }) => (s && typeof s.name === "string" && typeof s.email === "string" ? { name: s.name, email: s.email } : undefined);
456 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);
457 const ref = b.branch || (await loadRepo(c, P(c).owner, P(c).repo)).repo.default_branch;
458 return c.json({ content: contentJson(c, ref, path, res.blob.sha, res.blob.size, "file"), commit: gitCommitJson(c, res.commit) }, res.created ? 201 : 200);
459});
460api.delete("/repos/:owner/:repo/contents/*", async (c) => {
461 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
462 const path = decodeURIComponent(c.req.path.split("/contents/")[1] ?? "");
463 const b = await body<{ message: string; branch?: string; sha?: string; committer?: { name: string; email: string }; author?: { name: string; email: string } }>(c);
464 const commit = await stub.deleteContents({ path, message: b.message, branch: b.branch, sha: b.sha, author: b.author, committer: b.committer ?? b.author }, caller);
465 return c.json({ content: null, commit: gitCommitJson(c, commit) });
466});
467
468/** Agent-friendly multi-file commit without a Git client. */
469api.post("/repos/:owner/:repo/diffinery/commits", async (c) => {
470 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
471 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);
472 if (!Array.isArray(b.files) || b.files.length === 0) throw new HttpError(422, "files is required");
473 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 ?? "") }));
474 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);
475});
476
477api.get("/repos/:owner/:repo/raw/:ref/*", async (c) => {
478 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
479 const path = decodeURIComponent(c.req.path.split(`/raw/${c.req.param("ref")}/`)[1] ?? "");
480 const blob = await stub.blob(c.req.param("ref"), path);
481 if (!blob) throw new HttpError(404, "not found");
482 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" } });
483});
484
485// ---------------------------------------------------------------- branch protection
486
487api.get("/repos/:owner/:repo/branches/:branch/protection", async (c) => {
488 const { stub } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
489 const rule = (await stub.listProtections()).find((p) => p.pattern === c.req.param("branch"));
490 if (!rule) throw new HttpError(404, "branch not protected");
491 return c.json(rule);
492});
493api.put("/repos/:owner/:repo/branches/:branch/protection", async (c) => {
494 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
495 if (caller.kind === "agent") throw new HttpError(403, "agents cannot change branch protection");
496 const rules = await body<ProtectionRules>(c);
497 await stub.setProtection(c.req.param("branch"), rules, caller);
498 auditRepo(c, caller, repo, "repo.protection.set", { pattern: c.req.param("branch") });
499 return c.json({ pattern: c.req.param("branch"), rules });
500});
501api.delete("/repos/:owner/:repo/branches/:branch/protection", async (c) => {
502 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
503 if (caller.kind === "agent") throw new HttpError(403, "agents cannot change branch protection");
504 await stub.setProtection(c.req.param("branch"), null, caller);
505 auditRepo(c, caller, repo, "repo.protection.delete", { pattern: c.req.param("branch") });
506 return c.body(null, 204);
507});
508
509// ---------------------------------------------------------------- issues & pulls
510
511/** Label names from a GitHub payload (strings or `{ name }` objects). */
512const labelNames = (v: unknown): string[] | undefined => (Array.isArray(v) ? v.map((l) => (typeof l === "string" ? l : String((l as { name?: unknown })?.name ?? ""))).filter(Boolean) : undefined);
513/** Assignee logins from `assignees` or the older singular `assignee`. */
514const assigneeLogins = (b: { assignees?: unknown; assignee?: unknown }): string[] | undefined =>
515 Array.isArray(b.assignees) ? b.assignees.map(String) : b.assignee === null ? [] : typeof b.assignee === "string" ? [b.assignee] : undefined;
516const sortParam = (v: string | undefined) => (v === "updated" || v === "comments" || v === "created" ? v : undefined);
517
518for (const kind of ["issues", "pulls"] as const) {
519 api.get(`/repos/:owner/:repo/${kind}`, async (c) => {
520 const { stub, repo } = await loadRepo(c, P(c).owner, P(c).repo);
521 const p = pageOf(c);
522 const q = (k: string) => c.req.query(k) || undefined;
523 const labels = q("labels")?.split(",").map((l) => l.trim()).filter(Boolean);
524 const head = q("head");
525 // `milestone`: a milestone number, `none` or `*` (any), as on GitHub.
526 const ms = q("milestone");
527 if (ms && !/^(\d+|none|\*)$/.test(ms)) throw new HttpError(422, "milestone must be a milestone number, none or *");
528 const res = await stub.issues({
529 milestone: ms === "none" || ms === "*" ? ms : ms ? Number(ms) : undefined,
530 kind: kind === "pulls" ? "pull" : undefined,
531 state: (q("state") as "open" | "closed" | "all") ?? "open",
532 labels,
533 author: q("creator"),
534 assignee: q("assignee"),
535 since: q("since"),
536 head: head?.includes(":") ? head.slice(head.indexOf(":") + 1) : head,
537 base: q("base"),
538 sort: kind === "pulls" && q("sort") === "popularity" ? "comments" : sortParam(q("sort")),
539 direction: q("direction") === "asc" ? "asc" : q("direction") === "desc" ? "desc" : undefined,
540 q: q("q"),
541 limit: p.perPage,
542 offset: p.offset,
543 });
544 c.header("x-total-count", String(res.total));
545 setLinks(c, p, res.total);
546 return c.json(kind === "pulls" ? await pullsOut(c, repo, stub, res.items) : await issuesOut(c, repo, stub, res.items));
547 });
548}
549api.post("/repos/:owner/:repo/issues", async (c) => {
550 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
551 const b = await body<{ title: string; body?: string; labels?: unknown; assignees?: unknown; assignee?: unknown }>(c);
552 if (typeof b.title !== "string" && typeof b.title !== "number") throw new HttpError(422, "title is required", { errors: [{ resource: "Issue", code: "missing_field", field: "title" }] });
553 const issue = await stub.createIssue({ title: String(b.title), body: b.body ?? undefined, labels: labelNames(b.labels), assignees: assigneeLogins(b) }, caller);
554 return c.json((await issuesOut(c, repo, stub, [issue]))[0], 201);
555});
556api.get("/repos/:owner/:repo/issues/:number", async (c) => {
557 const { stub, repo } = await loadRepo(c, P(c).owner, P(c).repo);
558 return c.json((await issuesOut(c, repo, stub, [(await stub.issue(num(c))).issue]))[0]);
559});
560api.patch("/repos/:owner/:repo/issues/:number", async (c) => {
561 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
562 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);
563 // `milestone` (a number or null) is checked before anything is saved. As with labels and assignees,
564 // it is silently dropped for people without triage access.
565 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");
566 const milestone = atLeast(caller.role, "triage") ? (b.milestone as number | null | undefined) : undefined;
567 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" }] });
568 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);
569 if (milestone !== undefined) {
570 await stub.setIssueMilestone(num(c), milestone);
571 issue = (await stub.issue(num(c))).issue;
572 }
573 return c.json((await issuesOut(c, repo, stub, [issue]))[0]);
574});
575api.get("/repos/:owner/:repo/issues/:number/comments", async (c) => {
576 const { stub, repo } = await loadRepo(c, P(c).owner, P(c).repo);
577 const n = num(c);
578 const { issue, comments } = await stub.issue(n);
579 const since = c.req.query("since");
580 const list = paginate(c, comments.filter((x) => !x.reviewId && (!since || x.updatedAt >= since)));
581 const x = await issueCtx(c, repo, stub, [], list.map((cm) => `comment:${cm.id}`));
582 return c.json(list.map((cm) => ghComment(x, n, issue.kind === "pull", cm)));
583});
584api.post("/repos/:owner/:repo/issues/:number/comments", async (c) => {
585 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
586 const n = num(c);
587 const b = await body<{ body: string }>(c);
588 if (typeof b.body !== "string") throw new HttpError(422, "body is required", { errors: [{ resource: "IssueComment", code: "missing_field", field: "body" }] });
589 const cm = await stub.addComment(n, b.body, caller);
590 const { issue } = await stub.issue(n);
591 return c.json(ghComment(await issueCtx(c, repo, stub, []), n, issue.kind === "pull", cm), 201);
592});
593api.patch("/repos/:owner/:repo/issues/comments/:id", async (c) => {
594 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
595 const b = await body<{ body: string }>(c);
596 if (typeof b.body !== "string" || !b.body.trim()) throw new HttpError(422, "body is required", { errors: [{ resource: "IssueComment", code: "missing_field", field: "body" }] });
597 await stub.editComment(c.req.param("id"), b.body, caller);
598 const found = await stub.comment(c.req.param("id"));
599 return c.json(ghComment(await issueCtx(c, repo, stub, [], [`comment:${found.comment.id}`]), found.number, found.isPull, found.comment));
600});
601api.get("/repos/:owner/:repo/labels", async (c) => {
602 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
603 return c.json(paginate(c, (await stub.labelRows()).map((l) => ghLabel(baseOf(c), P(c).owner, P(c).repo, l))));
604});
605api.post("/repos/:owner/:repo/labels", async (c) => {
606 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "triage");
607 const b = await body<{ name: string; color?: string; description?: string }>(c);
608 return c.json(ghLabel(baseOf(c), P(c).owner, P(c).repo, await stub.createLabel(b, caller)), 201);
609});
610
611api.post("/repos/:owner/:repo/pulls", async (c) => {
612 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "write");
613 const b = await body<{ title: string; body?: string; head: string; base?: string; draft?: boolean; intent?: string; reviewers?: string[] }>(c);
614 if (typeof b.head !== "string" || !b.head) throw new HttpError(422, "head is required", { errors: [{ resource: "PullRequest", code: "missing_field", field: "head" }] });
615 const issue = await stub.createPull({ ...b, head: b.head.includes(":") ? b.head.split(":")[1]! : b.head }, caller);
616 return c.json((await pullsOut(c, repo, stub, [issue]))[0], 201);
617});
618api.get("/repos/:owner/:repo/pulls/:number", async (c) => {
619 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
620 return c.json(await pullDetail(c, repo, stub, num(c), caller));
621});
622api.patch("/repos/:owner/:repo/pulls/:number", async (c) => {
623 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
624 const b = await body<{ title?: string; body?: string | null; state?: "open" | "closed"; draft?: boolean }>(c);
625 // `draft` is a Diffinery extension (GitHub only offers it through GraphQL).
626 if (typeof b.draft === "boolean") await stub.setPullDraft(num(c), b.draft, caller);
627 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;
628 if (issue.kind !== "pull") throw new HttpError(404, "not a pull request");
629 return c.json((await pullsOut(c, repo, stub, [issue]))[0]);
630});
631api.get("/repos/:owner/:repo/pulls/:number/files", async (c) => {
632 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
633 const res = await stub.pullFiles(num(c));
634 return c.json(paginate(c, res.files.map((f) => ({ ...ghFile(baseOf(c), P(c).owner, P(c).repo, res.headSha, f), binary: f.binary }))));
635});
636api.get("/repos/:owner/:repo/pulls/:number/commits", async (c) => {
637 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
638 return c.json(paginate(c, (await stub.pullCommits(num(c))).map((x) => ghCommit(baseOf(c), P(c).owner, P(c).repo, x)), 250));
639});
640// GitHub clients (Accept: application/vnd.github...) get GitHub's "is it merged" answer: 204 or 404.
641// Other clients get Diffinery's mergeability report: blockers, approvals, checks and the merge queue.
642api.get("/repos/:owner/:repo/pulls/:number/merge", async (c) => {
643 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo);
644 const n = num(c);
645 if ((c.req.header("accept") ?? "").includes("application/vnd.github")) {
646 const { issue } = await stub.issue(n);
647 if (issue.pull?.merged) return c.body(null, 204);
648 throw new HttpError(404, "Not Found");
649 }
650 return c.json(await stub.mergeability(n, caller));
651});
652api.put("/repos/:owner/:repo/pulls/:number/merge", async (c) => {
653 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
654 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>);
655 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);
656 return c.json({ ...r, message: "Pull Request successfully merged" });
657});
658
659// Merge queue (GitHub exposes it through GraphQL only; these follow its REST conventions).
660const queueJson = (e: QueueEntry) => ({
661 number: e.number,
662 title: e.title,
663 base_ref: e.base,
664 position: e.position,
665 state: e.state,
666 head_sha: e.headSha,
667 merge_method: e.method,
668 delete_branch: e.deleteBranch,
669 enqueued_by: { login: e.enqueuedBy.login },
670 enqueued_at: e.enqueuedAt,
671 merge_group: e.groupSha ? { head_sha: e.groupSha, head_ref: e.groupRef, base_sha: e.parentSha, built_at: e.builtAt } : null,
672 checks: e.checks,
673});
674api.get("/repos/:owner/:repo/merge-queue/:branch{.+}", async (c) => {
675 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
676 const branch = c.req.param("branch");
677 const settings = await stub.mergeQueueSettings(branch);
678 return c.json({ branch, enabled: !!settings, settings, entries: (await stub.mergeQueue(branch)).map(queueJson) });
679});
680api.put("/repos/:owner/:repo/pulls/:number/merge-queue", async (c) => {
681 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
682 const b = await body<{ merge_method?: "merge" | "squash" | "rebase"; delete_branch?: boolean }>(c).catch(() => ({}) as Record<string, undefined>);
683 const r = await stub.enqueuePull(num(c), { method: b.merge_method, deleteBranch: b.delete_branch }, caller);
684 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);
685});
686api.delete("/repos/:owner/:repo/pulls/:number/merge-queue", async (c) => {
687 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
688 await stub.dequeuePull(num(c), caller);
689 return c.body(null, 204);
690});
691// Auto-merge (GitHub's enablePullRequestAutoMerge and disablePullRequestAutoMerge, which it exposes through GraphQL only).
692api.put("/repos/:owner/:repo/pulls/:number/auto-merge", async (c) => {
693 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
694 const b = await body<{ merge_method?: string; commit_title?: string; commit_message?: string; delete_branch?: unknown; sha?: unknown }>(c).catch(() => ({}) as Record<string, undefined>);
695 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" }] });
696 if (b.sha !== undefined && typeof b.sha !== "string") throw new HttpError(422, "sha must be a string", { errors: [{ resource: "PullRequest", code: "invalid", field: "sha" }] });
697 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);
698 return c.json({ state: r.state, auto_merge: ghAutoMerge(baseOf(c), r.autoMerge), merge_commit_sha: r.mergeCommit ?? null });
699});
700api.delete("/repos/:owner/:repo/pulls/:number/auto-merge", async (c) => {
701 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
702 await stub.disableAutoMerge(num(c), caller);
703 return c.body(null, 204);
704});
705api.get("/repos/:owner/:repo/pulls/:number/reviews", async (c) => {
706 const { stub, repo } = await loadRepo(c, P(c).owner, P(c).repo);
707 const n = num(c);
708 const x = await issueCtx(c, repo, stub, []);
709 return c.json(paginate(c, (await stub.issue(n)).reviews.map((r) => ghReview(x, n, r))));
710});
711api.post("/repos/:owner/:repo/pulls/:number/reviews", async (c) => {
712 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
713 const n = num(c);
714 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);
715 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" }] });
716 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;
717 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" }] });
718 const r = await stub.submitReview(n, { event: b.event ?? "COMMENT", body: b.body, comments }, caller);
719 return c.json(ghReview(await issueCtx(c, repo, stub, []), n, r), 201);
720});
721api.get("/repos/:owner/:repo/pulls/:number/comments", async (c) => {
722 const { stub, repo } = await loadRepo(c, P(c).owner, P(c).repo);
723 const n = num(c);
724 const list = paginate(c, (await stub.issue(n)).comments.filter((x) => x.reviewId));
725 const x = await issueCtx(c, repo, stub, [], list.map((cm) => `review_comment:${cm.id}`));
726 return c.json(list.map((cm) => ghReviewComment(x, n, cm)));
727});
728api.post("/repos/:owner/:repo/pulls/:number/requested_reviewers", async (c) => {
729 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo);
730 const n = num(c);
731 const b = await body<{ reviewers?: string[]; team_reviewers?: string[] }>(c);
732 if (b.team_reviewers?.length) throw new HttpError(422, "team reviewers are not supported; request people by login");
733 await stub.requestReviewers(n, (b.reviewers ?? []).map(String), caller);
734 return c.json((await pullsOut(c, repo, stub, [(await stub.issue(n)).issue]))[0], 201);
735});
736
737// ---------------------------------------------------------------- checks (for plugins and external CI)
738
739api.get("/repos/:owner/:repo/commits/:ref/check-runs", async (c) => {
740 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
741 const sha = await stub.resolve(c.req.param("ref"));
742 if (!sha) throw new HttpError(404, "ref not found");
743 let runs = await stub.checks(sha);
744 const name = c.req.query("check_name");
745 const status = c.req.query("status");
746 if (name) runs = runs.filter((r) => r.name === name);
747 if (status) runs = runs.filter((r) => r.status === status);
748 const page = paginate(c, runs);
749 return c.json({ total_count: runs.length, check_runs: page.map((r) => checkRunJson(c, r)) });
750});
751api.post("/repos/:owner/:repo/check-runs", async (c) => {
752 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
753 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);
754 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" }] });
755 if (caller.login.toLowerCase().startsWith("diffinery-actions")) throw new HttpError(403, "this account can't report check runs");
756 const sha = typeof b.head_sha === "string" ? await stub.resolve(b.head_sha) : null;
757 if (!sha) throw new HttpError(422, "head_sha is not a commit in this repository", { errors: [{ resource: "CheckRun", code: "invalid", field: "head_sha" }] });
758 const status = b.conclusion ? "completed" : (b.status ?? "queued");
759 const { annotations: _a, text: _t, ...output } = b.output ?? {};
760 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 } });
761 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);
762 return c.json(checkRunJson(c, check), 201);
763});
764
765// ---------------------------------------------------------------- actions
766
767const runJson = (c: AppContext, owner: string, repo: string, r: RunInfo) => ghRun(baseOf(c), owner, repo, r);
768
769api.get("/repos/:owner/:repo/actions/workflows", async (c) => {
770 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
771 const wfs = await stub.workflows();
772 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 })) });
773});
774api.post("/repos/:owner/:repo/actions/workflows/:workflow/dispatches", async (c) => {
775 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
776 const b = await body<{ ref: string; inputs?: Record<string, unknown> }>(c);
777 const run = await stub.dispatchWorkflow(decodeURIComponent(c.req.param("workflow")), b.ref, b.inputs ?? {}, caller);
778 return c.json({ run_id: run.id, html_url: `${c.env.PUBLIC_URL}/${P(c).owner}/${P(c).repo}/actions/runs/${run.id}` }, 201);
779});
780// Self-hosted runners poll this to pick up `runs-on: [self-hosted, ...]` jobs (see `diffinery runner`).
781api.post("/repos/:owner/:repo/actions/runners/claim", async (c) => {
782 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
783 const b = await body<{ name?: string; labels?: string[] }>(c);
784 const job = await stub.claimJob(b.name ?? "runner", Array.isArray(b.labels) ? b.labels.map(String) : [], caller);
785 if (!job) return c.body(null, 204);
786 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 });
787});
788api.get("/repos/:owner/:repo/actions/runs", async (c) => {
789 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
790 const perPage = Math.min(Number(c.req.query("per_page") ?? 25), 100);
791 const page = Number(c.req.query("page") ?? 1);
792 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 });
793 setLinks(c, { page, perPage, offset: (page - 1) * perPage }, res.total);
794 return c.json({ total_count: res.total, workflow_runs: res.runs.map((r) => runJson(c, P(c).owner, P(c).repo, r)) });
795});
796api.get("/repos/:owner/:repo/actions/runs/:id", async (c) => {
797 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
798 const r = await stub.run(c.req.param("id"));
799 return c.json({ ...runJson(c, P(c).owner, P(c).repo, r), jobs: r.jobs });
800});
801api.get("/repos/:owner/:repo/actions/runs/:id/jobs", async (c) => {
802 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
803 const run = await stub.run(c.req.param("id"));
804 const jobs = (await stub.runJobs(c.req.param("id"))) as unknown as JobInfo[];
805 return c.json({ total_count: jobs.length, jobs: paginate(c, jobs).map((j) => jobJson(c, P(c).owner, P(c).repo, run, j)) });
806});
807api.post("/repos/:owner/:repo/actions/runs/:id/cancel", async (c) => {
808 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
809 await stub.cancelRun(c.req.param("id"), caller);
810 return c.json({}, 202);
811});
812for (const path of ["rerun", "rerun-failed-jobs"]) {
813 api.post(`/repos/:owner/:repo/actions/runs/:id/${path}`, async (c) => {
814 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
815 const r = await stub.rerun(c.req.param("id"), caller);
816 return c.json({ run_id: r.id }, 201);
817 });
818}
819api.get("/repos/:owner/:repo/actions/jobs/:id", async (c) => {
820 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
821 const job = (await stub.job(c.req.param("id"))) as unknown as JobInfo;
822 return c.json(jobJson(c, P(c).owner, P(c).repo, await stub.run(job.runId), job));
823});
824api.get("/repos/:owner/:repo/actions/jobs/:id/logs", async (c) => {
825 const { stub } = await loadRepo(c, P(c).owner, P(c).repo);
826 const { lines } = await stub.jobLogs(c.req.param("id"), Number(c.req.query("after") ?? -1));
827 if (c.req.query("format") === "json") return c.json(lines);
828 return c.text(lines.map((l) => `${l.t} ${l.text}`).join("\n"));
829});
830api.route("/", actionsRest);
831api.get("/repos/:owner/:repo/actions/secrets", async (c) => {
832 const { stub } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
833 const s = await stub.secretNames();
834 return c.json({ total_count: s.length, secrets: s.map((x) => ({ name: x.name, updated_at: x.updatedAt })) });
835});
836api.put("/repos/:owner/:repo/actions/secrets/:name", async (c) => {
837 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
838 if (caller.kind === "agent") throw new HttpError(403, "agents cannot manage secrets");
839 const b = await body<{ value: string; encrypted_value?: string }>(c);
840 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");
841 if (typeof b.value !== "string") throw new HttpError(422, "value is required (send it over HTTPS; it is encrypted at rest)");
842 await stub.setSecret(c.req.param("name"), b.value);
843 auditRepo(c, caller, repo, "repo.secret.set", { name: c.req.param("name").toUpperCase() });
844 return c.body(null, 204);
845});
846api.delete("/repos/:owner/:repo/actions/secrets/:name", async (c) => {
847 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
848 refuseAgent(caller, "secrets");
849 await stub.deleteSecret(c.req.param("name"));
850 auditRepo(c, caller, repo, "repo.secret.delete", { name: c.req.param("name").toUpperCase() });
851 return c.body(null, 204);
852});
853api.get("/repos/:owner/:repo/actions/variables", async (c) => {
854 const { stub } = await loadRepo(c, P(c).owner, P(c).repo, "write");
855 // The repository's own variables; organization variables are listed under /orgs/:org/actions/variables.
856 const all = Object.entries(await stub.variables(false)).map(([name, value]) => ({ name, value }));
857 return c.json({ total_count: all.length, variables: paginate(c, all) });
858});
859api.delete("/repos/:owner/:repo/actions/variables/:name", async (c) => {
860 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
861 refuseAgent(caller, "variables");
862 await stub.setVariable(c.req.param("name"), null);
863 auditRepo(c, caller, repo, "repo.variable.delete", { name: c.req.param("name").toUpperCase() });
864 return c.body(null, 204);
865});
866api.put("/repos/:owner/:repo/actions/variables/:name", async (c) => {
867 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
868 refuseAgent(caller, "variables");
869 await stub.setVariable(c.req.param("name"), (await body<{ value: string }>(c)).value);
870 auditRepo(c, caller, repo, "repo.variable.set", { name: c.req.param("name").toUpperCase() });
871 return c.body(null, 204);
872});
873async function orgAdmin(c: AppContext) {
874 requireAccountScope(c, "admin");
875 const a = requireAccount(c);
876 if (a.kind === "agent") throw new HttpError(403, "agents cannot manage secrets");
877 const dir = c.get("dir");
878 const org = await dir.accountByLogin(c.req.param("org")!);
879 if (!org || org.kind !== "org") throw new HttpError(404, "not found");
880 const role = await dir.orgRole(org.id, a.id);
881 if (role !== "owner" && role !== "admin" && !a.site_admin) throw new HttpError(403, "organization admins only");
882 return { a, org };
883}
884api.get("/orgs/:org/actions/secrets", async (c) => {
885 const { org } = await orgAdmin(c);
886 const { results } = await c.env.DB.prepare("SELECT name, updated_at FROM org_secrets WHERE org_id = ? ORDER BY name").bind(org.id).all<{ name: string; updated_at: string }>();
887 return c.json({ total_count: results.length, secrets: results });
888});
889api.delete("/orgs/:org/actions/secrets/:name", async (c) => {
890 const { a, org } = await orgAdmin(c);
891 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();
892 // Like GitHub: deleting a secret that doesn't exist is a 404, and nothing is audited.
893 if (!r.meta?.changes) throw new HttpError(404, "secret not found");
894 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" } }));
895 return c.body(null, 204);
896});
897api.put("/orgs/:org/actions/secrets/:name", async (c) => {
898 const { a, org } = await orgAdmin(c);
899 const name = c.req.param("name").toUpperCase();
900 if (!/^[A-Z_][A-Z0-9_]*$/.test(name)) throw new HttpError(422, "invalid secret name");
901 const { value } = await body<{ value: string }>(c);
902 await c.env.DB.prepare("INSERT OR REPLACE INTO org_secrets (org_id, name, ciphertext, updated_at) VALUES (?, ?, ?, ?)").bind(org.id, name, await encryptSecret(c.env.MASTER_KEY, `org:${org.id}`, value), new Date().toISOString()).run();
903 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: a.id, actorLogin: a.login, action: "org.secret.set", target: org.login, detail: { name, via: "api" } }));
904 return c.body(null, 204);
905});
906
907// ---------------------------------------------------------------- webhooks
908
909api.get("/repos/:owner/:repo/hooks", async (c) => {
910 const { stub } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
911 return c.json(paginate(c, (await stub.webhooks()).map(({ secret: _s, ...h }) => hookJson(c, h))));
912});
913api.post("/repos/:owner/:repo/hooks", async (c) => {
914 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
915 const b = await body<{ config: { url: string; secret?: string }; events?: string[] }>(c);
916 if (typeof b.config?.url !== "string") throw new HttpError(422, "config.url is required", { errors: [{ resource: "Hook", code: "missing_field", field: "config.url" }] });
917 const created = await stub.createWebhook(b.config.url, Array.isArray(b.events) ? b.events.map(String) : ["*"], b.config.secret);
918 const hook = (await stub.webhooks()).find((h) => h.id === created.id)!;
919 auditRepo(c, caller, repo, "repo.webhook.create", { id: created.id, url: b.config.url });
920 // The generated secret is shown once, here (GitHub never returns secrets; Diffinery makes one when none is given).
921 return c.json({ ...hookJson(c, { ...hook, secret: undefined }), secret: b.config.secret ? undefined : created.secret }, 201);
922});
923api.delete("/repos/:owner/:repo/hooks/:id", async (c) => {
924 const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin");
925 await stub.deleteWebhook(c.req.param("id"));
926 auditRepo(c, caller, repo, "repo.webhook.delete", { id: c.req.param("id") });
927 return c.body(null, 204);
928});
929
930// ---------------------------------------------------------------- Diffinery: tokens, agents, sandboxes, notifications
931
932api.get("/diffinery/tokens", async (c) => c.json(await c.get("dir").tokens(requireAccount(c).id)));
933api.post("/diffinery/tokens", async (c) => {
934 // Minting a token needs a browser session: no token (however wide) can create another.
935 const a = requireBrowserSession(c);
936 const b = await body<{ name: string; scopes?: TokenScope[]; repositories?: string[]; expires_in_days?: number }>(c);
937 const scopes = parseScopes(b.scopes);
938 let repoIds: string[] | null = null;
939 if (b.repositories?.length) {
940 repoIds = [];
941 for (const full of b.repositories) {
942 const [o, n] = full.split("/");
943 const r = o && n ? ((await c.get("dir").repo(o, n)) ?? (await c.get("dir").movedRepo(o, n))) : null;
944 // Repositories the account can't see are "unknown", so this doesn't reveal private ones.
945 if (!r || !(await callerFor(c, r))) throw new HttpError(422, `unknown repository ${full}`);
946 repoIds.push(r.id);
947 }
948 }
949 const t = await c.get("dir").createToken(a, { name: b.name, scopes, repoIds, expiresInDays: b.expires_in_days });
950 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: a.id, actorLogin: a.login, action: "token.create", detail: { name: b.name, scopes } }));
951 return c.json(t, 201);
952});
953api.delete("/diffinery/tokens/:id", async (c) => {
954 requireAccountScope(c, "admin");
955 const a = requireAccount(c);
956 await c.get("dir").revokeToken(a.id, c.req.param("id"));
957 c.executionCtx.waitUntil(c.get("dir").audit({ actorId: a.id, actorLogin: a.login, action: "token.revoke", target: c.req.param("id"), detail: { via: "api" } }));
958 return c.body(null, 204);
959});
960api.get("/diffinery/agents", async (c) => {
961 const a = requireAccount(c);
962 const orgs = (await c.get("dir").orgsFor(a.id)).filter((o) => o.role !== "member").map((o) => o.id);
963 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) : {} })));
964});
965api.post("/diffinery/agents", async (c) => {
966 // Creating an agent mints its first token, so it needs a browser session too.
967 const a = requireBrowserSession(c);
968 if (a.kind !== "user") throw new HttpError(403, "only people can create agents");
969 const b = await body<{ login: string; name?: string; org?: string; policy?: Record<string, unknown>; token?: { scopes?: TokenScope[]; expires_in_days?: number } }>(c);
970 const dir = c.get("dir");
971 const org = b.org ? await dir.accountByLogin(b.org) : null;
972 const agent = await dir.createAgent(a, { login: b.login, name: b.name, orgId: org?.id, policy: b.policy });
973 const token = await dir.createToken(agent, { name: "default", scopes: parseScopes(b.token?.scopes), expiresInDays: b.token?.expires_in_days ?? 90 });
974 c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "agent.create", target: agent.login }));
975 return c.json({ agent: userJson(c, agent), token }, 201);
976});
977api.post("/diffinery/agents/:login/tokens", async (c) => {
978 const a = requireBrowserSession(c);
979 const dir = c.get("dir");
980 const agent = await dir.accountByLogin(c.req.param("login"));
981 if (!agent || agent.kind !== "agent") throw new HttpError(404, "agent not found");
982 const orgRole = agent.owner_id && agent.owner_id !== a.id ? await dir.orgRole(agent.owner_id, a.id) : null;
983 if (agent.owner_id !== a.id && orgRole !== "owner" && orgRole !== "admin") throw new HttpError(403, "not your agent");
984 const b = await body<{ name?: string; scopes?: TokenScope[]; expires_in_days?: number }>(c).catch(() => ({}) as Record<string, undefined>);
985 const scopes = parseScopes(b.scopes);
986 const t = await dir.createToken(agent, { name: b.name ?? "token", scopes, expiresInDays: b.expires_in_days });
987 c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "agent.token.create", target: agent.login, detail: { scopes } }));
988 return c.json(t, 201);
989});
990api.delete("/diffinery/agents/:login", async (c) => {
991 requireAccountScope(c, "admin");
992 const a = requireAccount(c);
993 const dir = c.get("dir");
994 const agent = await dir.accountByLogin(c.req.param("login"));
995 if (!agent || agent.kind !== "agent") throw new HttpError(404, "agent not found");
996 const orgRole = agent.owner_id && agent.owner_id !== a.id ? await dir.orgRole(agent.owner_id, a.id) : null;
997 if (agent.owner_id !== a.id && orgRole !== "owner" && orgRole !== "admin" && !a.site_admin) throw new HttpError(403, "not your agent");
998 await dir.setStatus(agent.id, "disabled");
999 c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "agent.disable", target: agent.login }));
1000 return c.body(null, 204);
1001});
1002
1003api.post("/repos/:owner/:repo/diffinery/sandboxes", async (c) => {
1004 // A sandbox's token outlives the job that would start it, so job and sandbox tokens can't start one.
1005 if (c.get("principal").type === "repo-token") throw new HttpError(403, "job and sandbox tokens can't start sandboxes");
1006 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
1007 const b = await body<{ ref?: string }>(c).catch(() => ({}) as { ref?: string });
1008 return c.json(await stub.createSandbox(caller, b.ref), 201);
1009});
1010api.post("/repos/:owner/:repo/diffinery/sandboxes/:id/:action", async (c) => {
1011 const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write");
1012 const id = c.req.param("id");
1013 const action = c.req.param("action");
1014 await stub.sandbox(id, caller);
1015 if (action === "close") {
1016 await stub.closeSandbox(id, caller);
1017 return c.body(null, 204);
1018 }
1019 const map: Record<string, string> = { exec: "/exec", read: "/files/read", write: "/files/write" };
1020 if (!map[action]) throw new HttpError(404, "unknown sandbox action");
1021 const res = await c.env.SANDBOX.get(c.env.SANDBOX.idFromName(id)).call(map[action]!, JSON.stringify(await c.req.json().catch(() => ({}))));
1022 return new Response(res.body, { status: res.status, headers: { "content-type": res.json ? "application/json" : "text/plain; charset=utf-8" } });
1023});
1024
1025api.get("/notifications", async (c) => c.json(await c.get("dir").notifications(requireAccount(c).id, c.req.query("all") !== "true")));
1026api.put("/notifications", async (c) => {
1027 requireAccountScope(c, "write");
1028 await c.get("dir").markRead(requireAccount(c).id);
1029 return c.body(null, 205);
1030});
1031
1032// OIDC discovery for workflow id tokens.
1033export const wellKnown = new Hono<{ Bindings: Env; Variables: AppVars }>();
1034wellKnown.get("/.well-known/openid-configuration", (c) =>
1035 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", "ref", "sha", "workflow", "actor", "run_id"] }),
1036);
1037wellKnown.get("/.well-known/jwks", (c) => c.json({ keys: c.env.OIDC_PRIVATE_KEY ? [publicJwk(JSON.parse(c.env.OIDC_PRIVATE_KEY))] : [] }));
1038
1039// ---------------------------------------------------------------- GitHub JSON helpers used above
1040
1041function permissionsOf(role: Role) {
1042 return { admin: role === "admin", maintain: role === "admin" || role === "maintain", push: role !== "read" && role !== "triage", triage: role !== "read", pull: true };
1043}
1044
1045function refJson(c: AppContext, r: { ref: string; sha: string; type: string }) {
1046 return ghRef(baseOf(c), P(c).owner, P(c).repo, r);
1047}
1048
1049function contentJson(c: AppContext, ref: string, path: string, sha: string, size: number, type: string) {
1050 const b = baseOf(c);
1051 const api = repoApi(b, P(c).owner, P(c).repo);
1052 const html = repoHtml(b, P(c).owner, P(c).repo);
1053 const self = `${api}/contents/${encPath(path)}?ref=${encodeURIComponent(ref)}`;
1054 const git = `${api}/git/${type === "dir" ? "trees" : "blobs"}/${sha}`;
1055 const htmlUrl = `${html}/${type === "dir" ? "tree" : "blob"}/${encPath(ref)}/${encPath(path)}`;
1056 return {
1057 type,
1058 size: type === "dir" ? 0 : size,
1059 name: path.split("/").pop() ?? path,
1060 path,
1061 sha,
1062 url: self,
1063 git_url: git,
1064 html_url: htmlUrl,
1065 download_url: type === "file" || type === "symlink" ? `${html}/raw/${encPath(ref)}/${encPath(path)}` : null,
1066 _links: { self, git, html: htmlUrl },
1067 };
1068}
1069
1070function gitCommitJson(c: AppContext, x: CommitInfo) {
1071 return ghGitCommit(baseOf(c), P(c).owner, P(c).repo, x);
1072}
1073
1074function checkRunJson(c: AppContext, r: Parameters<typeof ghCheckRun>[3]) {
1075 return ghCheckRun(baseOf(c), P(c).owner, P(c).repo, r);
1076}
1077
1078function jobJson(c: AppContext, owner: string, repo: string, run: RunInfo, j: JobInfo): Record<string, unknown> {
1079 return ghJob(baseOf(c), owner, repo, run, j);
1080}
1081
1082function hookJson(c: AppContext, h: { id: string; url: string; events: string[]; active: boolean; createdAt: string; lastStatus: number | null; lastDeliveryAt: string | null; secret?: string }) {
1083 const api = repoApi(baseOf(c), P(c).owner, P(c).repo);
1084 return {
1085 type: "Repository",
1086 id: h.id,
1087 name: "web",
1088 active: h.active,
1089 events: h.events,
1090 config: { url: h.url, content_type: "json", insecure_ssl: "0", ...(h.secret ? { secret: "********" } : {}) },
1091 updated_at: isoSeconds(h.lastDeliveryAt ?? h.createdAt),
1092 created_at: isoSeconds(h.createdAt),
1093 url: `${api}/hooks/${h.id}`,
1094 ping_url: `${api}/hooks/${h.id}/pings`,
1095 deliveries_url: `${api}/hooks/${h.id}/deliveries`,
1096 last_response: { code: h.lastStatus, status: h.lastStatus === null ? "unused" : h.lastStatus >= 200 && h.lastStatus < 300 ? "active" : "failed", message: null },
1097 };
1098}
1099
1100export { fromUtf8 };