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