gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitaf3ef7c4af3ef7c4gate: the legacy state line says progressmreaf3ef7c4/lib/api.hl

28.1 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): 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 reply(200, { 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 reply(200, { 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 new Response(JSON.stringify(inboxRows(u)), { status = 200 headers = hdr({ 'Content-Type' = 'application/json; charset=utf-8' 'Cache-Control' = 'no-store' }) })
  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(r.busy == true ? 429 : 400, 'Connect', r.error) }
  400. to = '/connect/' + r.nonce
  401. return new Response('continue at ' + to, { status = 302 headers = hdr({ '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 = hdr({ '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 reply(200, { 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. // A LOGIN GETS A NEW SESSION ID (session fixation, mission ST; as gitoria SG): a cookie planted before the login must not become
  480. // the logged-in one. The old session (if any) is logged out and left behind.
  481. old = req.session
  482. if (old != null) {
  483. old.user = null
  484. old.data.tag = null
  485. sessions.save(old)
  486. }
  487. let s = sessions.mint()
  488. s.user = { id = u.id }
  489. s.data.tag = randomBytes(16)
  490. sessions.save(s)
  491. to = joined != null ? projectHrefOf(joined.slug) : safeNext(q.next)
  492. res = new Response('logged in', { status = 302 headers = hdr({ 'Location' = to 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' }) })
  493. res.headers['Set-Cookie'] = sessions.cookieHeader(s.id)
  494. return res
  495. }
  496. // BACK TO THE PAGE (ticket #10): login.js puts `?next=<path + query of the page>` into the
  497. // button's return URL. Only a same-origin PATH goes: it starts with ONE `/` (not `//`, no
  498. // backslash — `/\host` is another host to some browsers), only URL-safe characters (no
  499. // scheme, no spaces, no control characters), at most 500 chars, never /login/… itself.
  500. // Anything else → `/`.
  501. static nextChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;@!$()*:'
  502. static safeNext = (want) => {
  503. if (want == null || hlTypeName(want) != 'String' || want == '' || want.length > 500) { return '/' }
  504. if (want.slice(0, 1) != '/' || want.slice(0, 2) == '//' || want.slice(0, 7) == '/login/') { return '/' }
  505. let i = 0
  506. while (i < want.length) {
  507. if (!nextChars.includes(want[i])) { return '/' }
  508. i = i + 1
  509. }
  510. return want
  511. }

Branches

Latest commits

  • 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
  • e9f428e7tools: reown-authors (tracker#36: every author that is not Caramboleyo or Apollo becomes the project's conductor; antcolony, miserit-anthar, hybrilior, termuplex stay) and a read-only author surveymre
  • f51029abMerge branch 'sy-sync'mre
  • eae6e8c7sync components.hybriel 4922f9c: comments like / Edit / Delete / 'edited' are 44 px targets; gate: 'edited' hit-area padding, thread targets check (SY)mre
  • 0de4750btheme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 4eeb7bfeST2 report wordingmre
  • 2558f56cst2-sec: keep the hlsid session cookie name (no one is signed out), Secure flag only; gate: a cookie issued by main stays signed in; ident stub serves selector.js; security.mjs in deploy GATESmre
  • ea2e440esecurity audit (ST): JSON body cap, relation rights, login session rotation, __Host- Secure cookie, API security headers, CSP+referrer meta, /connect cap, one-line subjects, tests/security.mjs, reportmre
  • 7c8c2282sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b6277497report MT-mobile, LOGmre
  • 6709398blist paging: the newest rows come first (the sorted array was not used); filter rows hide their scrollbar; gate checks the ordermre
  • 31736a80gate: member-name check fails on the old row layout toomre
  • e03ae537gate: the phone checks run on without the Show more button (so old code reports every failed check)mre
  • adf7f132gate: 390 px checks for the mobile audit fixes (row number, filters, field widths, Edit, member names, relation taps, paging)mre
  • 28e9c938ticket list: draw the newest 50 rows and a Show more button (500 rows were a 2-4 s first paint, 740 KB, a 90 000 px phone page)mre
  • 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