gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit926f7061926f7061|||PR records: merges, D36 deploymre926f7061/lib/api.hl

31.1 KB

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

Branches

Latest commits

  • 926f7061|||PR records: merges, D36 deploymre
  • bf58534eMerge branch 'l33-final' into mainTickets
  • 759a9ac3|||PR thin login (tickets#46, #45): merge main, route entry cleanupmre
  • 239436d8Merge remote-tracking branch 'origin/main' into l33-finalmre
  • 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
  • ecd7e226|||PR Consolidate login and move handler logic into topic libraries (partial)mre
  • 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