gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitfa0754c8fa0754c8|||PR repository owner transfer and members API (#55)mrefa0754c8/lib/api.hl

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

Branches

Latest commits

  • 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
  • e7af3eceMerge branch 'w52b-approval-followup' into mainGitoria
  • c01e66c6|||PR approvals follow-up: live Merge after status writes, helpers (#52)mre
  • 841da497Merge branch 'w53-pulls-speed-pr' into mainGitoria
  • 80307ae2|||PR pulls page cache: live PR numbers, complete scans onlymre
  • 69141f65|||PR pulls page: cache the git part per repo by branch tipsmre
  • 155861f6Merge branch 'w52-person-approval' into mainGitoria
  • b5435de8|||PR person approvals: second Kunibert round (#52)mre
  • 3a8b2fb8|||PR person approvals: Kunibert review fixes (#52)mre
  • 2a89d8d0|||PR person approvals: Approve button for people; merge needs the required checks or a listed person's approval (#52)mre