gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchw63-force-push52576cb0force push: defer on a failed scan, one-to-one pairs, docs (#56)mrew63-force-push/lib/api.hl

28.9 KB

  1. // lib/api.hl — THE FUNCTION ROUTES (project.hl wires them): thin wrappers — check the request and the session, call the
  2. // topic, answer. The plumbing (JSON / Markdown / plain answers, redirects, the ssh guard, `?next=`) is lib/api-helpers.hl.
  3. // /api/repos, /api/repos/:slug the public reads (repos.hl; Accept: text/markdown → the Markdown read view)
  4. // /login/callback the login button's return (users.hl)
  5. // /settings/connect, /settings/connected connecting a repo to a tickets project (tickets.hl)
  6. // /api/apps/token an app trades its key for a one-hour token (app-tokens.hl, gitoria#42)
  7. // /settings/apps/connect, /settings/apps/confirm, /api/apps/exchange connecting an app to a repo (apps.hl, gitoria#41)
  8. // POST /api/pulls/N/merge a repo member merges a PR with a gtr_ token (gitoria#48, apiMergePull)
  9. // /api/pulls… an app reads PRs, posts reviews with inline threads, replies, resolves, comments (reviews.hl, gitoria#44)
  10. // /__git/keys, /__git/access what the sshd container asks (sshkeys.hl, repos.hl)
  11. // (The git protocol's routes are lib/transport.hl gitTransport.)
  12. // A route that WRITES THE SESSION gets the request and the framework's session store BY REFERENCE (`&req`, `&sessions`,
  13. // from project.hl): copied into a second call, the session inside `req` would be a copy too and the write would be lost.
  14. import { Response } from 'hl:http1'
  15. import { randomBytes } from 'hl:crypto'
  16. import { NL, px, slugOfHost } from './util.hl'
  17. import { login, failedLogin } from './users.hl'
  18. import { createOrgFromInput, orgMemberNames, transferOrg, moveRepoFromInput, confirmedTransfer, changeMember, repoMemberNames, createRepoFromInput, repoRows, repoRow, repoBySlug, orgFor, ownsRepo, mayPush, mayRead } from './repos.hl'
  19. import { fullNameError, repoDocument, listDocument } from './repos-helpers.hl'
  20. import { forwardOf } from './forwards.hl'
  21. import { userIdOfSession, userRecord } from './users.hl'
  22. import { startConnect, completeConnect } from './tickets.hl'
  23. import { keyLine } from './sshkeys.hl'
  24. import { urlAllowed, withQuery, formFields } from './apps-helpers.hl'
  25. import { nameError, makeCode, exchangeCode, appOfKey } from './apps.hl'
  26. import { issueToken } from './app-tokens.hl'
  27. import { repoUserRequest, orgUserRequest, userTokenRequest, bearerOf, unauthorized, notFound, tooMany, appOfRequest, readerOfRequest, publicReaderOfRequest, appTokenRequired } from './app-auth.hl'
  28. import { inputError, answerOf, jsonOfRequest, reply, fail, apiError, wantsMarkdown, markdownReply, textReply, goTo, sshGuard, repoOfRequest, safeNext } from './api-helpers.hl'
  29. import { ensurePulls, recordByNumber, pullObject } from './pullsync.hl'
  30. import { closePull, reopenPull } from './pulls.hl'
  31. import { mergeAndAnnounce } from './pullmerge.hl'
  32. import { numberOf } from './reviews-helpers.hl'
  33. import { prOfRequest } from './prpage.hl'
  34. import { listPulls, getPull, postReview, listReviews, listThreads, postReply, resolveThread, listComments, postComment } from './reviews.hl'
  35. import { putStatus, listStatuses } from './statuses.hl'
  36. import { isHexId } from './git-helpers.hl'
  37. import { limitCheck } from './limits.hl'
  38. import { syncAndRaise, deliveryPage, redeliver } from './events.hl'
  39. import { notifyPush } from './tickets.hl'
  40. // ---- the API: public reads and creation with a person's access token ------------------------
  41. static apiRepos = (route, req) => {
  42. if (req.method == 'POST') { return apiCreateRepo(route, req) }
  43. if (req.method != 'GET') { return fail(405, 'GET only') }
  44. rows = repoRows(userIdOfSession(req.session))
  45. if (wantsMarkdown(req)) { return markdownReply(listDocument(rows)) }
  46. return reply(200, { repos = rows })
  47. }
  48. // POST /api/repos: app tokens remain read-only; owner comes only from the gtr_ token.
  49. static apiCreateRepo = (route, req) => {
  50. who = userTokenRequest(req)
  51. if (who.error != null) { return who.error }
  52. j = jsonOfRequest(req)
  53. if (j.error != null) { return j.error }
  54. r = createRepoFromInput(who.uid, j.json)
  55. if (r.error != null) { return inputError(r) }
  56. return reply(201, r.repo)
  57. }
  58. // User-token ownership and membership routes; topic functions own every write.
  59. static apiCreateOrg = (Hybrid route, Hybrid req) => {
  60. if (req.method != 'POST') { return fail(405, 'POST only') }
  61. who = userTokenRequest(req)
  62. if (who.error != null) { return who.error }
  63. j = jsonOfRequest(req)
  64. if (j.error != null) { return j.error }
  65. r = createOrgFromInput(who.uid, j.json)
  66. if (r.error != null) { return inputError(r) }
  67. return reply(201, r.org)
  68. }
  69. static apiOrgMembers = (Hybrid route, Hybrid req) => {
  70. if (req.method != 'GET' && req.method != 'POST' && req.method != 'DELETE') { return fail(405, 'GET, POST or DELETE only') }
  71. who = orgUserRequest(route, req)
  72. if (who.error != null) { return who.error }
  73. if (req.method != 'GET') {
  74. j = jsonOfRequest(req)
  75. if (j.error != null) { return j.error }
  76. name = j.json.name
  77. if (hlTypeName(name) != 'String') { return apiError(422, 'invalid', 'name must be text', { field = 'name' }) }
  78. r = changeMember(who.uid, 'o', who.org.slug, name, req.method == 'POST')
  79. if (r.error != null) { return apiError(422, 'invalid', r.error, { field = 'name' }) }
  80. }
  81. return reply(200, orgMemberNames(who.uid, who.org.slug).members)
  82. }
  83. static apiOrgOwner = (Hybrid route, Hybrid req) => {
  84. if (req.method != 'POST') { return fail(405, 'POST only') }
  85. who = orgUserRequest(route, req)
  86. if (who.error != null) { return who.error }
  87. j = jsonOfRequest(req)
  88. if (j.error != null) { return j.error }
  89. if (hlTypeName(j.json.confirm) != 'String' || j.json.confirm != who.org.slug) { return apiError(422, 'invalid', 'type the organization name to confirm', { field = 'confirm' }) }
  90. if (hlTypeName(j.json.name) != 'String') { return apiError(422, 'invalid', 'name must be text', { field = 'name' }) }
  91. if (j.json.stayMember != null && hlTypeName(j.json.stayMember) != 'Boolean') { return apiError(422, 'invalid', 'stayMember must be true or false', { field = 'stayMember' }) }
  92. r = transferOrg(who.uid, who.org.slug, j.json.name, j.json.confirm, j.json.stayMember == true)
  93. if (r.error != null) { return inputError(r) }
  94. return reply(200, r.org)
  95. }
  96. static apiRepoMove = (Hybrid route, Hybrid req) => {
  97. if (req.method != 'POST') { return fail(405, 'POST only') }
  98. who = repoUserRequest(route, req, true)
  99. if (who.error != null) { return who.error }
  100. j = jsonOfRequest(req)
  101. if (j.error != null) { return j.error }
  102. r = moveRepoFromInput(who.uid, who.repo.slug, j.json)
  103. if (r.error != null) { return inputError(r) }
  104. return reply(200, r.repo)
  105. }
  106. static apiRepoMembers = (Hybrid route, Hybrid req) => {
  107. if (req.method != 'GET' && req.method != 'POST' && req.method != 'DELETE') { return fail(405, 'GET, POST or DELETE only') }
  108. who = repoUserRequest(route, req, req.method != 'GET')
  109. if (who.error != null) { return who.error }
  110. if (req.method != 'GET') {
  111. j = jsonOfRequest(req)
  112. if (j.error != null) { return j.error }
  113. name = j.json.name
  114. if (hlTypeName(name) != 'String') { return apiError(422, 'invalid', 'name must be text', { field = 'name' }) }
  115. r = changeMember(who.uid, 'r', who.repo.slug, name, req.method == 'POST')
  116. if (r.error != null) { return apiError(422, 'invalid', r.error, { field = 'name' }) }
  117. }
  118. return reply(200, repoMemberNames(who.uid, who.repo.slug).members)
  119. }
  120. static apiRepoOwner = (Hybrid route, Hybrid req) => {
  121. if (req.method != 'POST') { return fail(405, 'POST only') }
  122. who = repoUserRequest(route, req, true)
  123. if (who.error != null) { return who.error }
  124. j = jsonOfRequest(req)
  125. if (j.error != null) { return j.error }
  126. if (hlTypeName(j.json.confirm) != 'String' || j.json.confirm != who.repo.slug) { return apiError(422, 'invalid', 'type the repository name to confirm', { field = 'confirm' }) }
  127. if (hlTypeName(j.json.name) != 'String') { return apiError(422, 'invalid', 'name must be text', { field = 'name' }) }
  128. r = confirmedTransfer(who.uid, who.repo.slug, j.json.name, j.json.confirm)
  129. if (r.error != null) { return apiError(422, 'invalid', r.error, { field = r.field == null ? 'name' : r.field }) }
  130. return reply(200, r.repo)
  131. }
  132. static apiRepo = (route, req) => {
  133. if (req.method != 'GET') { return fail(405, 'GET only') }
  134. row = repoRow(route.params.slug, userIdOfSession(req.session))
  135. if (row == null) { return fail(404, 'no such repository') }
  136. if (wantsMarkdown(req)) { return markdownReply(repoDocument(row)) }
  137. return reply(200, row)
  138. }
  139. // ---- NOTHING ELSE (mission MG, as ident's notFoundPage): the last route of project.hl answers a path no route knows with the
  140. // shell's 404 page (components/notfound.hl) — status 404, the page rendered by the framework with the request's session and host
  141. static notFoundPage = (route, req, &srv, pageComponent) => {
  142. m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { path = req.path } path = req.path }
  143. res = srv.page(m, req.session, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers))
  144. res.status = 404
  145. return res
  146. }
  147. // `/:orepo` (GO34): on an organization's address (one the viewer may see) the first segment is a repo's Readme page, rendered like the 404 page is (a function route:
  148. // a stray single-segment path on any other address keeps its real 404 status — /.env, /host.js, a private organization's /x)
  149. static orgRepoPage = (route, req, &srv, pageComponent, missingComponent) => {
  150. h = req.headers['host']
  151. label = slugOfHost(h == null ? '' : h.split(':')[0])
  152. if (label == '' || orgFor(label, userIdOfSession(req.session)) == null) { return notFoundPage(route, req, &srv, missingComponent) }
  153. m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { orepo = req.path.slice(1) } path = req.path }
  154. return srv.page(m, req.session, srv.hostOf(h), srv.requestHeaders(req.headers))
  155. }
  156. // `/pulls/:n` and `/:orepo/pulls/:n` (gitoria#45): the PR's page when the repo is visible to the viewer and the number is one of its pull requests, else the
  157. // shell's 404 page (a function route, so the status is a real 404 for an unknown number)
  158. static pullPage = (route, req, &srv, pageComponent, missingComponent) => {
  159. h = req.headers['host']
  160. host = h == null ? '' : h.split(':')[0]
  161. orepo = route.params.orepo != null ? route.params.orepo : ''
  162. nText = route.params.n
  163. if (prOfRequest(host, orepo, req.session, nText) == null) { return notFoundPage(route, req, &srv, missingComponent) }
  164. m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { orepo = orepo n = nText } path = req.path }
  165. return srv.page(m, req.session, srv.hostOf(h), srv.requestHeaders(req.headers))
  166. }
  167. // any other /api path: the contract's JSON 404 (docs/apps-api.md §6)
  168. static notFoundApi = (route, req) => { return apiError(404, 'not_found', 'no such endpoint', null) }
  169. // ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident") ----------------------------
  170. // ident sends the browser back with ?ident_code= (and our ?next=); the code is exchanged here (users.hl userOfLoginCode),
  171. // the user goes into THIS browser's session (`req.session`, the cookie's — hybriel #11; minted when it brought none, on a GOOD code only),
  172. // then → `?next=` (api-helpers.hl safeNext). A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked
  173. // in the session, then → /login/failed.
  174. static loginFailed = (&req, &sessions, why) => {
  175. // no session (a crawler, no cookie): nothing is minted, saved or set — just the redirect; /login/failed shows its generic text (gitoria#25)
  176. if (req.session != null) { failedLogin(why, req.session, &sessions) }
  177. res = new Response('login failed: ' + why, { status = 302 headers = { 'Location' = '/login/failed' 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' } })
  178. return res
  179. }
  180. static loginCallback = (route, &req, &sessions) => {
  181. if (req.method != 'GET') { return loginFailed(&req, &sessions, 'GET only') }
  182. q = req.query != null ? req.query : {}
  183. code = q.ident_code
  184. if (code == null || code == '') { return loginFailed(&req, &sessions, 'ident sent no login code') }
  185. x = login(code, req.session, &sessions)
  186. if (x.error != null) { return loginFailed(&req, &sessions, x.error) }
  187. s = x.session
  188. res = new Response('logged in', { status = 302 headers = { 'Location' = safeNext(q.next) 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' 'Set-Cookie' = sessions.cookieHeader(s.id) } })
  189. return res
  190. }
  191. // ---- ONE LOGIN FOR THE MAIN ADDRESS AND EVERY REPO ADDRESS ---------------------------------------------------------------------
  192. // Nothing here: hl:web (batch 20) does it. The session cookie carries `Domain=.<host>` (project.hl sessionDomain); among several gitoriasid
  193. // cookies the signed-in one wins and is re-issued with the Domain (the stray host-only copy expires), and a signed-in cookie is re-issued when its
  194. // attributes change (a login from before the Domain was set moves to it on its next request) and otherwise once a day. Gate: tests/browser.mjs "gitoria#24".
  195. // ---- CONNECT A REPO TO A TICKETS PROJECT (gitoria#18; tickets.hl, components/settings.hl) ----------------------------
  196. // /settings/connect: the owner's click → a fresh nonce parked in the session (bound to the repo) → tickets' /connect.
  197. // /settings/connected: tickets' return with ?code&state → tickets.hl finishConnect (nonce, exchange, key stored per
  198. // repo) → back to /settings. A failure is a note on the settings page.
  199. static connectStart = (route, &req, &sessions) => {
  200. if (req.method != 'GET') { return fail(405, 'GET only') }
  201. repo = repoOfRequest(route, req)
  202. if (repo == null) { return fail(404, 'no such repository') }
  203. s = req.session
  204. if (s == null || !ownsRepo(repo.slug, s)) { return goTo(px(repo.slug) + '/settings') }
  205. return goTo(startConnect(repo.slug, s, &sessions))
  206. }
  207. static connectBack = (route, &req, &sessions) => {
  208. if (req.method != 'GET') { return fail(405, 'GET only') }
  209. repo = repoOfRequest(route, req)
  210. if (repo == null) { return fail(404, 'no such repository') }
  211. q = req.query != null ? req.query : {}
  212. x = completeConnect(repo.slug, req.session, q, &sessions)
  213. res = goTo(px(repo.slug) + '/settings')
  214. if (x.fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(x.session.id) }
  215. return res
  216. }
  217. // ---- WHAT THE SSHD CONTAINER ASKS (ticket gitoria#7; docker/sshd) — only with the shared secret (api-helpers.hl sshGuard)
  218. // GET /__git/keys?type=<ssh-ed25519>&key=<base64> sshd AuthorizedKeysCommand: the authorized_keys line for a known key
  219. // (sshkeys.hl keyLine), empty for an unknown one
  220. // GET /__git/access?user=<id>&slug=<slug>&write=0|1 gitoria-shell before it starts git: `ok` or 403. Read = every repo (public);
  221. // write = the repo's owner only (repos.hl mayPush — the same rule as the token on HTTPS, transport.hl)
  222. static gitKeys = (route, req) => {
  223. no = sshGuard(req)
  224. if (no != null) { return no }
  225. q = req.query != null ? req.query : {}
  226. return textReply(200, keyLine(q.type, q.key))
  227. }
  228. // GET /__git/pushed?user=<id>&slug=<slug>&phase=before|after gitoria-shell around a push over ssh (what transport.hl does for HTTPS):
  229. // before → the repo's existing pull requests are numbered (ensurePulls); after (git exited 0) → notifyPush + syncPulls for that user. `ok`; never an error for the push.
  230. static gitPushed = (route, req) => {
  231. no = sshGuard(req)
  232. if (no != null) { return no }
  233. q = req.query != null ? req.query : {}
  234. slug = q.slug
  235. if (slug == null || hlTypeName(slug) != 'String' || fullNameError(slug) != null) { return textReply(404, 'no such repository' + NL) }
  236. let repo = repoBySlug(slug)
  237. if (repo == null && forwardOf(slug) != null) { repo = repoBySlug(forwardOf(slug)) }
  238. if (repo == null || !mayPush(q.user, repo)) { return textReply(403, 'not allowed' + NL) }
  239. if (q.phase == 'before') { ensurePulls(repo.slug) }
  240. else if (q.phase == 'after') {
  241. notifyPush(repo.slug, false)
  242. syncAndRaise(repo.slug, q.user)
  243. } else { return textReply(400, 'phase is before or after' + NL) }
  244. return textReply(200, 'ok' + NL)
  245. }
  246. static gitAccess = (route, req) => {
  247. no = sshGuard(req)
  248. if (no != null) { return no }
  249. q = req.query != null ? req.query : {}
  250. slug = q.slug
  251. if (slug == null || hlTypeName(slug) != 'String' || fullNameError(slug) != null) { return textReply(404, 'no such repository' + NL) }
  252. let repo = repoBySlug(slug)
  253. if (repo == null && forwardOf(slug) != null) { repo = repoBySlug(forwardOf(slug)) }
  254. // the asker is the key's user: a repo they may not see does not exist for them (404, as over HTTPS)
  255. if (repo == null || !mayRead(q.user, repo)) { return textReply(404, 'no such repository' + NL) }
  256. if (q.write == '1' && !mayPush(q.user, repo)) { return textReply(403, 'only the owner or a member of this repository can push to it' + NL) }
  257. // the sshd container runs git in the repo's real folder: tell it the name (it differs after a move)
  258. return textReply(200, 'ok ' + repo.slug + NL)
  259. }
  260. // ---- CONNECT AN APP TO A REPO (gitoria#41; apps.hl, docs/apps-api.md §1 flow A) ----------------------------------------------------
  261. // /settings/apps/connect?app&hook&return&state: the app sends the owner's browser here. The four values are checked (the URL allow-list:
  262. // anything else is 400 invalid_url) and PARKED in the session with a nonce; then → the repo's settings page, which asks the person to sign in
  263. // (the same session goes on after the login) and, for the owner, shows "Connect <app> to <repo>?" with a Yes / No form.
  264. // /settings/apps/confirm (POST): the form's answer → the owner check, the nonce, a one-time code → redirect to return?code&state (No: return?error=denied&state).
  265. static appConnectStart = (route, &req, &sessions) => {
  266. if (req.method != 'GET') { return apiError(405, 'invalid', 'GET only', null) }
  267. repo = repoOfRequest(route, req)
  268. if (repo == null) { return apiError(404, 'not_found', 'no such repository', null) }
  269. q = req.query != null ? req.query : {}
  270. if (!urlAllowed(q.hook)) { return apiError(400, 'invalid_url', 'hook is not an allowed receiver address', { field = 'hook' }) }
  271. if (!urlAllowed(q['return'])) { return apiError(400, 'invalid_url', 'return is not an allowed address', { field = 'return' }) }
  272. bad = nameError(q.app)
  273. if (bad != null) { return apiError(422, 'invalid', bad, { field = 'app' }) }
  274. if (q.state == null || hlTypeName(q.state) != 'String' || q.state.length == 0 || q.state.length > 200) { return apiError(422, 'invalid', 'state is missing or too long', { field = 'state' }) }
  275. let s = req.session
  276. fresh = s == null
  277. if (fresh) { s = sessions.mint() }
  278. s.data.appConnect = { slug = repo.slug app = ('' + q.app).trim() hook = q.hook ret = q['return'] state = q.state nonce = randomBytes(16) }
  279. sessions.save(s)
  280. res = goTo(px(repo.slug) + '/settings')
  281. if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }
  282. return res
  283. }
  284. static appConnectConfirm = (route, &req, &sessions) => {
  285. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  286. repo = repoOfRequest(route, req)
  287. if (repo == null) { return apiError(404, 'not_found', 'no such repository', null) }
  288. home = px(repo.slug) + '/settings'
  289. let s = req.session
  290. if (s == null || userIdOfSession(s) == null || !ownsRepo(repo.slug, s)) { return goTo(home) }
  291. p = s.data.appConnect
  292. f = formFields(req.body)
  293. if (p == null || p.slug != repo.slug || f.nonce == null || f.nonce != p.nonce) { return goTo(home) }
  294. // one try: the parked request goes whatever the answer is
  295. s.data.appConnect = null
  296. sessions.save(s)
  297. if (f.decision != 'yes') { return goTo(withQuery(p.ret, { error = 'denied' state = p.state })) }
  298. code = makeCode(repo, p.app, p.hook, userIdOfSession(s))
  299. if (code == null) { return goTo(home) }
  300. return goTo(withQuery(p.ret, { code = code state = p.state }))
  301. }
  302. // POST /api/apps/exchange {"code"} (no auth): the app's server trades the code → { key, secret, api, repo, app } (apps.hl exchangeCode)
  303. static appExchange = (route, req) => {
  304. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  305. repo = repoOfRequest(route, req)
  306. if (repo == null) { return apiError(404, 'not_found', 'no such repository', null) }
  307. j = jsonOfRequest(req)
  308. if (j.error != null) { return j.error }
  309. x = exchangeCode(repo, j.json.code)
  310. if (x.notFound == true) { return apiError(404, 'not_found', 'unknown, used or expired code', null) }
  311. return reply(200, x.body)
  312. }
  313. // POST {api}/apps/token Authorization: Bearer gak_… → 200 { token, expires } (app-tokens.hl); the key must be the key of the repo the address names
  314. static appToken = (route, req) => {
  315. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  316. no = appTokenRequired(req)
  317. if (no != null) { return no }
  318. app = appOfKey(bearerOf(req))
  319. if (app == null) { return unauthorized() }
  320. repo = repoOfRequest(route, req)
  321. if (repo == null || repo.id != app.repo) { return notFound() }
  322. wait = limitCheck(app.id, req.method)
  323. if (wait > 0) { return tooMany(wait) }
  324. t = issueToken(app)
  325. if (t.error != null) { return apiError(500, 'internal', 'could not make a token', null) }
  326. return reply(200, { token = t.token expires = t.expires })
  327. }
  328. // GET {api}/deliveries?cursor=&limit= → { deliveries: [{ id, event, action, time, status, tries, lastCode }], next } — the app's OWN deliveries (events.hl)
  329. static appDeliveries = (route, req) => {
  330. if (req.method != 'GET') { return apiError(405, 'invalid', 'GET only', null) }
  331. who = appOfRequest(route, req)
  332. if (who.error != null) { return who.error }
  333. q = req.query != null ? req.query : {}
  334. return reply(200, deliveryPage(who.app.id, q.cursor, q.limit == null ? null : toNumber(q.limit)))
  335. }
  336. // POST {api}/deliveries/:id/redeliver → 202; the same delivery id goes out again. Another app's delivery (or none) is a 404, like any foreign thing
  337. static appRedeliver = (route, req) => {
  338. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  339. who = appOfRequest(route, req)
  340. if (who.error != null) { return who.error }
  341. if (!redeliver(who.app.id, route.params.id)) { return apiError(404, 'not_found', 'no such delivery', null) }
  342. return reply(202, { accepted = true })
  343. }
  344. // ---- the apps API's PR routes (gitoria#44; lib/reviews.hl does the work, these only check the method and the app, and answer)
  345. // GET {api}/pulls?state=&cursor=&limit=
  346. static appPulls = (route, req) => {
  347. if (req.method != 'GET') { return apiError(405, 'invalid', 'GET only', null) }
  348. who = readerOfRequest(route, req)
  349. if (who.error != null) { return who.error }
  350. return answerOf(listPulls(who.repo, req.query))
  351. }
  352. // POST {api}/pulls/N/merge Authorization: Bearer gtr_… body optional {"head":"<40 hex>"} (gitoria#48): a person who may push merges the PR once the required checks
  353. // are green (lib/pullmerge.hl, the same as the Merge button). Apps (gat_) never merge. → 200 { merged, mergeCommit, pull }
  354. static apiMergePull = (route, req) => {
  355. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  356. who = userTokenRequest(req, 'apps cannot merge')
  357. if (who.error != null) { return who.error }
  358. uid = who.uid
  359. repo = repoOfRequest(route, req)
  360. if (repo == null || !mayRead(uid, repo)) { return apiError(404, 'not_found', 'no such repository', null) }
  361. if (!mayPush(uid, repo)) { return apiError(403, 'forbidden', 'only the owner and the members of this repository can merge', null) }
  362. let head = ''
  363. if (req.body != null && req.body.trim() != '') {
  364. j = jsonOfRequest(req)
  365. if (j.error != null) { return j.error }
  366. h = j.json.head
  367. if (h != null) {
  368. if (hlTypeName(h) != 'String' || h.length != 40 || !isHexId(h)) { return apiError(422, 'invalid', 'head must be a 40 character commit id', [{ field = 'head' reason = 'must be 40 hex characters' }]) }
  369. head = h
  370. }
  371. }
  372. ensurePulls(repo.slug)
  373. n = numberOf(route.params.n)
  374. rec = n == null ? null : recordByNumber(repo.id, n)
  375. if (rec == null) { return apiError(404, 'not_found', 'no such pull request', null) }
  376. if (rec.state == 'merged') { return apiError(409, 'conflict', 'this pull request is already merged', { reason = 'already_merged' }) }
  377. r = mergeAndAnnounce(repo, rec.sha, userRecord(uid), head)
  378. if (r.error != null) {
  379. if (r.error == 'no such pull request') { return apiError(404, 'not_found', r.error, null) }
  380. if (r.reason == 'checks_failed') { return apiError(422, 'checks_failed', r.error, r.details, r.approval) }
  381. return apiError(409, 'conflict', r.error, { reason = r.reason })
  382. }
  383. return reply(200, { merged = true mergeCommit = r.mergeCommit pull = pullObject(repo.slug, rec.number) })
  384. }
  385. // GET {api}/pulls/N
  386. static appPull = (route, req) => {
  387. if (req.method != 'GET') { return apiError(405, 'invalid', 'GET only', null) }
  388. who = publicReaderOfRequest(route, req)
  389. if (who.error != null) { return who.error }
  390. return answerOf(getPull(who.repo, route.params.n))
  391. }
  392. // GET / POST {api}/pulls/N/reviews
  393. static appReviews = (route, req) => {
  394. if (req.method != 'GET' && req.method != 'POST') { return apiError(405, 'invalid', 'GET or POST only', null) }
  395. who = req.method == 'GET' ? readerOfRequest(route, req) : appOfRequest(route, req)
  396. if (who.error != null) { return who.error }
  397. if (req.method == 'GET') { return answerOf(listReviews(who.app, who.repo, route.params.n, req.query)) }
  398. j = jsonOfRequest(req)
  399. if (j.error != null) { return j.error }
  400. return answerOf(postReview(who.app, who.repo, route.params.n, j.json))
  401. }
  402. // GET {api}/pulls/N/threads
  403. static appThreads = (route, req) => {
  404. if (req.method != 'GET') { return apiError(405, 'invalid', 'GET only', null) }
  405. who = readerOfRequest(route, req)
  406. if (who.error != null) { return who.error }
  407. return answerOf(listThreads(who.app, who.repo, route.params.n, req.query))
  408. }
  409. // POST {api}/pulls/N/threads/:id/replies
  410. static appReply = (route, req) => {
  411. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  412. who = appOfRequest(route, req)
  413. if (who.error != null) { return who.error }
  414. j = jsonOfRequest(req)
  415. if (j.error != null) { return j.error }
  416. return answerOf(postReply(who.app, who.repo, route.params.n, route.params.id, j.json))
  417. }
  418. // POST {api}/pulls/N/threads/:id/resolve
  419. static appResolve = (route, req) => {
  420. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  421. who = appOfRequest(route, req)
  422. if (who.error != null) { return who.error }
  423. j = jsonOfRequest(req)
  424. if (j.error != null) { return j.error }
  425. return answerOf(resolveThread(who.app, who.repo, route.params.n, route.params.id, j.json))
  426. }
  427. // GET / POST {api}/pulls/N/comments (the PR's conversation)
  428. static appComments = (route, req) => {
  429. if (req.method != 'GET' && req.method != 'POST') { return apiError(405, 'invalid', 'GET or POST only', null) }
  430. who = req.method == 'GET' ? readerOfRequest(route, req) : appOfRequest(route, req)
  431. if (who.error != null) { return who.error }
  432. if (req.method == 'GET') { return answerOf(listComments(who.repo, route.params.n, req.query)) }
  433. j = jsonOfRequest(req)
  434. if (j.error != null) { return j.error }
  435. return answerOf(postComment(who.app, who.repo, route.params.n, j.json))
  436. }
  437. // PUT {api}/statuses/<sha> {"context","state","title","summary","url"} → 200 { status } (statuses.hl): the app sets the state of a commit, a newer PUT replaces the older one
  438. static appStatus = (route, req) => {
  439. if (req.method != 'PUT' && req.method != 'GET') { return apiError(405, 'invalid', 'GET or PUT only', null) }
  440. who = req.method == 'GET' ? publicReaderOfRequest(route, req) : appOfRequest(route, req)
  441. if (who.error != null) { return who.error }
  442. // GET (v1.3): every context on that sha, from every app; a sha this repo does not have is 404 not_found (§6 shape)
  443. if (req.method == 'GET') {
  444. l = listStatuses(who.repo, route.params.sha)
  445. if (l.unknown == true) { return apiError(404, 'not_found', 'that sha is not a commit of this repository', null) }
  446. return reply(200, { statuses = l.statuses })
  447. }
  448. j = jsonOfRequest(req)
  449. if (j.error != null) { return j.error }
  450. r = putStatus(who.repo, who.app, route.params.sha, j.json)
  451. if (r.invalid != null) { return apiError(422, 'invalid', 'the status is not valid', r.invalid) }
  452. if (r.unknown == true) { return apiError(422, 'invalid', 'that sha is not a commit of this repository', [{ field = 'sha' reason = 'no_such_commit' }]) }
  453. return reply(200, { status = r.status })
  454. }
  455. static apiPullState = (Hybrid route, Hybrid req, Boolean closed) => {
  456. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  457. who = userTokenRequest(req, closed ? 'apps cannot close pull requests' : 'apps cannot reopen pull requests')
  458. if (who.error != null) { return who.error }
  459. repo = route.params.slug != null ? repoBySlug(route.params.org == null ? decodeURIComponent(route.params.slug) : route.params.org + '/' + route.params.slug) : repoOfRequest(route, req)
  460. if (repo == null || !mayRead(who.uid, repo)) { return apiError(404, 'not_found', 'no such repository', null) }
  461. r = closed ? closePull(who.uid, repo.slug, numberOf(route.params.n)) : reopenPull(who.uid, repo.slug, numberOf(route.params.n))
  462. if (r.error != null) { return apiError(r.code, r.code == 404 ? 'not_found' : (r.code == 403 ? 'forbidden' : 'conflict'), r.error, r.reason == null ? null : { reason = r.reason }) }
  463. return reply(200, { pull = pullObject(repo.slug, numberOf(route.params.n)) })
  464. }
  465. static apiClosePull = (Hybrid route, Hybrid req) => { return apiPullState(route, req, true) }
  466. static apiReopenPull = (Hybrid route, Hybrid req) => { return apiPullState(route, req, false) }

Branches

Latest commits

  • 52576cb0force push: defer on a failed scan, one-to-one pairs, docs (#56)mre
  • 5a7b3e68|||PR a force push keeps the same pull request (#56)mre
  • cc1be2d6Merge branch 'w62-pr-close' into mainGitoria
  • 6e03be0apull state: keep the resync marker until the sync ran (#56)mre
  • 93bdd26cpull state: wait for a claimed row, resync when it stays busy (#56)mre
  • e53d284bpull state: stop on a failed branch scan, claim the row on writes (#56)mre
  • d8608224close and reopen: keep a manual close against sync (#56)mre
  • ffb60746|||PR close and reopen pull requests (#56)mre
  • fe209ffeMerge branch 'w56-owner-members' into mainGitoria
  • fa0754c8|||PR repository owner transfer and members API (#55)mre
  • 8862e537Merge branch 'w55-rename-org' into mainGitoria
  • 014d2b7fOne immutable readers snapshot per move for the left-organization event (#53)mre
  • 1859d506Decide who hears a repo left its organization by its readers before the move (#53)mre
  • 499f25f2Review fixes for the Settings organization move (#53)mre
  • ed3b922b|||PR move a repository into an organization in Settings (#53)mre
  • 74ec2af8Merge branch 'w54-repo-rename-pr' into mainGitoria
  • 9f7ce8d8Preserve rename compatibility and live page titlesmre
  • c3d95b6e|||PR separate names and addresses, rename repositories in Settings (#53)mre
  • ce08920dMerge branch 'w52c-header-phone' into mainGitoria
  • 0bab9e46|||PR header: ident status wraps on phones instead of clippingmre