| 1 | import { Hono } from "hono"; |
| 2 | import { fromUtf8 } from "@diffinery/git-core"; |
| 3 | import type { Env } from "../env.js"; |
| 4 | import { callerFor, parseScopes, requireAccount, requireAccountScope, requireBrowserSession, type AppContext, type AppVars } from "../auth/principal.js"; |
| 5 | import { baseRole, type Account, type Directory, type Repo, type TokenScope } from "../lib/directory.js"; |
| 6 | import { encryptSecret } from "../lib/crypto.js"; |
| 7 | import { publicJwk } from "../lib/jwt.js"; |
| 8 | import { HttpError, b64, fromB64 } from "../lib/util.js"; |
| 9 | import { atLeast, type ProtectionRules, type Role } from "../repo/types.js"; |
| 10 | import type { JobInfo, RunInfo } from "../repo/actions.js"; |
| 11 | import type { CommitInfo } from "../repo/RepoDO.js"; |
| 12 | import type { QueueEntry } from "../repo/queue.js"; |
| 13 | import { imports } from "./imports.js"; |
| 14 | import { agenticApi } from "../agentic/api.js"; |
| 15 | import { auditRepo, loadRepo, refuseAgent, repoStub } from "./common.js"; |
| 16 | import { repoCreated } from "../mail/notify.js"; |
| 17 | import { actionsRest } from "./actions-runtime.js"; |
| 18 | import { compat } from "./compat.js"; |
| 19 | import { 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"; |
| 20 | import { 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 | */ |
| 26 | export 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. |
| 30 | api.route("/", compat); |
| 31 | |
| 32 | const userJson = (c: AppContext, a: Pick<Account, "id" | "login" | "kind" | "name">) => ({ ...ghUser(baseOf(c), a)!, name: a.name || null }); |
| 33 | |
| 34 | const repoJson = repoOut; |
| 35 | |
| 36 | async 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. */ |
| 45 | const viaToken = (c: AppContext) => { |
| 46 | const p = c.get("principal"); |
| 47 | return p.type === "account" && p.via === "token"; |
| 48 | }; |
| 49 | const P = (c: AppContext) => ({ owner: c.req.param("owner")!, repo: c.req.param("repo")! }); |
| 50 | const 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. |
| 57 | api.route("/", imports); |
| 58 | // Agentic work: the Today view (agentic/). |
| 59 | api.route("/", agenticApi); |
| 60 | |
| 61 | // ---------------------------------------------------------------- meta & users |
| 62 | |
| 63 | api.get("/", (c) => c.json({ name: "Diffinery", api: "v3", docs: `${c.env.PUBLIC_URL}/docs/api`, mcp: `${c.env.PUBLIC_URL}/mcp` })); |
| 64 | api.get("/meta", (c) => c.json({ name: "Diffinery", oidc: !!c.env.OIDC_PRIVATE_KEY })); |
| 65 | api.get("/user", (c) => { |
| 66 | const a = requireAccount(c); |
| 67 | return c.json({ ...userJson(c, a), email: a.email, site_admin: !!a.site_admin }); |
| 68 | }); |
| 69 | api.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 | }); |
| 75 | api.get("/user/orgs", async (c) => c.json((await c.get("dir").orgsFor(requireAccount(c).id)).map((o) => ({ ...userJson(c, o), role: o.role })))); |
| 76 | api.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). |
| 85 | const orgJson = async (c: AppContext, org: Account, me: Account) => ({ ...userJson(c, org), ...((await c.get("dir").inOrg(org.id, me)) ? { default_repository_permission: baseRole(org) } : {}) }); |
| 86 | api.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 | }); |
| 92 | api.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). |
| 107 | api.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 | }); |
| 120 | api.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 | }); |
| 128 | api.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. |
| 144 | api.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). |
| 158 | const 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 }); |
| 159 | const 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 | }; |
| 170 | const 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 | }; |
| 176 | api.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 | }); |
| 180 | api.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 | }); |
| 185 | api.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 | }); |
| 189 | api.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 | }); |
| 195 | api.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 | }); |
| 200 | api.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 | |
| 208 | api.get("/user/repos", async (c) => c.json(paginate(c, (await c.get("dir").reposVisibleTo(requireAccount(c))).map((r) => repoJson(c, r))))); |
| 209 | api.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 | }); |
| 218 | api.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 | }); |
| 224 | api.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 | }); |
| 230 | api.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 | }); |
| 240 | api.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 | }); |
| 245 | api.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 | }); |
| 257 | api.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. |
| 266 | api.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 | }); |
| 281 | api.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 | }); |
| 285 | api.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 | }); |
| 296 | api.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 | |
| 308 | api.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 | }); |
| 315 | api.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 | }); |
| 330 | api.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). |
| 337 | api.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 | }); |
| 347 | api.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 | }); |
| 355 | api.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 | }); |
| 363 | api.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 | }); |
| 368 | api.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 | }); |
| 386 | api.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 | }); |
| 394 | api.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. |
| 426 | async 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 | } |
| 442 | api.get("/repos/:owner/:repo/contents/*", getContents); |
| 443 | api.get("/repos/:owner/:repo/contents", getContents); |
| 444 | api.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 | }); |
| 460 | api.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. */ |
| 469 | api.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 | |
| 477 | api.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 | |
| 487 | api.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 | }); |
| 493 | api.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 | }); |
| 501 | api.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). */ |
| 512 | const 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`. */ |
| 514 | const 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; |
| 516 | const sortParam = (v: string | undefined) => (v === "updated" || v === "comments" || v === "created" ? v : undefined); |
| 517 | |
| 518 | for (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 | } |
| 549 | api.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 | }); |
| 556 | api.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 | }); |
| 560 | api.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 | }); |
| 575 | api.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 | }); |
| 584 | api.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 | }); |
| 593 | api.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 | }); |
| 601 | api.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 | }); |
| 605 | api.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 | |
| 611 | api.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 | }); |
| 618 | api.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 | }); |
| 622 | api.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 | }); |
| 631 | api.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 | }); |
| 636 | api.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. |
| 642 | api.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 | }); |
| 652 | api.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). |
| 660 | const 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 | }); |
| 674 | api.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 | }); |
| 680 | api.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 | }); |
| 686 | api.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). |
| 692 | api.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 }>(c).catch(() => ({}) as Record<string, undefined>); |
| 695 | const r = await stub.enableAutoMerge(num(c), { method: b.merge_method, commitTitle: b.commit_title, commitMessage: b.commit_message }, caller); |
| 696 | return c.json({ state: r.state, auto_merge: ghAutoMerge(baseOf(c), r.autoMerge), merge_commit_sha: r.mergeCommit ?? null }); |
| 697 | }); |
| 698 | api.delete("/repos/:owner/:repo/pulls/:number/auto-merge", async (c) => { |
| 699 | const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write"); |
| 700 | await stub.disableAutoMerge(num(c), caller); |
| 701 | return c.body(null, 204); |
| 702 | }); |
| 703 | api.get("/repos/:owner/:repo/pulls/:number/reviews", async (c) => { |
| 704 | const { stub, repo } = await loadRepo(c, P(c).owner, P(c).repo); |
| 705 | const n = num(c); |
| 706 | const x = await issueCtx(c, repo, stub, []); |
| 707 | return c.json(paginate(c, (await stub.issue(n)).reviews.map((r) => ghReview(x, n, r)))); |
| 708 | }); |
| 709 | api.post("/repos/:owner/:repo/pulls/:number/reviews", async (c) => { |
| 710 | const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo); |
| 711 | const n = num(c); |
| 712 | 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); |
| 713 | 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" }] }); |
| 714 | 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; |
| 715 | 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" }] }); |
| 716 | const r = await stub.submitReview(n, { event: b.event ?? "COMMENT", body: b.body, comments }, caller); |
| 717 | return c.json(ghReview(await issueCtx(c, repo, stub, []), n, r), 201); |
| 718 | }); |
| 719 | api.get("/repos/:owner/:repo/pulls/:number/comments", async (c) => { |
| 720 | const { stub, repo } = await loadRepo(c, P(c).owner, P(c).repo); |
| 721 | const n = num(c); |
| 722 | const list = paginate(c, (await stub.issue(n)).comments.filter((x) => x.reviewId)); |
| 723 | const x = await issueCtx(c, repo, stub, [], list.map((cm) => `review_comment:${cm.id}`)); |
| 724 | return c.json(list.map((cm) => ghReviewComment(x, n, cm))); |
| 725 | }); |
| 726 | api.post("/repos/:owner/:repo/pulls/:number/requested_reviewers", async (c) => { |
| 727 | const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo); |
| 728 | const n = num(c); |
| 729 | const b = await body<{ reviewers?: string[]; team_reviewers?: string[] }>(c); |
| 730 | if (b.team_reviewers?.length) throw new HttpError(422, "team reviewers are not supported; request people by login"); |
| 731 | await stub.requestReviewers(n, (b.reviewers ?? []).map(String), caller); |
| 732 | return c.json((await pullsOut(c, repo, stub, [(await stub.issue(n)).issue]))[0], 201); |
| 733 | }); |
| 734 | |
| 735 | // ---------------------------------------------------------------- checks (for plugins and external CI) |
| 736 | |
| 737 | api.get("/repos/:owner/:repo/commits/:ref/check-runs", async (c) => { |
| 738 | const { stub } = await loadRepo(c, P(c).owner, P(c).repo); |
| 739 | const sha = await stub.resolve(c.req.param("ref")); |
| 740 | if (!sha) throw new HttpError(404, "ref not found"); |
| 741 | let runs = await stub.checks(sha); |
| 742 | const name = c.req.query("check_name"); |
| 743 | const status = c.req.query("status"); |
| 744 | if (name) runs = runs.filter((r) => r.name === name); |
| 745 | if (status) runs = runs.filter((r) => r.status === status); |
| 746 | const page = paginate(c, runs); |
| 747 | return c.json({ total_count: runs.length, check_runs: page.map((r) => checkRunJson(c, r)) }); |
| 748 | }); |
| 749 | api.post("/repos/:owner/:repo/check-runs", async (c) => { |
| 750 | const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write"); |
| 751 | 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); |
| 752 | 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" }] }); |
| 753 | if (caller.login.toLowerCase().startsWith("diffinery-actions")) throw new HttpError(403, "this account can't report check runs"); |
| 754 | const sha = typeof b.head_sha === "string" ? await stub.resolve(b.head_sha) : null; |
| 755 | if (!sha) throw new HttpError(422, "head_sha is not a commit in this repository", { errors: [{ resource: "CheckRun", code: "invalid", field: "head_sha" }] }); |
| 756 | const status = b.conclusion ? "completed" : (b.status ?? "queued"); |
| 757 | const { annotations: _a, text: _t, ...output } = b.output ?? {}; |
| 758 | 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 } }); |
| 759 | 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); |
| 760 | return c.json(checkRunJson(c, check), 201); |
| 761 | }); |
| 762 | |
| 763 | // ---------------------------------------------------------------- actions |
| 764 | |
| 765 | const runJson = (c: AppContext, owner: string, repo: string, r: RunInfo) => ghRun(baseOf(c), owner, repo, r); |
| 766 | |
| 767 | api.get("/repos/:owner/:repo/actions/workflows", async (c) => { |
| 768 | const { stub } = await loadRepo(c, P(c).owner, P(c).repo); |
| 769 | const wfs = await stub.workflows(); |
| 770 | 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 })) }); |
| 771 | }); |
| 772 | api.post("/repos/:owner/:repo/actions/workflows/:workflow/dispatches", async (c) => { |
| 773 | const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write"); |
| 774 | const b = await body<{ ref: string; inputs?: Record<string, unknown> }>(c); |
| 775 | const run = await stub.dispatchWorkflow(decodeURIComponent(c.req.param("workflow")), b.ref, b.inputs ?? {}, caller); |
| 776 | return c.json({ run_id: run.id, html_url: `${c.env.PUBLIC_URL}/${P(c).owner}/${P(c).repo}/actions/runs/${run.id}` }, 201); |
| 777 | }); |
| 778 | // Self-hosted runners poll this to pick up `runs-on: [self-hosted, ...]` jobs (see `diffinery runner`). |
| 779 | api.post("/repos/:owner/:repo/actions/runners/claim", async (c) => { |
| 780 | const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "admin"); |
| 781 | const b = await body<{ name?: string; labels?: string[] }>(c); |
| 782 | const job = await stub.claimJob(b.name ?? "runner", Array.isArray(b.labels) ? b.labels.map(String) : [], caller); |
| 783 | if (!job) return c.body(null, 204); |
| 784 | 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 }); |
| 785 | }); |
| 786 | api.get("/repos/:owner/:repo/actions/runs", async (c) => { |
| 787 | const { stub } = await loadRepo(c, P(c).owner, P(c).repo); |
| 788 | const perPage = Math.min(Number(c.req.query("per_page") ?? 25), 100); |
| 789 | const page = Number(c.req.query("page") ?? 1); |
| 790 | 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 }); |
| 791 | setLinks(c, { page, perPage, offset: (page - 1) * perPage }, res.total); |
| 792 | return c.json({ total_count: res.total, workflow_runs: res.runs.map((r) => runJson(c, P(c).owner, P(c).repo, r)) }); |
| 793 | }); |
| 794 | api.get("/repos/:owner/:repo/actions/runs/:id", async (c) => { |
| 795 | const { stub } = await loadRepo(c, P(c).owner, P(c).repo); |
| 796 | const r = await stub.run(c.req.param("id")); |
| 797 | return c.json({ ...runJson(c, P(c).owner, P(c).repo, r), jobs: r.jobs }); |
| 798 | }); |
| 799 | api.get("/repos/:owner/:repo/actions/runs/:id/jobs", async (c) => { |
| 800 | const { stub } = await loadRepo(c, P(c).owner, P(c).repo); |
| 801 | const run = await stub.run(c.req.param("id")); |
| 802 | const jobs = (await stub.runJobs(c.req.param("id"))) as unknown as JobInfo[]; |
| 803 | return c.json({ total_count: jobs.length, jobs: paginate(c, jobs).map((j) => jobJson(c, P(c).owner, P(c).repo, run, j)) }); |
| 804 | }); |
| 805 | api.post("/repos/:owner/:repo/actions/runs/:id/cancel", async (c) => { |
| 806 | const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write"); |
| 807 | await stub.cancelRun(c.req.param("id"), caller); |
| 808 | return c.json({}, 202); |
| 809 | }); |
| 810 | for (const path of ["rerun", "rerun-failed-jobs"]) { |
| 811 | api.post(`/repos/:owner/:repo/actions/runs/:id/${path}`, async (c) => { |
| 812 | const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write"); |
| 813 | const r = await stub.rerun(c.req.param("id"), caller); |
| 814 | return c.json({ run_id: r.id }, 201); |
| 815 | }); |
| 816 | } |
| 817 | api.get("/repos/:owner/:repo/actions/jobs/:id", async (c) => { |
| 818 | const { stub } = await loadRepo(c, P(c).owner, P(c).repo); |
| 819 | const job = (await stub.job(c.req.param("id"))) as unknown as JobInfo; |
| 820 | return c.json(jobJson(c, P(c).owner, P(c).repo, await stub.run(job.runId), job)); |
| 821 | }); |
| 822 | api.get("/repos/:owner/:repo/actions/jobs/:id/logs", async (c) => { |
| 823 | const { stub } = await loadRepo(c, P(c).owner, P(c).repo); |
| 824 | const { lines } = await stub.jobLogs(c.req.param("id"), Number(c.req.query("after") ?? -1)); |
| 825 | if (c.req.query("format") === "json") return c.json(lines); |
| 826 | return c.text(lines.map((l) => `${l.t} ${l.text}`).join("\n")); |
| 827 | }); |
| 828 | api.route("/", actionsRest); |
| 829 | api.get("/repos/:owner/:repo/actions/secrets", async (c) => { |
| 830 | const { stub } = await loadRepo(c, P(c).owner, P(c).repo, "admin"); |
| 831 | const s = await stub.secretNames(); |
| 832 | return c.json({ total_count: s.length, secrets: s.map((x) => ({ name: x.name, updated_at: x.updatedAt })) }); |
| 833 | }); |
| 834 | api.put("/repos/:owner/:repo/actions/secrets/:name", async (c) => { |
| 835 | const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin"); |
| 836 | if (caller.kind === "agent") throw new HttpError(403, "agents cannot manage secrets"); |
| 837 | const b = await body<{ value: string; encrypted_value?: string }>(c); |
| 838 | 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"); |
| 839 | if (typeof b.value !== "string") throw new HttpError(422, "value is required (send it over HTTPS; it is encrypted at rest)"); |
| 840 | await stub.setSecret(c.req.param("name"), b.value); |
| 841 | auditRepo(c, caller, repo, "repo.secret.set", { name: c.req.param("name").toUpperCase() }); |
| 842 | return c.body(null, 204); |
| 843 | }); |
| 844 | api.delete("/repos/:owner/:repo/actions/secrets/:name", async (c) => { |
| 845 | const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin"); |
| 846 | refuseAgent(caller, "secrets"); |
| 847 | await stub.deleteSecret(c.req.param("name")); |
| 848 | auditRepo(c, caller, repo, "repo.secret.delete", { name: c.req.param("name").toUpperCase() }); |
| 849 | return c.body(null, 204); |
| 850 | }); |
| 851 | api.get("/repos/:owner/:repo/actions/variables", async (c) => { |
| 852 | const { stub } = await loadRepo(c, P(c).owner, P(c).repo, "write"); |
| 853 | // The repository's own variables; organization variables are listed under /orgs/:org/actions/variables. |
| 854 | const all = Object.entries(await stub.variables(false)).map(([name, value]) => ({ name, value })); |
| 855 | return c.json({ total_count: all.length, variables: paginate(c, all) }); |
| 856 | }); |
| 857 | api.delete("/repos/:owner/:repo/actions/variables/:name", async (c) => { |
| 858 | const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin"); |
| 859 | refuseAgent(caller, "variables"); |
| 860 | await stub.setVariable(c.req.param("name"), null); |
| 861 | auditRepo(c, caller, repo, "repo.variable.delete", { name: c.req.param("name").toUpperCase() }); |
| 862 | return c.body(null, 204); |
| 863 | }); |
| 864 | api.put("/repos/:owner/:repo/actions/variables/:name", async (c) => { |
| 865 | const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin"); |
| 866 | refuseAgent(caller, "variables"); |
| 867 | await stub.setVariable(c.req.param("name"), (await body<{ value: string }>(c)).value); |
| 868 | auditRepo(c, caller, repo, "repo.variable.set", { name: c.req.param("name").toUpperCase() }); |
| 869 | return c.body(null, 204); |
| 870 | }); |
| 871 | async function orgAdmin(c: AppContext) { |
| 872 | requireAccountScope(c, "admin"); |
| 873 | const a = requireAccount(c); |
| 874 | if (a.kind === "agent") throw new HttpError(403, "agents cannot manage secrets"); |
| 875 | const dir = c.get("dir"); |
| 876 | const org = await dir.accountByLogin(c.req.param("org")!); |
| 877 | if (!org || org.kind !== "org") throw new HttpError(404, "not found"); |
| 878 | const role = await dir.orgRole(org.id, a.id); |
| 879 | if (role !== "owner" && role !== "admin" && !a.site_admin) throw new HttpError(403, "organization admins only"); |
| 880 | return { a, org }; |
| 881 | } |
| 882 | api.get("/orgs/:org/actions/secrets", async (c) => { |
| 883 | const { org } = await orgAdmin(c); |
| 884 | 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 }>(); |
| 885 | return c.json({ total_count: results.length, secrets: results }); |
| 886 | }); |
| 887 | api.delete("/orgs/:org/actions/secrets/:name", async (c) => { |
| 888 | const { a, org } = await orgAdmin(c); |
| 889 | 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(); |
| 890 | // Like GitHub: deleting a secret that doesn't exist is a 404, and nothing is audited. |
| 891 | if (!r.meta?.changes) throw new HttpError(404, "secret not found"); |
| 892 | 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" } })); |
| 893 | return c.body(null, 204); |
| 894 | }); |
| 895 | api.put("/orgs/:org/actions/secrets/:name", async (c) => { |
| 896 | const { a, org } = await orgAdmin(c); |
| 897 | const name = c.req.param("name").toUpperCase(); |
| 898 | if (!/^[A-Z_][A-Z0-9_]*$/.test(name)) throw new HttpError(422, "invalid secret name"); |
| 899 | const { value } = await body<{ value: string }>(c); |
| 900 | 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(); |
| 901 | c.executionCtx.waitUntil(c.get("dir").audit({ actorId: a.id, actorLogin: a.login, action: "org.secret.set", target: org.login, detail: { name, via: "api" } })); |
| 902 | return c.body(null, 204); |
| 903 | }); |
| 904 | |
| 905 | // ---------------------------------------------------------------- webhooks |
| 906 | |
| 907 | api.get("/repos/:owner/:repo/hooks", async (c) => { |
| 908 | const { stub } = await loadRepo(c, P(c).owner, P(c).repo, "admin"); |
| 909 | return c.json(paginate(c, (await stub.webhooks()).map(({ secret: _s, ...h }) => hookJson(c, h)))); |
| 910 | }); |
| 911 | api.post("/repos/:owner/:repo/hooks", async (c) => { |
| 912 | const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin"); |
| 913 | const b = await body<{ config: { url: string; secret?: string }; events?: string[] }>(c); |
| 914 | if (typeof b.config?.url !== "string") throw new HttpError(422, "config.url is required", { errors: [{ resource: "Hook", code: "missing_field", field: "config.url" }] }); |
| 915 | const created = await stub.createWebhook(b.config.url, Array.isArray(b.events) ? b.events.map(String) : ["*"], b.config.secret); |
| 916 | const hook = (await stub.webhooks()).find((h) => h.id === created.id)!; |
| 917 | auditRepo(c, caller, repo, "repo.webhook.create", { id: created.id, url: b.config.url }); |
| 918 | // The generated secret is shown once, here (GitHub never returns secrets; Diffinery makes one when none is given). |
| 919 | return c.json({ ...hookJson(c, { ...hook, secret: undefined }), secret: b.config.secret ? undefined : created.secret }, 201); |
| 920 | }); |
| 921 | api.delete("/repos/:owner/:repo/hooks/:id", async (c) => { |
| 922 | const { stub, caller, repo } = await loadRepo(c, P(c).owner, P(c).repo, "admin"); |
| 923 | await stub.deleteWebhook(c.req.param("id")); |
| 924 | auditRepo(c, caller, repo, "repo.webhook.delete", { id: c.req.param("id") }); |
| 925 | return c.body(null, 204); |
| 926 | }); |
| 927 | |
| 928 | // ---------------------------------------------------------------- Diffinery: tokens, agents, sandboxes, notifications |
| 929 | |
| 930 | api.get("/diffinery/tokens", async (c) => c.json(await c.get("dir").tokens(requireAccount(c).id))); |
| 931 | api.post("/diffinery/tokens", async (c) => { |
| 932 | // Minting a token needs a browser session: no token (however wide) can create another. |
| 933 | const a = requireBrowserSession(c); |
| 934 | const b = await body<{ name: string; scopes?: TokenScope[]; repositories?: string[]; expires_in_days?: number }>(c); |
| 935 | const scopes = parseScopes(b.scopes); |
| 936 | let repoIds: string[] | null = null; |
| 937 | if (b.repositories?.length) { |
| 938 | repoIds = []; |
| 939 | for (const full of b.repositories) { |
| 940 | const [o, n] = full.split("/"); |
| 941 | const r = o && n ? ((await c.get("dir").repo(o, n)) ?? (await c.get("dir").movedRepo(o, n))) : null; |
| 942 | // Repositories the account can't see are "unknown", so this doesn't reveal private ones. |
| 943 | if (!r || !(await callerFor(c, r))) throw new HttpError(422, `unknown repository ${full}`); |
| 944 | repoIds.push(r.id); |
| 945 | } |
| 946 | } |
| 947 | const t = await c.get("dir").createToken(a, { name: b.name, scopes, repoIds, expiresInDays: b.expires_in_days }); |
| 948 | c.executionCtx.waitUntil(c.get("dir").audit({ actorId: a.id, actorLogin: a.login, action: "token.create", detail: { name: b.name, scopes } })); |
| 949 | return c.json(t, 201); |
| 950 | }); |
| 951 | api.delete("/diffinery/tokens/:id", async (c) => { |
| 952 | requireAccountScope(c, "admin"); |
| 953 | await c.get("dir").revokeToken(requireAccount(c).id, c.req.param("id")); |
| 954 | return c.body(null, 204); |
| 955 | }); |
| 956 | api.get("/diffinery/agents", async (c) => { |
| 957 | const a = requireAccount(c); |
| 958 | const orgs = (await c.get("dir").orgsFor(a.id)).filter((o) => o.role !== "member").map((o) => o.id); |
| 959 | 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) : {} }))); |
| 960 | }); |
| 961 | api.post("/diffinery/agents", async (c) => { |
| 962 | // Creating an agent mints its first token, so it needs a browser session too. |
| 963 | const a = requireBrowserSession(c); |
| 964 | if (a.kind !== "user") throw new HttpError(403, "only people can create agents"); |
| 965 | const b = await body<{ login: string; name?: string; org?: string; policy?: Record<string, unknown>; token?: { scopes?: TokenScope[]; expires_in_days?: number } }>(c); |
| 966 | const dir = c.get("dir"); |
| 967 | const org = b.org ? await dir.accountByLogin(b.org) : null; |
| 968 | const agent = await dir.createAgent(a, { login: b.login, name: b.name, orgId: org?.id, policy: b.policy }); |
| 969 | const token = await dir.createToken(agent, { name: "default", scopes: parseScopes(b.token?.scopes), expiresInDays: b.token?.expires_in_days ?? 90 }); |
| 970 | c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "agent.create", target: agent.login })); |
| 971 | return c.json({ agent: userJson(c, agent), token }, 201); |
| 972 | }); |
| 973 | api.post("/diffinery/agents/:login/tokens", async (c) => { |
| 974 | const a = requireBrowserSession(c); |
| 975 | const dir = c.get("dir"); |
| 976 | const agent = await dir.accountByLogin(c.req.param("login")); |
| 977 | if (!agent || agent.kind !== "agent") throw new HttpError(404, "agent not found"); |
| 978 | const orgRole = agent.owner_id && agent.owner_id !== a.id ? await dir.orgRole(agent.owner_id, a.id) : null; |
| 979 | if (agent.owner_id !== a.id && orgRole !== "owner" && orgRole !== "admin") throw new HttpError(403, "not your agent"); |
| 980 | const b = await body<{ name?: string; scopes?: TokenScope[]; expires_in_days?: number }>(c).catch(() => ({}) as Record<string, undefined>); |
| 981 | const scopes = parseScopes(b.scopes); |
| 982 | const t = await dir.createToken(agent, { name: b.name ?? "token", scopes, expiresInDays: b.expires_in_days }); |
| 983 | c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "agent.token.create", target: agent.login, detail: { scopes } })); |
| 984 | return c.json(t, 201); |
| 985 | }); |
| 986 | api.delete("/diffinery/agents/:login", async (c) => { |
| 987 | requireAccountScope(c, "admin"); |
| 988 | const a = requireAccount(c); |
| 989 | const dir = c.get("dir"); |
| 990 | const agent = await dir.accountByLogin(c.req.param("login")); |
| 991 | if (!agent || agent.kind !== "agent") throw new HttpError(404, "agent not found"); |
| 992 | const orgRole = agent.owner_id && agent.owner_id !== a.id ? await dir.orgRole(agent.owner_id, a.id) : null; |
| 993 | if (agent.owner_id !== a.id && orgRole !== "owner" && orgRole !== "admin" && !a.site_admin) throw new HttpError(403, "not your agent"); |
| 994 | await dir.setStatus(agent.id, "disabled"); |
| 995 | c.executionCtx.waitUntil(dir.audit({ actorId: a.id, actorLogin: a.login, action: "agent.disable", target: agent.login })); |
| 996 | return c.body(null, 204); |
| 997 | }); |
| 998 | |
| 999 | api.post("/repos/:owner/:repo/diffinery/sandboxes", async (c) => { |
| 1000 | // A sandbox's token outlives the job that would start it, so job and sandbox tokens can't start one. |
| 1001 | if (c.get("principal").type === "repo-token") throw new HttpError(403, "job and sandbox tokens can't start sandboxes"); |
| 1002 | const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write"); |
| 1003 | const b = await body<{ ref?: string }>(c).catch(() => ({}) as { ref?: string }); |
| 1004 | return c.json(await stub.createSandbox(caller, b.ref), 201); |
| 1005 | }); |
| 1006 | api.post("/repos/:owner/:repo/diffinery/sandboxes/:id/:action", async (c) => { |
| 1007 | const { stub, caller } = await loadRepo(c, P(c).owner, P(c).repo, "write"); |
| 1008 | const id = c.req.param("id"); |
| 1009 | const action = c.req.param("action"); |
| 1010 | await stub.sandbox(id, caller); |
| 1011 | if (action === "close") { |
| 1012 | await stub.closeSandbox(id, caller); |
| 1013 | return c.body(null, 204); |
| 1014 | } |
| 1015 | const map: Record<string, string> = { exec: "/exec", read: "/files/read", write: "/files/write" }; |
| 1016 | if (!map[action]) throw new HttpError(404, "unknown sandbox action"); |
| 1017 | const res = await c.env.SANDBOX.get(c.env.SANDBOX.idFromName(id)).call(map[action]!, JSON.stringify(await c.req.json().catch(() => ({})))); |
| 1018 | return new Response(res.body, { status: res.status, headers: { "content-type": res.json ? "application/json" : "text/plain; charset=utf-8" } }); |
| 1019 | }); |
| 1020 | |
| 1021 | api.get("/notifications", async (c) => c.json(await c.get("dir").notifications(requireAccount(c).id, c.req.query("all") !== "true"))); |
| 1022 | api.put("/notifications", async (c) => { |
| 1023 | requireAccountScope(c, "write"); |
| 1024 | await c.get("dir").markRead(requireAccount(c).id); |
| 1025 | return c.body(null, 205); |
| 1026 | }); |
| 1027 | |
| 1028 | // OIDC discovery for workflow id tokens. |
| 1029 | export const wellKnown = new Hono<{ Bindings: Env; Variables: AppVars }>(); |
| 1030 | wellKnown.get("/.well-known/openid-configuration", (c) => |
| 1031 | 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"] }), |
| 1032 | ); |
| 1033 | wellKnown.get("/.well-known/jwks", (c) => c.json({ keys: c.env.OIDC_PRIVATE_KEY ? [publicJwk(JSON.parse(c.env.OIDC_PRIVATE_KEY))] : [] })); |
| 1034 | |
| 1035 | // ---------------------------------------------------------------- GitHub JSON helpers used above |
| 1036 | |
| 1037 | function permissionsOf(role: Role) { |
| 1038 | return { admin: role === "admin", maintain: role === "admin" || role === "maintain", push: role !== "read" && role !== "triage", triage: role !== "read", pull: true }; |
| 1039 | } |
| 1040 | |
| 1041 | function refJson(c: AppContext, r: { ref: string; sha: string; type: string }) { |
| 1042 | return ghRef(baseOf(c), P(c).owner, P(c).repo, r); |
| 1043 | } |
| 1044 | |
| 1045 | function contentJson(c: AppContext, ref: string, path: string, sha: string, size: number, type: string) { |
| 1046 | const b = baseOf(c); |
| 1047 | const api = repoApi(b, P(c).owner, P(c).repo); |
| 1048 | const html = repoHtml(b, P(c).owner, P(c).repo); |
| 1049 | const self = `${api}/contents/${encPath(path)}?ref=${encodeURIComponent(ref)}`; |
| 1050 | const git = `${api}/git/${type === "dir" ? "trees" : "blobs"}/${sha}`; |
| 1051 | const htmlUrl = `${html}/${type === "dir" ? "tree" : "blob"}/${encPath(ref)}/${encPath(path)}`; |
| 1052 | return { |
| 1053 | type, |
| 1054 | size: type === "dir" ? 0 : size, |
| 1055 | name: path.split("/").pop() ?? path, |
| 1056 | path, |
| 1057 | sha, |
| 1058 | url: self, |
| 1059 | git_url: git, |
| 1060 | html_url: htmlUrl, |
| 1061 | download_url: type === "file" || type === "symlink" ? `${html}/raw/${encPath(ref)}/${encPath(path)}` : null, |
| 1062 | _links: { self, git, html: htmlUrl }, |
| 1063 | }; |
| 1064 | } |
| 1065 | |
| 1066 | function gitCommitJson(c: AppContext, x: CommitInfo) { |
| 1067 | return ghGitCommit(baseOf(c), P(c).owner, P(c).repo, x); |
| 1068 | } |
| 1069 | |
| 1070 | function checkRunJson(c: AppContext, r: Parameters<typeof ghCheckRun>[3]) { |
| 1071 | return ghCheckRun(baseOf(c), P(c).owner, P(c).repo, r); |
| 1072 | } |
| 1073 | |
| 1074 | function jobJson(c: AppContext, owner: string, repo: string, run: RunInfo, j: JobInfo): Record<string, unknown> { |
| 1075 | return ghJob(baseOf(c), owner, repo, run, j); |
| 1076 | } |
| 1077 | |
| 1078 | function hookJson(c: AppContext, h: { id: string; url: string; events: string[]; active: boolean; createdAt: string; lastStatus: number | null; lastDeliveryAt: string | null; secret?: string }) { |
| 1079 | const api = repoApi(baseOf(c), P(c).owner, P(c).repo); |
| 1080 | return { |
| 1081 | type: "Repository", |
| 1082 | id: h.id, |
| 1083 | name: "web", |
| 1084 | active: h.active, |
| 1085 | events: h.events, |
| 1086 | config: { url: h.url, content_type: "json", insecure_ssl: "0", ...(h.secret ? { secret: "********" } : {}) }, |
| 1087 | updated_at: isoSeconds(h.lastDeliveryAt ?? h.createdAt), |
| 1088 | created_at: isoSeconds(h.createdAt), |
| 1089 | url: `${api}/hooks/${h.id}`, |
| 1090 | ping_url: `${api}/hooks/${h.id}/pings`, |
| 1091 | deliveries_url: `${api}/hooks/${h.id}/deliveries`, |
| 1092 | last_response: { code: h.lastStatus, status: h.lastStatus === null ? "unused" : h.lastStatus >= 200 && h.lastStatus < 300 ? "active" : "failed", message: null }, |
| 1093 | }; |
| 1094 | } |
| 1095 | |
| 1096 | export { fromUtf8 }; |