gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitfd83ac1ffd83ac1fconductor: caramboleyo is the user, not owner/creatorApollofd83ac1f/lib/api.hl

28.6 KB

  1. // lib/api.hl — THE FUNCTION ROUTES (project.hl `routes`): the JSON API for the scheduler, a CLI and connected apps,
  2. // and the three page routes that are not components (/login/callback, /connect, /tickets/:ref). Thin wrappers:
  3. // check the method, the token / key and the body (lib/api-helpers.hl), call the topic function, push what
  4. // changed (the same frames the web faces push, so an open browser follows an API write live), answer.
  5. // See README.md "API" for the shapes.
  6. //
  7. // Every POST body goes through readBody: invalid JSON, unknown field, missing/empty required field, non-string
  8. // value → 400. WRITES NEED A TOKEN (ticket #7): no / bad / revoked token → 401, checked BEFORE the body. The
  9. // author is the token's user; a body with `author` → 400 naming it. Reads stay public.
  10. // THE MARKDOWN READ VIEW (ticket #6): `Accept: text/markdown` on the ticket GETs (the two lists,
  11. // the two single-ticket forms) answers a compact Markdown document (mdview.hl); JSON otherwise, unchanged.
  12. // TWO WAYS TO NAME A TICKET (ticket #38): `/api/tickets/:ref` — :ref is the OLD global
  13. // number of a migrated ticket (docs say "#38") or the ticket's UUID (`id`) — and the
  14. // per-project form `/api/projects/:slug/tickets/:number`. Both answer the same shapes.
  15. import { Response } from 'hl:http1'
  16. import { randomBytes } from 'hl:crypto'
  17. import { connectCodeOf, loginCodeOf } from './problems.hl'
  18. import { reply, hdr, fail, queryOf, readBody, refuse, unauthorized, unauthorizedFor, authDenied, denied, apiUser, apiAuth, actorIn, stateFilter, filterLabel, wantsMarkdown, markdownReply, problemRedirect, moved, missing, commentFormOf, fileReply } from './api-helpers.hl'
  19. import { isMultipart } from './multipart.hl'
  20. import { attachmentFor } from './attachments.hl'
  21. import { exchangeCode, ensureUser, userOfSession } from './users.hl'
  22. import { projectNames, projectByAnySlug, projectByRef, slugOfRef, projectRecords, projectRowOf, projectSlugOf, createProject, updateProject, memberRows, setMemberRole, userByRef, roles } from './projects.hl'
  23. import { states } from './tickets-helpers.hl'
  24. import { pageEventOf } from './events.hl'
  25. import { ticketRows, ticketWithEvents, ticketByRef, ticketAt, createTicket, addComment, changeComment, changeState, assignTicket, editTicket, setParent, changeBlocker, relatedViews, removeMember, inboxRows } from './tickets.hl'
  26. import { mayInvite, createInvite, joinByInvite } from './invites.hl'
  27. import { createRequest, exchangeConnectCode, connectionRows, disconnect } from './connections.hl'
  28. import { listDocument, ticketDocument } from './mdview.hl'
  29. import { subscriptionOf, openStream } from './stream.hl'
  30. import { ticketHref, projectHrefOf } from './util.hl'
  31. // ---- tickets ------------------------------------------------------------------------------------
  32. static byRef = (route) => { return ticketByRef(route.params.ref) }
  33. // the project of an /api/projects/:slug/… route: its slug (also an old one) or its id (ticket #25) → the slug
  34. static slugOf = (route) => { return slugOfRef(route.params.slug) }
  35. static byNumber = (route) => { return ticketAt(slugOf(route), route.params.number) }
  36. static listTickets = (route, req) => {
  37. if (req.method != 'GET') { return fail(405, 'GET only') }
  38. // hl:http1 hands the parsed query string as `req.query`; the path carries none
  39. q = req.query != null ? req.query : queryOf(req.path)
  40. sf = stateFilter(q)
  41. if (sf.bad != null) { return sf.bad }
  42. pr = q.project != null && q.project != '' ? q.project : null
  43. rows = ticketRows(pr, sf.state)
  44. if (wantsMarkdown(req)) { return markdownReply(listDocument(rows, filterLabel(pr, sf.state))) }
  45. return reply(200, { tickets = rows })
  46. }
  47. // POST /api/tickets { project, … } and POST /api/projects/:slug/tickets { … }
  48. static createFromApi = (project, b, auth, req) => {
  49. pr = projectByRef(project)
  50. w = actorIn(auth, req, pr != null ? pr.id : null)
  51. if (w.response != null) { return w.response }
  52. user = w.user
  53. r = createTicket(project, b.subject, b.summary, user, b.source, b.assignee)
  54. if (r.forbidden == true) { return reply(403, { error = r.error field = r.field }) }
  55. if (r.error != null) { return refuse({ error = r.error field = r.field }) }
  56. if (!r.existed) { emit client ticketCreated(r.ticket) }
  57. return reply(r.existed ? 200 : 201, { ticket = r.ticket existed = r.existed })
  58. }
  59. static postTicket = (route, req) => {
  60. if (req.method == 'GET') { return listTickets(route, req) }
  61. if (req.method != 'POST') { return fail(405, 'GET or POST') }
  62. u = apiAuth(req)
  63. if (u == null || u.response != null) { return authDenied(u, 'an API write') }
  64. rb = readBody(req, ['project' 'subject'], ['summary' 'source' 'assignee'])
  65. if (rb.bad != null) { return refuse(rb.bad) }
  66. return createFromApi(rb.body.project, rb.body, u, req)
  67. }
  68. static projectTickets = (route, req) => {
  69. slug = slugOf(route)
  70. if (req.method == 'GET') {
  71. if (projectByAnySlug(slug) == null) { return fail(404, 'no such project') }
  72. q = req.query != null ? req.query : queryOf(req.path)
  73. sf = stateFilter(q)
  74. if (sf.bad != null) { return sf.bad }
  75. rows = ticketRows(slug, sf.state)
  76. if (wantsMarkdown(req)) { return markdownReply(listDocument(rows, filterLabel(slug, sf.state))) }
  77. return reply(200, { tickets = rows })
  78. }
  79. if (req.method != 'POST') { return fail(405, 'GET or POST') }
  80. u = apiAuth(req)
  81. if (u == null || u.response != null) { return authDenied(u, 'an API write') }
  82. rb = readBody(req, ['subject'], ['summary' 'source' 'assignee'])
  83. if (rb.bad != null) { return refuse(rb.bad) }
  84. return createFromApi(slug, rb.body, u, req)
  85. }
  86. static getOne = (t, req) => {
  87. if (req.method != 'GET') { return fail(405, 'GET only') }
  88. if (t == null) { return fail(404, 'no such ticket') }
  89. data = ticketWithEvents(t)
  90. if (wantsMarkdown(req)) { return markdownReply(ticketDocument(data)) }
  91. return reply(200, data)
  92. }
  93. // tickets#27 (mission 017): a comment WITH FILES is a multipart/form-data body (`text` + file parts, lib/api-helpers.hl
  94. // commentFormOf); JSON { text } stays as it was. Over a size limit → 413, a file that is not what it claims → 400.
  95. static commentOnTicket = (t, req) => {
  96. if (req.method != 'POST') { return fail(405, 'POST only') }
  97. auth = apiAuth(req)
  98. if (auth == null || auth.response != null) { return authDenied(auth, 'an API write') }
  99. let text = ''
  100. let files = null
  101. if (isMultipart(req)) {
  102. mp = commentFormOf(req)
  103. if (mp.bad != null) { return mp.bad }
  104. text = mp.text
  105. files = mp.files
  106. } else {
  107. rb = readBody(req, ['text'], [])
  108. if (rb.bad != null) { return refuse(rb.bad) }
  109. text = rb.body.text
  110. }
  111. if (t == null) { return fail(404, 'no such ticket') }
  112. w = actorIn(auth, req, t.project)
  113. if (w.response != null) { return w.response }
  114. u = w.user
  115. r = addComment(t.id, u, text, files)
  116. if (r.error == 'no such ticket') { return fail(404, r.error) }
  117. if (r.forbidden == true) { return reply(403, { error = r.error field = r.field }) }
  118. if (r.tooBig == true) { return reply(413, { error = r.error field = r.field }) }
  119. if (r.error != null) { return refuse({ error = r.error field = r.field }) }
  120. emit client ticketEvent(r.ticket.id, pageEventOf(r.event), r.ticket)
  121. return reply(201, r)
  122. }
  123. // mission 016: a comment's author EDITS it (POST …/comments/:comment/edit { text }) or DELETES it (…/delete, body empty or
  124. // {}); any member LIKES it (…/like, again = take it back). `:comment` = the comment's event `id`. 200 { ticket, event (the
  125. // comment as it is now), liked (like only) }; 401 no token, 403 not the author / not a member, 404 no such ticket / comment,
  126. // 400 empty or unchanged text, a deleted comment, a bad body. An open ticket page follows (push commentChanged).
  127. static changeOfComment = (t, route, req, action) => {
  128. if (req.method != 'POST') { return fail(405, 'POST only') }
  129. auth = apiAuth(req)
  130. if (auth == null || auth.response != null) { return authDenied(auth, 'an API write') }
  131. let b = {}
  132. if (action == 'edit' || (req.body != null && req.body != '')) {
  133. rb = readBody(req, action == 'edit' ? ['text'] : [], [])
  134. if (rb.bad != null) { return refuse(rb.bad) }
  135. b = rb.body
  136. }
  137. if (t == null) { return fail(404, 'no such ticket') }
  138. w = actorIn(auth, req, t.project)
  139. if (w.response != null) { return w.response }
  140. r = changeComment(t.id, route.params.comment, w.user, action, b.text)
  141. if (r.error == 'no such ticket' || r.error == 'no such comment on this ticket') { return fail(404, r.error) }
  142. if (r.error != null) { return denied(r) }
  143. emit client commentChanged(r.ticket.id, pageEventOf(r.event))
  144. return reply(200, r)
  145. }
  146. static stateOfTicket = (t, req) => {
  147. if (req.method != 'POST') { return fail(405, 'POST only') }
  148. auth = apiAuth(req)
  149. if (auth == null || auth.response != null) { return authDenied(auth, 'an API write') }
  150. rb = readBody(req, ['state'], ['text'])
  151. if (rb.bad != null) { return refuse(rb.bad) }
  152. if (t == null) { return fail(404, 'no such ticket') }
  153. w = actorIn(auth, req, t.project)
  154. if (w.response != null) { return w.response }
  155. u = w.user
  156. b = rb.body
  157. r = changeState(t.id, b.state, u, b.text)
  158. if (r.error == 'no such ticket') { return fail(404, r.error) }
  159. if (r.forbidden == true) { return reply(403, { error = r.error field = r.field }) }
  160. if (r.error != null) { return refuse({ error = r.error field = r.field }) }
  161. emit client ticketEvent(r.ticket.id, pageEventOf(r.event), r.ticket)
  162. if (r.assignEvent != null) { emit client ticketEvent(r.ticket.id, pageEventOf(r.assignEvent), r.ticket) }
  163. emit client ticketsRelated(relatedViews(r.ticket.id, []))
  164. return reply(201, r)
  165. }
  166. // POST …/assign { assignee } (ticket #20): a member's display name (or users id, or ident id); '' = nobody.
  167. // Needs the role edit or admin → else 403.
  168. static assignOfTicket = (t, req) => {
  169. if (req.method != 'POST') { return fail(405, 'POST only') }
  170. u = apiUser(req)
  171. if (u == null || u.response != null) { return authDenied(u, 'an API write') }
  172. rb = readBody(req, [], ['assignee'])
  173. if (rb.bad != null) { return refuse(rb.bad) }
  174. if (rb.body.assignee == null) { return refuse({ error = "field 'assignee' is required: a member's name, or an empty string for nobody" field = 'assignee' }) }
  175. if (t == null) { return fail(404, 'no such ticket') }
  176. let who = ''
  177. if (rb.body.assignee.trim() != '') {
  178. f = userByRef(rb.body.assignee, t.project)
  179. if (f.error != null) { return refuse({ error = f.error field = 'assignee' }) }
  180. who = f.user.id
  181. }
  182. r = assignTicket(t.id, u, who)
  183. if (r.forbidden == true) { return reply(403, { error = r.error field = r.field }) }
  184. if (r.error != null) { return refuse({ error = r.error field = r.field }) }
  185. emit client ticketEvent(r.ticket.id, pageEventOf(r.event), r.ticket)
  186. return reply(201, r)
  187. }
  188. // POST …/edit { subject?, summary? } (ticket #8): a member with the role edit or admin → else 403;
  189. // the history keeps the previous values
  190. static editOfTicket = (t, req) => {
  191. if (req.method != 'POST') { return fail(405, 'POST only') }
  192. u = apiUser(req)
  193. if (u == null || u.response != null) { return authDenied(u, 'an API write') }
  194. rb = readBody(req, [], ['subject' 'summary'])
  195. if (rb.bad != null) { return refuse(rb.bad) }
  196. if (t == null) { return fail(404, 'no such ticket') }
  197. b = rb.body
  198. r = editTicket(t.id, u, b.subject, b.summary)
  199. if (r.error == 'no such ticket') { return fail(404, r.error) }
  200. if (r.forbidden == true) { return reply(403, { error = r.error }) }
  201. if (r.error != null) { return refuse({ error = r.error field = r.field }) }
  202. emit client ticketEvent(r.ticket.id, pageEventOf(r.event), r.ticket)
  203. emit client ticketsRelated(relatedViews(r.ticket.id, []))
  204. return reply(201, r)
  205. }
  206. // RELATIONS (ticket #4, mission 017; tickets.hl "relations"): a ticket is named as
  207. // `<project>#<number>` or by its UUID. Who may: a member with the role edit or admin in THIS ticket's project (the one whose relation changes; mission ST) → else 403.
  208. // POST …/parent { parent }: set the parent; `"parent": ""` removes it.
  209. // POST …/blocked-by { add } or { remove }: this ticket is (no longer) blocked by that one.
  210. // 201 { ticket, event (kind link) }; the ticket rows and every open page of the tickets involved follow.
  211. static linkReply = (r) => {
  212. if (r.error == 'no such ticket') { return fail(404, r.error) }
  213. if (r.forbidden == true) { return reply(403, { error = r.error }) }
  214. if (r.error != null) { return refuse({ error = r.error field = r.field }) }
  215. emit client ticketEvent(r.ticket.id, pageEventOf(r.event), r.ticket)
  216. emit client ticketsRelated(r.related)
  217. return reply(201, { ticket = r.ticket event = r.event })
  218. }
  219. static parentOfTicket = (t, req) => {
  220. if (req.method != 'POST') { return fail(405, 'POST only') }
  221. u = apiUser(req)
  222. if (u == null || u.response != null) { return authDenied(u, 'an API write') }
  223. rb = readBody(req, [], ['parent'])
  224. if (rb.bad != null) { return refuse(rb.bad) }
  225. if (rb.body.parent == null) { return refuse({ error = "field 'parent' is required: <project>#<number>, or an empty string to remove the parent" field = 'parent' }) }
  226. if (t == null) { return fail(404, 'no such ticket') }
  227. return linkReply(setParent(t.id, u, rb.body.parent))
  228. }
  229. static blockersOfTicket = (t, req) => {
  230. if (req.method != 'POST') { return fail(405, 'POST only') }
  231. u = apiUser(req)
  232. if (u == null || u.response != null) { return authDenied(u, 'an API write') }
  233. rb = readBody(req, [], ['add' 'remove'])
  234. if (rb.bad != null) { return refuse(rb.bad) }
  235. b = rb.body
  236. if ((b.add == null) == (b.remove == null)) { return refuse({ error = "give exactly one of 'add' or 'remove' (<project>#<number>)" field = b.add == null ? 'add' : 'remove' }) }
  237. if (t == null) { return fail(404, 'no such ticket') }
  238. adding = b.add != null
  239. return linkReply(changeBlocker(t.id, u, adding ? b.add : b.remove, adding, adding ? 'add' : 'remove'))
  240. }
  241. // ---- the event stream for programs (ticket #26, lib/stream.hl) ----------------------------------------
  242. // GET /api/events[?project=a,b&assignee=<name|id|me>&notMine=1&after=<id>] with `Authorization: Bearer <token>`
  243. // (a user's token, or a project key tktc_ = that project only) → text/event-stream, held open. 401 without a
  244. // valid token, 400 a bad filter, 403 a project the key does not reach. `Last-Event-ID` wins over `after`.
  245. static getEvents = (route, req) => {
  246. if (req.method != 'GET') { return fail(405, 'GET only') }
  247. auth = apiAuth(req)
  248. if (auth == null || auth.response != null) { return authDenied(auth, 'the event stream') }
  249. who = auth.user != null ? { user = auth.user } : { project = auth.conn.project }
  250. q = req.query != null ? req.query : queryOf(req.path)
  251. r = subscriptionOf(q, req.headers['last-event-id'], who)
  252. if (r.error != null) { return denied(r) }
  253. if (openStream(req.respond, r.sub) == null) { return fail(500, 'the event stream could not start') }
  254. return null
  255. }
  256. // GET /api/attachments/:id (tickets#27, opened by tickets#37): an attachment's bytes, for everyone who may see its comment — and a
  257. // ticket's comments are public, so no sign-in is needed. 404 for an unknown file or one whose comment was deleted.
  258. static getAttachment = (route, req) => {
  259. if (req.method != 'GET' && req.method != 'HEAD') { return fail(405, 'GET only') }
  260. r = attachmentFor(route.params.id)
  261. if (r.error != null) { return fail(r.status, r.error) }
  262. return fileReply(r.file)
  263. }
  264. static getTicket = (route, req) => { return getOne(byRef(route), req) }
  265. static postComment = (route, req) => { return commentOnTicket(byRef(route), req) }
  266. static postState = (route, req) => { return stateOfTicket(byRef(route), req) }
  267. static postCommentEdit = (route, req) => { return changeOfComment(byRef(route), route, req, 'edit') }
  268. static postCommentDelete = (route, req) => { return changeOfComment(byRef(route), route, req, 'delete') }
  269. static postCommentLike = (route, req) => { return changeOfComment(byRef(route), route, req, 'like') }
  270. static postProjectCommentEdit = (route, req) => { return changeOfComment(byNumber(route), route, req, 'edit') }
  271. static postProjectCommentDelete = (route, req) => { return changeOfComment(byNumber(route), route, req, 'delete') }
  272. static postProjectCommentLike = (route, req) => { return changeOfComment(byNumber(route), route, req, 'like') }
  273. static getProjectTicket = (route, req) => { return getOne(byNumber(route), req) }
  274. static postProjectComment = (route, req) => { return commentOnTicket(byNumber(route), req) }
  275. static postProjectState = (route, req) => { return stateOfTicket(byNumber(route), req) }
  276. static postAssign = (route, req) => { return assignOfTicket(byRef(route), req) }
  277. static postProjectAssign = (route, req) => { return assignOfTicket(byNumber(route), req) }
  278. static postEdit = (route, req) => { return editOfTicket(byRef(route), req) }
  279. static postProjectEdit = (route, req) => { return editOfTicket(byNumber(route), req) }
  280. static postParent = (route, req) => { return parentOfTicket(byRef(route), req) }
  281. static postProjectParent = (route, req) => { return parentOfTicket(byNumber(route), req) }
  282. static postBlockers = (route, req) => { return blockersOfTicket(byRef(route), req) }
  283. static postProjectBlockers = (route, req) => { return blockersOfTicket(byNumber(route), req) }
  284. // ---- projects and members (ticket #20; projects.hl) ----------------------------------------------
  285. // GET /api/projects → { projects (the slugs), details (title, slug, description, id …), states, roles }
  286. // POST /api/projects { title, slug?, description? } → 201 { project, members } — any logged-in user opens
  287. // a project and is its first admin; the slug is generated from the title unless given
  288. // GET /api/projects/:slug → { project, members } (the slug may be an old one)
  289. // POST /api/projects/:slug { title?, slug?, description? } → { project } — admin only; a new slug keeps the old one working
  290. // POST /api/projects/:slug/members { user, role } — admin only: `user` = a display name, an ident id or a user id of someone
  291. // who logged in here; sets (adds / changes) the role: use | edit | admin
  292. // POST /api/projects/:slug/members/remove { user } — admin only
  293. // POST /api/projects/:slug/invites { role, uses?, days?, email? } — admin only: an ident invite link → { url, id, expires, mailed }
  294. // GET /api/inbox — the token's user: { pending, review }, the tickets assigned to them
  295. static getProjects = (route, req) => {
  296. if (req.method == 'POST') { return postNewProject(req) }
  297. if (req.method != 'GET') { return fail(405, 'GET or POST') }
  298. let details = []
  299. for (p of projectRecords()) { details.push(projectRowOf(p)) }
  300. return reply(200, { projects = projectNames() details = details states = states roles = roles })
  301. }
  302. static postNewProject = (req) => {
  303. u = apiUser(req)
  304. if (u == null || u.response != null) { return authDenied(u, 'an API write') }
  305. rb = readBody(req, ['title'], ['slug' 'description'])
  306. if (rb.bad != null) { return refuse(rb.bad) }
  307. r = createProject(u, rb.body.title, rb.body.slug, rb.body.description)
  308. if (r.error != null) { return denied(r) }
  309. return reply(201, r)
  310. }
  311. static getProject = (route, req) => {
  312. p = projectByAnySlug(slugOf(route))
  313. if (req.method == 'GET') {
  314. if (p == null) { return fail(404, 'no such project') }
  315. return reply(200, { project = projectRowOf(p) members = memberRows(p.id) })
  316. }
  317. if (req.method != 'POST') { return fail(405, 'GET or POST') }
  318. u = apiUser(req)
  319. if (u == null || u.response != null) { return authDenied(u, 'an API write') }
  320. rb = readBody(req, [], ['title' 'slug' 'description'])
  321. if (rb.bad != null) { return refuse(rb.bad) }
  322. if (p == null) { return fail(404, 'no such project') }
  323. r = updateProject(p.id, u, rb.body.title, rb.body.slug, rb.body.description)
  324. if (r.error != null) { return denied(r) }
  325. return reply(200, r)
  326. }
  327. static postMembers = (route, req) => {
  328. if (req.method != 'POST') { return fail(405, 'POST only') }
  329. p = projectByAnySlug(slugOf(route))
  330. u = apiUser(req)
  331. if (u == null || u.response != null) { return authDenied(u, 'an API write') }
  332. rb = readBody(req, ['user' 'role'], [])
  333. if (rb.bad != null) { return refuse(rb.bad) }
  334. if (p == null) { return fail(404, 'no such project') }
  335. f = userByRef(rb.body.user, null)
  336. if (f.error != null) { return refuse({ error = f.error field = 'user' }) }
  337. r = setMemberRole(p.id, u, f.user.id, rb.body.role)
  338. if (r.error != null) { return denied(r) }
  339. return reply(200, r)
  340. }
  341. static postMemberRemove = (route, req) => {
  342. if (req.method != 'POST') { return fail(405, 'POST only') }
  343. p = projectByAnySlug(slugOf(route))
  344. u = apiUser(req)
  345. if (u == null || u.response != null) { return authDenied(u, 'an API write') }
  346. rb = readBody(req, ['user'], [])
  347. if (rb.bad != null) { return refuse(rb.bad) }
  348. if (p == null) { return fail(404, 'no such project') }
  349. f = userByRef(rb.body.user, p.id)
  350. if (f.error != null) { return refuse({ error = f.error field = 'user' }) }
  351. r = removeMember(p.id, u, f.user.id)
  352. if (r.error != null) { return denied(r) }
  353. return reply(200, r)
  354. }
  355. // an invite is only for an admin (invites.hl mayInvite); ident makes the link
  356. static postInvites = (route, req) => {
  357. if (req.method != 'POST') { return fail(405, 'POST only') }
  358. p = projectByAnySlug(slugOf(route))
  359. u = apiUser(req)
  360. if (u == null || u.response != null) { return authDenied(u, 'an API write') }
  361. rb = readBody(req, ['role'], ['uses' 'days' 'email'])
  362. if (rb.bad != null) { return refuse(rb.bad) }
  363. if (p == null) { return fail(404, 'no such project') }
  364. b = rb.body
  365. no = mayInvite(p, u, b.role)
  366. if (no != null) { return denied(no) }
  367. n = b.uses == null ? 1 : toNumber(b.uses)
  368. d = b.days == null ? 7 : toNumber(b.days)
  369. if (n == null || n < 1 || n > 1000) { return denied({ error = "'uses' must be a number from 1 to 1000" field = 'uses' }) }
  370. if (d == null || d < 1 || d > 90) { return denied({ error = "'days' must be a number from 1 to 90" field = 'days' }) }
  371. r = createInvite(p.id, b.role, n, d, b.email)
  372. if (r.error != null) { return denied(r) }
  373. return reply(201, r)
  374. }
  375. static getInbox = (route, req) => {
  376. if (req.method != 'GET') { return fail(405, 'GET only') }
  377. u = apiUser(req)
  378. if (u == null || u.response != null) { return authDenied(u, 'an API write') }
  379. return new Response(JSON.stringify(inboxRows(u)), { status = 200 headers = hdr({ 'Content-Type' = 'application/json; charset=utf-8' 'Cache-Control' = 'no-store' }) })
  380. }
  381. // ---- connecting an app (ticket #21; connections.hl) ------------------------------------------------
  382. // GET /connect?app=&label=&return=&state= — the app sends the person here; the request is stored and the browser goes to
  383. // the page /connect/<nonce> (components/connect.hl), where they pick or make a project and confirm.
  384. // POST /api/connect/exchange { code } — the app's SERVER swaps the one-time code for the project's key:
  385. // 200 { key, project (slug), title, api }; 400 for an unknown, used or expired code. The key is shown here ONCE.
  386. // GET /api/projects/:slug/connections — who is connected (public, like the project page)
  387. // POST /api/projects/:slug/connections/remove { id } — an admin disconnects; the key is dead at once
  388. static connectStart = (route, req) => {
  389. if (req.method != 'GET') { return problemRedirect('connect', 'connect-method') }
  390. q = req.query != null ? req.query : {}
  391. r = createRequest(q.app, q.label, q['return'], q.state)
  392. if (r.error != null) { return problemRedirect('connect', connectCodeOf(r)) }
  393. to = '/connect/' + r.nonce
  394. return new Response('continue at ' + to, { status = 302 headers = hdr({ 'Location' = to 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' }) })
  395. }
  396. static connectExchange = (route, req) => {
  397. if (req.method != 'POST') { return fail(405, 'POST only') }
  398. rb = readBody(req, ['code'], [])
  399. if (rb.bad != null) { return refuse(rb.bad) }
  400. r = exchangeConnectCode(rb.body.code)
  401. if (r.error != null) { return refuse({ error = r.error field = 'code' }) }
  402. emit client connectionsChanged(r.project)
  403. return new Response(JSON.stringify(r), { status = 200 headers = hdr({ 'Content-Type' = 'application/json; charset=utf-8' 'Cache-Control' = 'no-store' }) })
  404. }
  405. static projectConnections = (route, req) => {
  406. if (req.method != 'GET') { return fail(405, 'GET only') }
  407. p = projectByAnySlug(slugOf(route))
  408. if (p == null) { return fail(404, 'no such project') }
  409. return reply(200, { connections = connectionRows(p.id) })
  410. }
  411. static projectDisconnect = (route, req) => {
  412. if (req.method != 'POST') { return fail(405, 'POST only') }
  413. p = projectByAnySlug(slugOf(route))
  414. u = apiUser(req)
  415. if (u == null || u.response != null) { return authDenied(u, 'an API write') }
  416. rb = readBody(req, ['id'], [])
  417. if (rb.bad != null) { return refuse(rb.bad) }
  418. if (p == null) { return fail(404, 'no such project') }
  419. r = disconnect(p.id, u, rb.body.id)
  420. if (r.error != null) { return denied(r) }
  421. emit client connectionsChanged(p.slug)
  422. return reply(200, r)
  423. }
  424. // ---- old page URLs -----------------------------------------------------------------------------
  425. // They move for good (301) to the short page URLs of ticket #25, `/<slug>` and `/<slug>/<number>`, with the
  426. // project's CURRENT slug; what names nothing → 404.
  427. // `/tickets/<old global number>` (also `/tickets/<uuid>`)
  428. static oldTicketPage = (route, req) => {
  429. t = ticketByRef(route.params.ref)
  430. if (t == null) { return missing('no such ticket') }
  431. return moved(ticketHref(projectSlugOf(t), t.number))
  432. }
  433. // `/projects/<slug>` (ticket #25)
  434. static oldProjectPage = (route, req) => {
  435. p = projectByAnySlug(route.params.slug)
  436. if (p == null) { return missing('no such project') }
  437. return moved(projectHrefOf(p.slug))
  438. }
  439. // `/projects/<slug>/<number>` and `/projects/<slug>/tickets/<number>` (the form the conductor sent in messages)
  440. static oldProjectTicketPage = (route, req) => {
  441. t = ticketAt(route.params.slug, route.params.number)
  442. if (t == null) { return missing('no such ticket') }
  443. return moved(ticketHref(projectSlugOf(t), t.number))
  444. }
  445. // ---- THE LOGIN BUTTON'S RETURN (ticket #7; ident README "How apps use ident") -------------
  446. // The shell's "Log in with ident" goes to <ident>/login?key=<IDENT_API_KEY>&return=
  447. // <TICKETS_PUBLIC_URL>/login/callback; ident sends the browser back here with ?ident_code=.
  448. // The code is exchanged SERVER SIDE (users.hl exchangeCode, key + secret) for the per-app
  449. // identity id; its tickets user (made at the first login) goes into THIS browser's hl:web
  450. // session (`req.session`, the cookie's — hybriel#11; minted from `sessions` when the browser brought none), then →
  451. // the page the login started from (`?next=`, ticket #10, safeNext) or `/`, where the shell asks for a display name
  452. // if there is none yet. project.hl hands `req` AND the framework's session store BY REFERENCE: copied into this
  453. // second call, the session inside `req` would be a copy too and the login would never reach the session the
  454. // framework keeps (mission 010: the gate's logins failed that way).
  455. // (The identity selector logs in through the shell's face `identLogin` instead — no reload.)
  456. static loginCallback = (route, &req, &sessions) => {
  457. if (req.method != 'GET') { return problemRedirect('login', 'login-method') }
  458. q = req.query != null ? req.query : {}
  459. code = q.ident_code
  460. if (code == null || code == '') { return problemRedirect('login', 'login-no-code') }
  461. x = exchangeCode(code)
  462. if (x.error != null) { return problemRedirect('login', loginCodeOf(x.error)) }
  463. u = ensureUser(x.identity)
  464. if (u == null) { return problemRedirect('login', 'login-no-user') }
  465. // an INVITE (ident#22, invites.hl): ident sends `invite=<id>` with the code
  466. let joined = null
  467. if (q.invite != null && q.invite != '') {
  468. j = joinByInvite(q.invite, x.identity, u.id)
  469. if (j.error != null) { return problemRedirect('login', 'login-invite') }
  470. joined = j.project
  471. }
  472. // THE CALLBACK NEVER SIGNS OUT THE SESSION IT FINDS (ident#28): only a valid ident code gets here (a missing, unknown or reused
  473. // code answered 400 above and touched nothing). The new user goes onto the SAME session, the browser's own cookie and id; a
  474. // session is minted only when the browser brought none. The old code logged the presented session out first, so a repeated
  475. // or raced callback could leave the browser signed out.
  476. let s = req.session
  477. if (s == null) { s = sessions.mint() }
  478. s.user = { id = u.id }
  479. s.data.tag = randomBytes(16)
  480. sessions.save(s)
  481. to = joined != null ? projectHrefOf(joined.slug) : safeNext(q.next)
  482. res = new Response('logged in', { status = 302 headers = hdr({ 'Location' = to 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' }) })
  483. res.headers['Set-Cookie'] = sessions.cookieHeader(s.id)
  484. return res
  485. }
  486. // BACK TO THE PAGE (ticket #10): login.js puts `?next=<path + query of the page>` into the
  487. // button's return URL. Only a same-origin PATH goes: it starts with ONE `/` (not `//`, no
  488. // backslash — `/\host` is another host to some browsers), only URL-safe characters (no
  489. // scheme, no spaces, no control characters), at most 500 chars, never /login/… itself.
  490. // Anything else → `/`.
  491. static nextChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;@!$()*:'
  492. static safeNext = (want) => {
  493. if (want == null || hlTypeName(want) != 'String' || want == '' || want.length > 500) { return '/' }
  494. if (want.slice(0, 1) != '/' || want.slice(0, 2) == '//' || want.slice(0, 7) == '/login/') { return '/' }
  495. let i = 0
  496. while (i < want.length) {
  497. if (!nextChars.includes(want[i])) { return '/' }
  498. i = i + 1
  499. }
  500. return want
  501. }

Branches

Latest commits

  • fd83ac1fconductor: caramboleyo is the user, not owner/creatorApollo
  • 3b858c91Log backup hard-link fixmre
  • 7f6b37a0deploy.sh backup: tar --hard-dereference (hard links broke mpackdb sidecars on restore)mre
  • e93711d9Log E30 livemre
  • 59c02e4dMerge e30: preserve edited state note labels in Markdownmre
  • 30970796Log E30 deploy GOmre
  • 7c8e6d83Limit edited state note fix to Markdown renderingmre
  • 910536d0Log E30 reviewmre
  • 36984386Preserve state transitions when their notes are editedmre
  • d75cb946Log E30 startmre
  • 0bf3fefaMission 030: edited state note labelmre
  • 691565c6Log neutral-ticket rule checkmre
  • bc3bdecerecords: day38b live, #94 purgedmre
  • f6c5aa0dMerge main (records)mre
  • e23d42acconnect gate: wait for hydration before clicking Disconnectmre
  • a5d45d00records: D38 cause, GOmre
  • 19eeb938records: D38 gates, two day38b failuresmre
  • f8e42a85Re-vendor tickets to Hybriel set day38b (1e554d7)mre
  • 51645016Merge purge-94 (#94, identity rule)mre
  • 94d6ca2arecords: D38 startedmre