gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitdb443456db443456log: vinzenz note retry 2mredb443456/lib/api.hl

26.0 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 { userOfToken } from './tokens.hl'
  15. import { Response } from 'hl:http1'
  16. import { randomBytes } from 'hl:crypto'
  17. import { NL, px, slugOfHost } from './util.hl'
  18. import { userOfLoginCode } from './users.hl'
  19. import { createRepoFromInput, repoRows, repoRow, repoBySlug, repoFor, orgFor, ownsRepo, mayPush, mayRead } from './repos.hl'
  20. import { fullNameError, repoDocument, listDocument } from './repos-helpers.hl'
  21. import { forwardOf } from './forwards.hl'
  22. import { userIdOfSession, userRecord } from './users.hl'
  23. import { connectHref, finishConnect } from './tickets.hl'
  24. import { keyLine } from './sshkeys.hl'
  25. import { urlAllowed, withQuery, formFields } from './apps-helpers.hl'
  26. import { nameError, makeCode, exchangeCode, appOfKey } from './apps.hl'
  27. import { issueToken } from './app-tokens.hl'
  28. import { bearerOf, unauthorized, notFound, tooMany, appOfRequest, readerOfRequest, appTokenRequired } from './app-auth.hl'
  29. import { answerOf, jsonOfRequest, reply, fail, apiError, wantsMarkdown, markdownReply, textReply, goTo, sshGuard, repoOfRequest, safeNext } from './api-helpers.hl'
  30. import { ensurePulls, recordByNumber, pullObject } from './pullsync.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. token = bearerOf(req)
  51. if (token != null && token.startsWith('gat_')) { return apiError(403, 'forbidden', 'app tokens cannot create repositories', null) }
  52. uid = userOfToken(token)
  53. if (uid == null) { return apiError(401, 'unauthorized', 'a user access token is required', null) }
  54. j = jsonOfRequest(req)
  55. if (j.error != null) { return j.error }
  56. r = createRepoFromInput(uid, j.json)
  57. if (r.error != null) {
  58. status = r.status == null ? 422 : r.status
  59. code = status == 403 ? 'forbidden' : (status == 409 ? 'conflict' : (status == 500 ? 'internal' : 'invalid'))
  60. return apiError(status, code, r.error, { field = r.field })
  61. }
  62. return reply(201, r.repo)
  63. }
  64. static apiRepo = (route, req) => {
  65. if (req.method != 'GET') { return fail(405, 'GET only') }
  66. row = repoRow(route.params.slug, userIdOfSession(req.session))
  67. if (row == null) { return fail(404, 'no such repository') }
  68. if (wantsMarkdown(req)) { return markdownReply(repoDocument(row)) }
  69. return reply(200, row)
  70. }
  71. // ---- NOTHING ELSE (mission MG, as ident's notFoundPage): the last route of project.hl answers a path no route knows with the
  72. // shell's 404 page (components/notfound.hl) — status 404, the page rendered by the framework with the request's session and host
  73. static notFoundPage = (route, req, &srv, pageComponent) => {
  74. m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { path = req.path } path = req.path }
  75. res = srv.page(m, req.session, srv.hostOf(req.headers['host']), srv.requestHeaders(req.headers))
  76. res.status = 404
  77. return res
  78. }
  79. // `/: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:
  80. // a stray single-segment path on any other address keeps its real 404 status — /.env, /host.js, a private organization's /x)
  81. static orgRepoPage = (route, req, &srv, pageComponent, missingComponent) => {
  82. h = req.headers['host']
  83. label = slugOfHost(h == null ? '' : h.split(':')[0])
  84. if (label == '' || orgFor(label, userIdOfSession(req.session)) == null) { return notFoundPage(route, req, &srv, missingComponent) }
  85. m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { orepo = req.path.slice(1) } path = req.path }
  86. return srv.page(m, req.session, srv.hostOf(h), srv.requestHeaders(req.headers))
  87. }
  88. // `/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
  89. // shell's 404 page (a function route, so the status is a real 404 for an unknown number)
  90. static pullPage = (route, req, &srv, pageComponent, missingComponent) => {
  91. h = req.headers['host']
  92. host = h == null ? '' : h.split(':')[0]
  93. orepo = route.params.orepo != null ? route.params.orepo : ''
  94. nText = route.params.n
  95. if (prOfRequest(host, orepo, req.session, nText) == null) { return notFoundPage(route, req, &srv, missingComponent) }
  96. m = { route = { pattern = route.route.pattern component = pageComponent } kind = 'component' params = { orepo = orepo n = nText } path = req.path }
  97. return srv.page(m, req.session, srv.hostOf(h), srv.requestHeaders(req.headers))
  98. }
  99. // any other /api path: the contract's JSON 404 (docs/apps-api.md §6)
  100. static notFoundApi = (route, req) => { return apiError(404, 'not_found', 'no such endpoint', null) }
  101. // ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident") ----------------------------
  102. // ident sends the browser back with ?ident_code= (and our ?next=); the code is exchanged here (users.hl userOfLoginCode),
  103. // the user goes into THIS browser's session (`req.session`, the cookie's — hybriel #11; minted when it brought none),
  104. // then → `?next=` (api-helpers.hl safeNext). A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked
  105. // in the session, then → /login/failed.
  106. static loginFailed = (&req, &sessions, why) => {
  107. let s = req.session
  108. fresh = s == null
  109. if (fresh) { s = sessions.mint() }
  110. s.data.loginError = why
  111. sessions.save(s)
  112. 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' } })
  113. if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }
  114. return res
  115. }
  116. static loginCallback = (route, &req, &sessions) => {
  117. if (req.method != 'GET') { return loginFailed(&req, &sessions, 'GET only') }
  118. q = req.query != null ? req.query : {}
  119. code = q.ident_code
  120. if (code == null || code == '') { return loginFailed(&req, &sessions, 'ident sent no login code') }
  121. x = userOfLoginCode(code)
  122. if (x.error != null) { return loginFailed(&req, &sessions, x.error) }
  123. // THE SAME SESSION, NEVER SIGNED OUT (ident#28): a good code signs the session the browser already has in (a second tab or an installed
  124. // app may not store a new cookie, and a session we signed out would leave it anonymous); none yet → minted here
  125. let s = req.session
  126. if (s == null) { s = sessions.mint() }
  127. s.user = { id = x.user.id }
  128. s.data.tag = randomBytes(16)
  129. s.data.loginError = null
  130. sessions.save(s)
  131. 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) } })
  132. return res
  133. }
  134. // ---- ONE LOGIN FOR THE MAIN ADDRESS AND EVERY REPO ADDRESS ---------------------------------------------------------------------
  135. // Nothing here: hl:web (batch 20) does it. The session cookie carries `Domain=.<host>` (project.hl sessionDomain); among several gitoriasid
  136. // 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
  137. // 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".
  138. // ---- CONNECT A REPO TO A TICKETS PROJECT (gitoria#18; tickets.hl, components/settings.hl) ----------------------------
  139. // /settings/connect: the owner's click → a fresh nonce parked in the session (bound to the repo) → tickets' /connect.
  140. // /settings/connected: tickets' return with ?code&state → tickets.hl finishConnect (nonce, exchange, key stored per
  141. // repo) → back to /settings. A failure is a note on the settings page.
  142. static connectStart = (route, &req, &sessions) => {
  143. if (req.method != 'GET') { return fail(405, 'GET only') }
  144. repo = repoOfRequest(route, req)
  145. if (repo == null) { return fail(404, 'no such repository') }
  146. s = req.session
  147. if (s == null || !ownsRepo(repo.slug, s)) { return goTo(px(repo.slug) + '/settings') }
  148. nonce = randomBytes(16)
  149. s.data.connectState = repo.slug + '.' + nonce
  150. s.data.connectNote = null
  151. sessions.save(s)
  152. return goTo(connectHref(repo.slug, nonce))
  153. }
  154. // One log line for every end of the connect flow (docker logs of the gitoria container): "connect-back <slug> <outcome> ..." and
  155. // never the code, the state value or a key. `state` only says whether tickets brought one.
  156. static connectLog = (slug, outcome, hasState) => {
  157. console.log('connect-back ' + slug + ' ' + outcome + ' state=' + (hasState ? 'present' : 'absent'))
  158. }
  159. static notSignedInNote = 'The connection to tickets did not finish: this browser is not signed in to gitoria as the repo owner. Sign in and press Connect again.'
  160. static connectBack = (route, &req, &sessions) => {
  161. if (req.method != 'GET') { return fail(405, 'GET only') }
  162. repo = repoOfRequest(route, req)
  163. if (repo == null) { return fail(404, 'no such repository') }
  164. q = req.query != null ? req.query : {}
  165. hasState = q.state != null
  166. let s = req.session
  167. if (s == null || userIdOfSession(s) == null || !ownsRepo(repo.slug, s)) {
  168. // nothing is exchanged; the code is dropped. The browser is told why on the settings page: a session-less browser gets a fresh
  169. // session that carries the note (like loginFailed), a session that exists keeps itself and gets the note
  170. why = s == null ? 'no-session' : (userIdOfSession(s) == null ? 'session-not-signed-in' : 'not-owner')
  171. connectLog(repo.slug, 'refused reason=' + why, hasState)
  172. fresh = s == null
  173. if (fresh) { s = sessions.mint() }
  174. s.data.connectNote = notSignedInNote
  175. sessions.save(s)
  176. res = goTo(px(repo.slug) + '/settings')
  177. if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }
  178. return res
  179. }
  180. want = s.data.connectState
  181. s.data.connectState = null
  182. note = finishConnect(repo.slug, want, q)
  183. s.data.connectNote = note == '' ? null : note
  184. sessions.save(s)
  185. if (note == '') {
  186. connectLog(repo.slug, 'connected', hasState)
  187. } else if (q.error != null && q.code == null) {
  188. connectLog(repo.slug, 'tickets-error', hasState)
  189. } else if (want == null || want != repo.slug + '.' + q.state) {
  190. connectLog(repo.slug, 'state-mismatch', hasState)
  191. } else {
  192. connectLog(repo.slug, 'exchange-failed', hasState)
  193. }
  194. return goTo(px(repo.slug) + '/settings')
  195. }
  196. // ---- WHAT THE SSHD CONTAINER ASKS (ticket gitoria#7; docker/sshd) — only with the shared secret (api-helpers.hl sshGuard)
  197. // GET /__git/keys?type=<ssh-ed25519>&key=<base64> sshd AuthorizedKeysCommand: the authorized_keys line for a known key
  198. // (sshkeys.hl keyLine), empty for an unknown one
  199. // GET /__git/access?user=<id>&slug=<slug>&write=0|1 gitoria-shell before it starts git: `ok` or 403. Read = every repo (public);
  200. // write = the repo's owner only (repos.hl mayPush — the same rule as the token on HTTPS, transport.hl)
  201. static gitKeys = (route, req) => {
  202. no = sshGuard(req)
  203. if (no != null) { return no }
  204. q = req.query != null ? req.query : {}
  205. return textReply(200, keyLine(q.type, q.key))
  206. }
  207. // GET /__git/pushed?user=<id>&slug=<slug>&phase=before|after gitoria-shell around a push over ssh (what transport.hl does for HTTPS):
  208. // 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.
  209. static gitPushed = (route, req) => {
  210. no = sshGuard(req)
  211. if (no != null) { return no }
  212. q = req.query != null ? req.query : {}
  213. slug = q.slug
  214. if (slug == null || hlTypeName(slug) != 'String' || fullNameError(slug) != null) { return textReply(404, 'no such repository' + NL) }
  215. let repo = repoBySlug(slug)
  216. if (repo == null && forwardOf(slug) != null) { repo = repoBySlug(forwardOf(slug)) }
  217. if (repo == null || !mayPush(q.user, repo)) { return textReply(403, 'not allowed' + NL) }
  218. if (q.phase == 'before') { ensurePulls(repo.slug) }
  219. else if (q.phase == 'after') {
  220. notifyPush(repo.slug, false)
  221. syncAndRaise(repo.slug, q.user)
  222. } else { return textReply(400, 'phase is before or after' + NL) }
  223. return textReply(200, 'ok' + NL)
  224. }
  225. static gitAccess = (route, req) => {
  226. no = sshGuard(req)
  227. if (no != null) { return no }
  228. q = req.query != null ? req.query : {}
  229. slug = q.slug
  230. if (slug == null || hlTypeName(slug) != 'String' || fullNameError(slug) != null) { return textReply(404, 'no such repository' + NL) }
  231. let repo = repoBySlug(slug)
  232. if (repo == null && forwardOf(slug) != null) { repo = repoBySlug(forwardOf(slug)) }
  233. // the asker is the key's user: a repo they may not see does not exist for them (404, as over HTTPS)
  234. if (repo == null || !mayRead(q.user, repo)) { return textReply(404, 'no such repository' + NL) }
  235. 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) }
  236. // the sshd container runs git in the repo's real folder: tell it the name (it differs after a move)
  237. return textReply(200, 'ok ' + repo.slug + NL)
  238. }
  239. // ---- CONNECT AN APP TO A REPO (gitoria#41; apps.hl, docs/apps-api.md §1 flow A) ----------------------------------------------------
  240. // /settings/apps/connect?app&hook&return&state: the app sends the owner's browser here. The four values are checked (the URL allow-list:
  241. // 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
  242. // (the same session goes on after the login) and, for the owner, shows "Connect <app> to <repo>?" with a Yes / No form.
  243. // /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).
  244. static appConnectStart = (route, &req, &sessions) => {
  245. if (req.method != 'GET') { return apiError(405, 'invalid', 'GET only', null) }
  246. repo = repoOfRequest(route, req)
  247. if (repo == null) { return apiError(404, 'not_found', 'no such repository', null) }
  248. q = req.query != null ? req.query : {}
  249. if (!urlAllowed(q.hook)) { return apiError(400, 'invalid_url', 'hook is not an allowed receiver address', { field = 'hook' }) }
  250. if (!urlAllowed(q['return'])) { return apiError(400, 'invalid_url', 'return is not an allowed address', { field = 'return' }) }
  251. bad = nameError(q.app)
  252. if (bad != null) { return apiError(422, 'invalid', bad, { field = 'app' }) }
  253. 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' }) }
  254. let s = req.session
  255. fresh = s == null
  256. if (fresh) { s = sessions.mint() }
  257. s.data.appConnect = { slug = repo.slug app = ('' + q.app).trim() hook = q.hook ret = q['return'] state = q.state nonce = randomBytes(16) }
  258. sessions.save(s)
  259. res = goTo(px(repo.slug) + '/settings')
  260. if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }
  261. return res
  262. }
  263. static appConnectConfirm = (route, &req, &sessions) => {
  264. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  265. repo = repoOfRequest(route, req)
  266. if (repo == null) { return apiError(404, 'not_found', 'no such repository', null) }
  267. home = px(repo.slug) + '/settings'
  268. let s = req.session
  269. if (s == null || userIdOfSession(s) == null || !ownsRepo(repo.slug, s)) { return goTo(home) }
  270. p = s.data.appConnect
  271. f = formFields(req.body)
  272. if (p == null || p.slug != repo.slug || f.nonce == null || f.nonce != p.nonce) { return goTo(home) }
  273. // one try: the parked request goes whatever the answer is
  274. s.data.appConnect = null
  275. sessions.save(s)
  276. if (f.decision != 'yes') { return goTo(withQuery(p.ret, { error = 'denied' state = p.state })) }
  277. code = makeCode(repo, p.app, p.hook, userIdOfSession(s))
  278. if (code == null) { return goTo(home) }
  279. return goTo(withQuery(p.ret, { code = code state = p.state }))
  280. }
  281. // POST /api/apps/exchange {"code"} (no auth): the app's server trades the code → { key, secret, api, repo, app } (apps.hl exchangeCode)
  282. static appExchange = (route, req) => {
  283. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  284. repo = repoOfRequest(route, req)
  285. if (repo == null) { return apiError(404, 'not_found', 'no such repository', null) }
  286. j = jsonOfRequest(req)
  287. if (j.error != null) { return j.error }
  288. x = exchangeCode(repo, j.json.code)
  289. if (x.notFound == true) { return apiError(404, 'not_found', 'unknown, used or expired code', null) }
  290. return reply(200, x.body)
  291. }
  292. // 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
  293. static appToken = (route, req) => {
  294. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  295. no = appTokenRequired(req)
  296. if (no != null) { return no }
  297. app = appOfKey(bearerOf(req))
  298. if (app == null) { return unauthorized() }
  299. repo = repoOfRequest(route, req)
  300. if (repo == null || repo.id != app.repo) { return notFound() }
  301. wait = limitCheck(app.id, req.method)
  302. if (wait > 0) { return tooMany(wait) }
  303. t = issueToken(app)
  304. if (t.error != null) { return apiError(500, 'internal', 'could not make a token', null) }
  305. return reply(200, { token = t.token expires = t.expires })
  306. }
  307. // GET {api}/deliveries?cursor=&limit= → { deliveries: [{ id, event, action, time, status, tries, lastCode }], next } — the app's OWN deliveries (events.hl)
  308. static appDeliveries = (route, req) => {
  309. if (req.method != 'GET') { return apiError(405, 'invalid', 'GET only', null) }
  310. who = appOfRequest(route, req)
  311. if (who.error != null) { return who.error }
  312. q = req.query != null ? req.query : {}
  313. return reply(200, deliveryPage(who.app.id, q.cursor, q.limit == null ? null : toNumber(q.limit)))
  314. }
  315. // 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
  316. static appRedeliver = (route, req) => {
  317. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  318. who = appOfRequest(route, req)
  319. if (who.error != null) { return who.error }
  320. if (!redeliver(who.app.id, route.params.id)) { return apiError(404, 'not_found', 'no such delivery', null) }
  321. return reply(202, { accepted = true })
  322. }
  323. // ---- the apps API's PR routes (gitoria#44; lib/reviews.hl does the work, these only check the method and the app, and answer)
  324. // GET {api}/pulls?state=&cursor=&limit=
  325. static appPulls = (route, req) => {
  326. if (req.method != 'GET') { return apiError(405, 'invalid', 'GET only', null) }
  327. who = readerOfRequest(route, req)
  328. if (who.error != null) { return who.error }
  329. return answerOf(listPulls(who.repo, req.query))
  330. }
  331. // 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
  332. // are green (lib/pullmerge.hl, the same as the Merge button). Apps (gat_) never merge. → 200 { merged, mergeCommit, pull }
  333. static apiMergePull = (route, req) => {
  334. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  335. token = bearerOf(req)
  336. if (token != null && token.startsWith('gat_')) { return apiError(403, 'forbidden', 'apps cannot merge', null) }
  337. uid = userOfToken(token)
  338. if (uid == null) { return apiError(401, 'unauthorized', 'a user access token is required', null) }
  339. repo = repoOfRequest(route, req)
  340. if (repo == null || !mayRead(uid, repo)) { return apiError(404, 'not_found', 'no such repository', null) }
  341. if (!mayPush(uid, repo)) { return apiError(403, 'forbidden', 'only the owner and the members of this repository can merge', null) }
  342. let head = ''
  343. if (req.body != null && req.body.trim() != '') {
  344. j = jsonOfRequest(req)
  345. if (j.error != null) { return j.error }
  346. h = j.json.head
  347. if (h != null) {
  348. 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' }]) }
  349. head = h
  350. }
  351. }
  352. ensurePulls(repo.slug)
  353. n = numberOf(route.params.n)
  354. rec = n == null ? null : recordByNumber(repo.id, n)
  355. if (rec == null) { return apiError(404, 'not_found', 'no such pull request', null) }
  356. r = mergeAndAnnounce(repo, rec.sha, userRecord(uid), head)
  357. if (r.error != null) { return apiError(r.error == 'no such pull request' ? 404 : 409, r.error == 'no such pull request' ? 'not_found' : 'conflict', r.error, null) }
  358. return reply(200, { merged = true mergeCommit = r.mergeCommit pull = pullObject(repo.slug, rec.number) })
  359. }
  360. // GET {api}/pulls/N
  361. static appPull = (route, req) => {
  362. if (req.method != 'GET') { return apiError(405, 'invalid', 'GET only', null) }
  363. who = readerOfRequest(route, req)
  364. if (who.error != null) { return who.error }
  365. return answerOf(getPull(who.repo, route.params.n))
  366. }
  367. // GET / POST {api}/pulls/N/reviews
  368. static appReviews = (route, req) => {
  369. if (req.method != 'GET' && req.method != 'POST') { return apiError(405, 'invalid', 'GET or POST only', null) }
  370. who = req.method == 'GET' ? readerOfRequest(route, req) : appOfRequest(route, req)
  371. if (who.error != null) { return who.error }
  372. if (req.method == 'GET') { return answerOf(listReviews(who.app, who.repo, route.params.n, req.query)) }
  373. j = jsonOfRequest(req)
  374. if (j.error != null) { return j.error }
  375. return answerOf(postReview(who.app, who.repo, route.params.n, j.json))
  376. }
  377. // GET {api}/pulls/N/threads
  378. static appThreads = (route, req) => {
  379. if (req.method != 'GET') { return apiError(405, 'invalid', 'GET only', null) }
  380. who = readerOfRequest(route, req)
  381. if (who.error != null) { return who.error }
  382. return answerOf(listThreads(who.app, who.repo, route.params.n, req.query))
  383. }
  384. // POST {api}/pulls/N/threads/:id/replies
  385. static appReply = (route, req) => {
  386. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  387. who = appOfRequest(route, req)
  388. if (who.error != null) { return who.error }
  389. j = jsonOfRequest(req)
  390. if (j.error != null) { return j.error }
  391. return answerOf(postReply(who.app, who.repo, route.params.n, route.params.id, j.json))
  392. }
  393. // POST {api}/pulls/N/threads/:id/resolve
  394. static appResolve = (route, req) => {
  395. if (req.method != 'POST') { return apiError(405, 'invalid', 'POST only', null) }
  396. who = appOfRequest(route, req)
  397. if (who.error != null) { return who.error }
  398. j = jsonOfRequest(req)
  399. if (j.error != null) { return j.error }
  400. return answerOf(resolveThread(who.app, who.repo, route.params.n, route.params.id, j.json))
  401. }
  402. // GET / POST {api}/pulls/N/comments (the PR's conversation)
  403. static appComments = (route, req) => {
  404. if (req.method != 'GET' && req.method != 'POST') { return apiError(405, 'invalid', 'GET or POST only', null) }
  405. who = req.method == 'GET' ? readerOfRequest(route, req) : appOfRequest(route, req)
  406. if (who.error != null) { return who.error }
  407. if (req.method == 'GET') { return answerOf(listComments(who.repo, route.params.n, req.query)) }
  408. j = jsonOfRequest(req)
  409. if (j.error != null) { return j.error }
  410. return answerOf(postComment(who.app, who.repo, route.params.n, j.json))
  411. }
  412. // 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
  413. static appStatus = (route, req) => {
  414. if (req.method != 'PUT' && req.method != 'GET') { return apiError(405, 'invalid', 'GET or PUT only', null) }
  415. who = req.method == 'GET' ? readerOfRequest(route, req) : appOfRequest(route, req)
  416. if (who.error != null) { return who.error }
  417. // GET (v1.3): every context on that sha, from every app; a sha this repo does not have is 404 not_found (§6 shape)
  418. if (req.method == 'GET') {
  419. l = listStatuses(who.repo, route.params.sha)
  420. if (l.unknown == true) { return apiError(404, 'not_found', 'that sha is not a commit of this repository', null) }
  421. return reply(200, { statuses = l.statuses })
  422. }
  423. j = jsonOfRequest(req)
  424. if (j.error != null) { return j.error }
  425. r = putStatus(who.repo, who.app, route.params.sha, j.json)
  426. if (r.invalid != null) { return apiError(422, 'invalid', 'the status is not valid', r.invalid) }
  427. if (r.unknown == true) { return apiError(422, 'invalid', 'that sha is not a commit of this repository', [{ field = 'sha' reason = 'no_such_commit' }]) }
  428. return reply(200, { status = r.status })
  429. }

