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.

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