gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit5822cb3a5822cb3aMerge branch 'o34-clean' into mainTickets5822cb3a/lib/api.hl

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

Branches

Latest commits

  • 5822cb3aMerge branch 'o34-clean' into mainTickets
  • 0870653c|||PR offline note from __hlOnline, no polling (tickets#41)mre
  • 14cf96b4Merge branch 'records-t36' into mainTickets
  • 07749fa1|||PR records: day72 + #40 mergedmre
  • 6dea1c60Merge branch 'r35-day72' into mainTickets
  • 7bcfdc22|||PR drop worker edits to conductor recordsmre
  • 2617b6ee|||PR dialogs: host flag cleared on close, dialog gate (tickets#40)mre
  • 6e701371|||PR record partial day72 dialog validationmre
  • b9fb9a91|||PR bind ticket dialog visibility to member flagsmre
  • 0788e65f|||PR re-vendor Hybriel day72mre
  • e2a6bdcfMerge branch 'records-t35' into mainTickets
  • d8d54df1|||PR records: R35 day72 + #40mre
  • 8a7f475aMerge branch 'records-t33' into mainTickets
  • e685d0c2|||PR records: PROCEDURES merge callmre
  • b42aff2b|||PR records: GO 2026-11-23, workers L33 O34, PROCEDURES.mdmre
  • ed091d44Merge branch 'records' into mainTickets
  • 180c0cdb|||PR records: ticket move live (M32), hybriel#439mre
  • 497cae7bMerge branch 'm32-move' into mainTickets
  • 772e0696|||PR Allow project admins to move tickets between their projectsmre
  • be92a560Merge branch 'records' into mainTickets