Branches

Latest commits

  • db443456log: vinzenz note retry 2mre
  • 802f229alog: kunibert repo ping provenmre
  • 2d2eaa92log: Kunibert connected to kunibert repomre
  • 65d5f80alogmre
  • dab74b0dW49 report, logmre
  • fd4fc028Exercise member status reads with a populated check statemre
  • 536ca6f9Allow repository members to read pull workflow APIs with user tokensmre
  • 705dd834W49 missionmre
  • b554cd5flogmre
  • f4c9440ddeploy.sh: tar --hard-dereference for the live data backupmre
  • 1a687b15Merge branch 'w48-member-merge'mre
  • 166c775fW48 report, logmre
  • 1b4623f0Members merge pull requests: API route, button on /pulls and /pulls/N, one shared merge pathmre
  • 1075c38cW48 mission, logmre
  • 17bdd0d6V37/V39 missions, logmre
  • 146de5f8Re-vendor gitoria to Hybriel set-day39 (51e921d7)mre
  • e874e44dtests/status-keyed: app token lives 60 s so it outlives the gate's two restartsmre
  • 270b8d61deploy.sh: DEPLOY_STOP_START=1 stops, waits for the old pid, then starts (mpackdb freeze, replaces the standby swap)mre
  • 3f9235b8project.hl: drop the dummy /pulls/:n component route (hybriel#294 is fixed in day37)mre
  • c90daf19Re-vendor gitoria to Hybriel set-day37 (f6b3d45b)mre