gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit2e1b116f2e1b116ftickets: re-vendor Hybriel master acaceaf3 (framework ec8d6c1d): plugins/web patch queue while a page is built, anonymous session cookies refresh; gate waits for the comment editors to draw (W174) and clicks the form editor when it stands still; security gate: main's code runs on its own binary, lazy-session cookie checksmre2e1b116f/lib/api.hl

27.9 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, hdr, 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 reply(200, { 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 reply(200, { 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 reply(200, 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 THIS ticket's project (the one whose relation changes; mission ST) → 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, opened by tickets#37): an attachment's bytes, for everyone who may see its comment — and a
  256. // ticket's comments are public, so no sign-in is needed. 404 for an unknown file or one whose comment was deleted.
  257. static getAttachment = (route, req) => {
  258. if (req.method != 'GET' && req.method != 'HEAD') { return fail(405, 'GET only') }
  259. r = attachmentFor(route.params.id)
  260. if (r.error != null) { return fail(r.status, r.error) }
  261. return fileReply(r.file)
  262. }
  263. static getTicket = (route, req) => { return getOne(byRef(route), req) }
  264. static postComment = (route, req) => { return commentOnTicket(byRef(route), req) }
  265. static postState = (route, req) => { return stateOfTicket(byRef(route), req) }
  266. static postCommentEdit = (route, req) => { return changeOfComment(byRef(route), route, req, 'edit') }
  267. static postCommentDelete = (route, req) => { return changeOfComment(byRef(route), route, req, 'delete') }
  268. static postCommentLike = (route, req) => { return changeOfComment(byRef(route), route, req, 'like') }
  269. static postProjectCommentEdit = (route, req) => { return changeOfComment(byNumber(route), route, req, 'edit') }
  270. static postProjectCommentDelete = (route, req) => { return changeOfComment(byNumber(route), route, req, 'delete') }
  271. static postProjectCommentLike = (route, req) => { return changeOfComment(byNumber(route), route, req, 'like') }
  272. static getProjectTicket = (route, req) => { return getOne(byNumber(route), req) }
  273. static postProjectComment = (route, req) => { return commentOnTicket(byNumber(route), req) }
  274. static postProjectState = (route, req) => { return stateOfTicket(byNumber(route), req) }
  275. static postAssign = (route, req) => { return assignOfTicket(byRef(route), req) }
  276. static postProjectAssign = (route, req) => { return assignOfTicket(byNumber(route), req) }
  277. static postEdit = (route, req) => { return editOfTicket(byRef(route), req) }
  278. static postProjectEdit = (route, req) => { return editOfTicket(byNumber(route), req) }
  279. static postParent = (route, req) => { return parentOfTicket(byRef(route), req) }
  280. static postProjectParent = (route, req) => { return parentOfTicket(byNumber(route), req) }
  281. static postBlockers = (route, req) => { return blockersOfTicket(byRef(route), req) }
  282. static postProjectBlockers = (route, req) => { return blockersOfTicket(byNumber(route), req) }
  283. // ---- projects and members (ticket #20; projects.hl) ----------------------------------------------
  284. // GET /api/projects → { projects (the slugs), details (title, slug, description, id …), states, roles }
  285. // POST /api/projects { title, slug?, description? } → 201 { project, members } — any logged-in user opens
  286. // a project and is its first admin; the slug is generated from the title unless given
  287. // GET /api/projects/:slug → { project, members } (the slug may be an old one)
  288. // POST /api/projects/:slug { title?, slug?, description? } → { project } — admin only; a new slug keeps the old one working
  289. // POST /api/projects/:slug/members { user, role } — admin only: `user` = a display name, an ident id or a user id of someone
  290. // who logged in here; sets (adds / changes) the role: use | edit | admin
  291. // POST /api/projects/:slug/members/remove { user } — admin only
  292. // POST /api/projects/:slug/invites { role, uses?, days?, email? } — admin only: an ident invite link → { url, id, expires, mailed }
  293. // GET /api/inbox — the token's user: { pending, review }, the tickets assigned to them
  294. static getProjects = (route, req) => {
  295. if (req.method == 'POST') { return postNewProject(req) }
  296. if (req.method != 'GET') { return fail(405, 'GET or POST') }
  297. let details = []
  298. for (p of projectRecords()) { details.push(projectRowOf(p)) }
  299. return reply(200, { projects = projectNames() details = details states = states roles = roles })
  300. }
  301. static postNewProject = (req) => {
  302. u = apiUser(req)
  303. if (u == null) { return unauthorized() }
  304. rb = readBody(req, ['title'], ['slug' 'description'])
  305. if (rb.bad != null) { return refuse(rb.bad) }
  306. r = createProject(u, rb.body.title, rb.body.slug, rb.body.description)
  307. if (r.error != null) { return denied(r) }
  308. return reply(201, r)
  309. }
  310. static getProject = (route, req) => {
  311. p = projectByAnySlug(slugOf(route))
  312. if (req.method == 'GET') {
  313. if (p == null) { return fail(404, 'no such project') }
  314. return reply(200, { project = projectRowOf(p) members = memberRows(p.id) })
  315. }
  316. if (req.method != 'POST') { return fail(405, 'GET or POST') }
  317. u = apiUser(req)
  318. if (u == null) { return unauthorized() }
  319. rb = readBody(req, [], ['title' 'slug' 'description'])
  320. if (rb.bad != null) { return refuse(rb.bad) }
  321. if (p == null) { return fail(404, 'no such project') }
  322. r = updateProject(p.id, u, rb.body.title, rb.body.slug, rb.body.description)
  323. if (r.error != null) { return denied(r) }
  324. return reply(200, r)
  325. }
  326. static postMembers = (route, req) => {
  327. if (req.method != 'POST') { return fail(405, 'POST only') }
  328. p = projectByAnySlug(slugOf(route))
  329. u = apiUser(req)
  330. if (u == null) { return unauthorized() }
  331. rb = readBody(req, ['user' 'role'], [])
  332. if (rb.bad != null) { return refuse(rb.bad) }
  333. if (p == null) { return fail(404, 'no such project') }
  334. f = userByRef(rb.body.user, null)
  335. if (f.error != null) { return refuse({ error = f.error field = 'user' }) }
  336. r = setMemberRole(p.id, u, f.user.id, rb.body.role)
  337. if (r.error != null) { return denied(r) }
  338. return reply(200, r)
  339. }
  340. static postMemberRemove = (route, req) => {
  341. if (req.method != 'POST') { return fail(405, 'POST only') }
  342. p = projectByAnySlug(slugOf(route))
  343. u = apiUser(req)
  344. if (u == null) { return unauthorized() }
  345. rb = readBody(req, ['user'], [])
  346. if (rb.bad != null) { return refuse(rb.bad) }
  347. if (p == null) { return fail(404, 'no such project') }
  348. f = userByRef(rb.body.user, p.id)
  349. if (f.error != null) { return refuse({ error = f.error field = 'user' }) }
  350. r = removeMember(p.id, u, f.user.id)
  351. if (r.error != null) { return denied(r) }
  352. return reply(200, r)
  353. }
  354. // an invite is only for an admin (invites.hl mayInvite); ident makes the link
  355. static postInvites = (route, req) => {
  356. if (req.method != 'POST') { return fail(405, 'POST only') }
  357. p = projectByAnySlug(slugOf(route))
  358. u = apiUser(req)
  359. if (u == null) { return unauthorized() }
  360. rb = readBody(req, ['role'], ['uses' 'days' 'email'])
  361. if (rb.bad != null) { return refuse(rb.bad) }
  362. if (p == null) { return fail(404, 'no such project') }
  363. b = rb.body
  364. no = mayInvite(p, u, b.role)
  365. if (no != null) { return denied(no) }
  366. n = b.uses == null ? 1 : toNumber(b.uses)
  367. d = b.days == null ? 7 : toNumber(b.days)
  368. if (n == null || n < 1 || n > 1000) { return denied({ error = "'uses' must be a number from 1 to 1000" field = 'uses' }) }
  369. if (d == null || d < 1 || d > 90) { return denied({ error = "'days' must be a number from 1 to 90" field = 'days' }) }
  370. r = createInvite(p.id, b.role, n, d, b.email)
  371. if (r.error != null) { return denied(r) }
  372. return reply(201, r)
  373. }
  374. static getInbox = (route, req) => {
  375. if (req.method != 'GET') { return fail(405, 'GET only') }
  376. u = apiUser(req)
  377. if (u == null) { return unauthorized() }
  378. return new Response(JSON.stringify(inboxRows(u)), { status = 200 headers = hdr({ 'Content-Type' = 'application/json; charset=utf-8' 'Cache-Control' = 'no-store' }) })
  379. }
  380. // ---- connecting an app (ticket #21; connections.hl) ------------------------------------------------
  381. // GET /connect?app=&label=&return=&state= — the app sends the person here; the request is stored and the browser goes to
  382. // the page /connect/<nonce> (components/connect.hl), where they pick or make a project and confirm.
  383. // POST /api/connect/exchange { code } — the app's SERVER swaps the one-time code for the project's key:
  384. // 200 { key, project (slug), title, api }; 400 for an unknown, used or expired code. The key is shown here ONCE.
  385. // GET /api/projects/:slug/connections — who is connected (public, like the project page)
  386. // POST /api/projects/:slug/connections/remove { id } — an admin disconnects; the key is dead at once
  387. static connectStart = (route, req) => {
  388. if (req.method != 'GET') { return htmlPage(405, 'Connect', 'GET only') }
  389. q = req.query != null ? req.query : {}
  390. r = createRequest(q.app, q.label, q['return'], q.state)
  391. if (r.error != null) { return htmlPage(r.busy == true ? 429 : 400, 'Connect', r.error) }
  392. to = '/connect/' + r.nonce
  393. return new Response('continue at ' + to, { status = 302 headers = hdr({ 'Location' = to 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' }) })
  394. }
  395. static connectExchange = (route, req) => {
  396. if (req.method != 'POST') { return fail(405, 'POST only') }
  397. rb = readBody(req, ['code'], [])
  398. if (rb.bad != null) { return refuse(rb.bad) }
  399. r = exchangeConnectCode(rb.body.code)
  400. if (r.error != null) { return refuse({ error = r.error field = 'code' }) }
  401. emit client connectionsChanged(r.project)
  402. return new Response(JSON.stringify(r), { status = 200 headers = hdr({ 'Content-Type' = 'application/json; charset=utf-8' 'Cache-Control' = 'no-store' }) })
  403. }
  404. static projectConnections = (route, req) => {
  405. if (req.method != 'GET') { return fail(405, 'GET only') }
  406. p = projectByAnySlug(slugOf(route))
  407. if (p == null) { return fail(404, 'no such project') }
  408. return reply(200, { connections = connectionRows(p.id) })
  409. }
  410. static projectDisconnect = (route, req) => {
  411. if (req.method != 'POST') { return fail(405, 'POST only') }
  412. p = projectByAnySlug(slugOf(route))
  413. u = apiUser(req)
  414. if (u == null) { return unauthorized() }
  415. rb = readBody(req, ['id'], [])
  416. if (rb.bad != null) { return refuse(rb.bad) }
  417. if (p == null) { return fail(404, 'no such project') }
  418. r = disconnect(p.id, u, rb.body.id)
  419. if (r.error != null) { return denied(r) }
  420. emit client connectionsChanged(p.slug)
  421. return reply(200, r)
  422. }
  423. // ---- old page URLs -----------------------------------------------------------------------------
  424. // They move for good (301) to the short page URLs of ticket #25, `/<slug>` and `/<slug>/<number>`, with the
  425. // project's CURRENT slug; what names nothing → 404.
  426. // `/tickets/<old global number>` (also `/tickets/<uuid>`)
  427. static oldTicketPage = (route, req) => {
  428. t = ticketByRef(route.params.ref)
  429. if (t == null) { return missing('no such ticket') }
  430. return moved(ticketHref(projectSlugOf(t), t.number))
  431. }
  432. // `/projects/<slug>` (ticket #25)
  433. static oldProjectPage = (route, req) => {
  434. p = projectByAnySlug(route.params.slug)
  435. if (p == null) { return missing('no such project') }
  436. return moved(projectHrefOf(p.slug))
  437. }
  438. // `/projects/<slug>/<number>` and `/projects/<slug>/tickets/<number>` (the form the conductor sent in messages)
  439. static oldProjectTicketPage = (route, req) => {
  440. t = ticketAt(route.params.slug, route.params.number)
  441. if (t == null) { return missing('no such ticket') }
  442. return moved(ticketHref(projectSlugOf(t), t.number))
  443. }
  444. // ---- THE LOGIN BUTTON'S RETURN (ticket #7; ident README "How apps use ident") -------------
  445. // The shell's "Log in with ident" goes to <ident>/login?key=<IDENT_API_KEY>&return=
  446. // <TICKETS_PUBLIC_URL>/login/callback; ident sends the browser back here with ?ident_code=.
  447. // The code is exchanged SERVER SIDE (users.hl exchangeCode, key + secret) for the per-app
  448. // identity id; its tickets user (made at the first login) goes into THIS browser's hl:web
  449. // session (`req.session`, the cookie's — hybriel#11; minted from `sessions` when the browser brought none), then →
  450. // the page the login started from (`?next=`, ticket #10, safeNext) or `/`, where the shell asks for a display name
  451. // if there is none yet. project.hl hands `req` AND the framework's session store BY REFERENCE: copied into this
  452. // second call, the session inside `req` would be a copy too and the login would never reach the session the
  453. // framework keeps (mission 010: the gate's logins failed that way).
  454. // (The identity selector logs in through the shell's face `identLogin` instead — no reload.)
  455. static loginCallback = (route, &req, &sessions) => {
  456. if (req.method != 'GET') { return htmlPage(405, 'Login failed', 'GET only') }
  457. q = req.query != null ? req.query : {}
  458. code = q.ident_code
  459. if (code == null || code == '') { return htmlPage(400, 'Login failed', 'ident sent no login code') }
  460. x = exchangeCode(code)
  461. if (x.error != null) { return htmlPage(400, 'Login failed', x.error) }
  462. u = ensureUser(x.identity)
  463. if (u == null) { return htmlPage(500, 'Login failed', 'could not store the user') }
  464. // an INVITE (ident#22, invites.hl): ident sends `invite=<id>` with the code
  465. let joined = null
  466. if (q.invite != null && q.invite != '') {
  467. j = joinByInvite(q.invite, x.identity, u.id)
  468. if (j.error != null) { return htmlPage(400, 'Invite failed', j.error) }
  469. joined = j.project
  470. }
  471. // THE CALLBACK NEVER SIGNS OUT THE SESSION IT FINDS (ident#28): only a valid ident code gets here (a missing, unknown or reused
  472. // code answered 400 above and touched nothing). The new user goes onto the SAME session, the browser's own cookie and id; a
  473. // session is minted only when the browser brought none. The old code logged the presented session out first, so a repeated
  474. // or raced callback could leave the browser signed out.
  475. let s = req.session
  476. if (s == null) { s = sessions.mint() }
  477. s.user = { id = u.id }
  478. s.data.tag = randomBytes(16)
  479. sessions.save(s)
  480. to = joined != null ? projectHrefOf(joined.slug) : safeNext(q.next)
  481. res = new Response('logged in', { status = 302 headers = hdr({ 'Location' = to 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' }) })
  482. res.headers['Set-Cookie'] = sessions.cookieHeader(s.id)
  483. return res
  484. }
  485. // BACK TO THE PAGE (ticket #10): login.js puts `?next=<path + query of the page>` into the
  486. // button's return URL. Only a same-origin PATH goes: it starts with ONE `/` (not `//`, no
  487. // backslash — `/\host` is another host to some browsers), only URL-safe characters (no
  488. // scheme, no spaces, no control characters), at most 500 chars, never /login/… itself.
  489. // Anything else → `/`.
  490. static nextChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;@!$()*:'
  491. static safeNext = (want) => {
  492. if (want == null || hlTypeName(want) != 'String' || want == '' || want.length > 500) { return '/' }
  493. if (want.slice(0, 1) != '/' || want.slice(0, 2) == '//' || want.slice(0, 7) == '/login/') { return '/' }
  494. let i = 0
  495. while (i < want.length) {
  496. if (!nextChars.includes(want[i])) { return '/' }
  497. i = i + 1
  498. }
  499. return want
  500. }

Branches

Latest commits

  • 2e1b116ftickets: re-vendor Hybriel master acaceaf3 (framework ec8d6c1d): plugins/web patch queue while a page is built, anonymous session cookies refresh; gate waits for the comment editors to draw (W174) and clicks the form editor when it stands still; security gate: main's code runs on its own binary, lazy-session cookie checksmre
  • 361bc0fetickets: re-vendor Hybriel 7a684920 (WIP, not deployed); on Error exits 1 at startup; migrate passes its log by reference; gate checks follow lazy sessions and the 413 refusalmre
  • 8a69999cident#28: /login/callback never signs out the session it finds; a valid code puts the user on the same sessionmre
  • 337e9b21tickets#37: a comment's files are open to everyone who can read the commentmre
  • 1800600ftickets: write the standby service out in full so the boot gate can read the main servicemre
  • 8179d287tickets: standby service on its port plus 10 and a deploy that hands over through it without a gapmre
  • 0398145ctickets: the table grid rule is marked functional for check-thememre
  • 40fddc20tickets takes components e54f83a: tables get thin grey lines from the theme, desktop toolbar stays one row with the Table button, F4 check counts 11 buttonsmre
  • c1b77d61tickets#35: text typed before the editor is built is taken in once by the build (the input handler no longer writes it to the field first, which doubled the first letters); the gate failure shows the surfacemre
  • 32bf1873tickets#35: the gate types right after the load with the CPU slowed, no waitingmre
  • 64ea9ca2tickets#35: text typed into the reply editor before the page has finished starting is kept; the gate types right after loadmre
  • ccd3a327tickets: the security gate expects frame-src to be exactly the ident address (the sign-in frame), still no wildcard or selfmre
  • 4348dbabident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
  • 66ef3005Merge branch 'iw-ident-widget'mre
  • bc0ad663tickets: a gap between your name and Log out in the phone header (they touched); gate checks itmre
  • 2f818d46UX2: report, LOG line, e2e fixes, gate pause after loadmre
  • af3ef7c4gate: the legacy state line says progressmre
  • 62480a00tickets#33: a state change with a note is a comment card in the feed (same framework rendering, can be liked, edited, deleted), its state line stands alone; gate checks for a new comment with and without a state change, at once and after a reloadmre
  • 4ae80007UX: Respond is one composer (state in its footer, button says what happens); New ticket / New project windows in the list heading row; project form shared; theme copied from layouts; gates and a lisbeth e2emre
  • f03b438atickets header: the selector alone top right plus your name and Log out as before the theme missions; the user icon is gonemre