gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitccebb0c7ccebb0c7mobile: ticket number stays on one line, filter chips one scrolling row, fields full width under their caption, Edit/action buttons, member names whole, 44 px relation linksmreccebb0c7/lib/api.hl

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

Branches

Latest commits

  • ccebb0c7mobile: ticket number stays on one line, filter chips one scrolling row, fields full width under their caption, Edit/action buttons, member names whole, 44 px relation linksmre
  • f2dc7741gate: the phone toolbar is two even rows (E2)mre
  • 20f7c33async components.hybriel 214c318: MdEditor on a phone, two even toolbar rows of 44 px targets, label 15 px, table head 16 px (E2)mre
  • d74a5482sync components.hybriel 134b4e3: MdEditor builds an editor put into the page at once, redraws a surface put in anew (F5, hybriel#211)mre
  • 9d02c540sync components.hybriel 6b0936a: the 'edited' foldable drops the theme's border and marginmre
  • 22751914sync components.hybriel 8d79ff7: bubble hugs its content, quiet 'edited' label; gate checksmre
  • c8452453sync components 9a: shared Icon (icons/icons.hl), md-editor toolbar icons + single focus ring (components f4-icons ba96735)mre
  • 52ba11e8sync-components: copy icons/icons.hl + README (F4); testsmre
  • 138d198dmd-editor.hl: verbatim copy of components f3-mdvalue (an older text handed back is kept)mre
  • 18d2df60md-editor.hl: verbatim copy of components f3-mdvalue (an outside value change is shown by the editor)mre
  • f6764bedreports/H1-hydrate.mdmre
  • 1bbbf0edtests/browser.mjs: wait for hydration before clicking the login button on / (device B)mre
  • 6f503cfctests/cdp.mjs: HL_CPU_THROTTLE=<rate> optional CPU throttling for gate runsmre
  • e17e2855re-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • a6ddccd2re-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • 81e036b7docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • 5d8d2cf6deploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • 58e8c02cmission 024: report, LOG, STATUS, e2e fixmre
  • 50778073tests/e2e-route-marker.mjs: first paint marker, comments post/edit redrawmre
  • c5203298mission 024: MainMenu marks the page from the route (layouts 0bcc629 main-menu.hl); browser-side marker removed; gate: marker in the server HTMLmre