gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitf83d9c0df83d9c0dtickets (mission 016): report reports/016-comments-block.md, LOG, STATUS, README gate countmref83d9c0d/lib/api.hl

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

Branches

Latest commits

  • f83d9c0dtickets (mission 016): report reports/016-comments-block.md, LOG, STATUS, README gate countmre
  • eef80f55tickets (mission 016): comments through the shared Comments block (layouts#2) — edit (author, earlier versions kept), delete (author, asks; leaves one line in the history), like (members, toggle) on the server (lib/comments.hl, append-only tables), faces + API …/comments/:comment/{edit,delete,like}, push commentChanged; every run of comments is a block in place in the history; Markdown fields on the Hybriel MdEditor (shared/md-editor.js retired: it took over the block's <md-editor>); blocks copied verbatim from components.hybriel 9db927d (tools/sync-components.sh); gates browser 351/0 (old 326/0), events 52/0 (old 52/0)mre
  • eb7aeeb9mission brief 016mre
  • e4c34759paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • 26efb23freport w6-events (events test)mre
  • c6bfab04mission 015: re-vendor Hybriel 0f396652 (static build), reportmre
  • b7ec5981mission brief 015mre
  • 5dc68731docker-compose: init: true (hybriel#156, PID 1 ignored SIGTERM, every restart waited 10 s)mre
  • 8a460b16mission 014: Apollo's 'stream opened right after the start gets no live events' is not a tickets bug — events.mjs checks early streamsmre
  • 6309ca81mission brief 014mre
  • c1161469mission 013: GitHub pipe tables on ticket pages (lib/markdown.hl + View + CSS) and re-vendor hybriel master a832f73bmre
  • a30b5d12mission brief (w13)mre
  • b50a6f93w9 (tickets): re-vendor hybriel 9f912f3b (#146 emit in a lib static, #147) — the 12 live-push emits in lib/api.hl compile as they are; cold start (#148): tests wait TICKETS_COLD_MS for every start, deploy.sh gates browser + events and waits up to 120 s for the URL, container /tmp tmpfs + hybriel-cache volume; events-client stops at EVENTS_MAX inside a chunk; connect.mjs ports by env. bin/hybriel sha256 7421907868ac07d8a7d08296b083c6f8b20407d0e099ce4bebbf7ae053d9060a. Gates (8720–8739): browser 315/0 (+ all-cold 315/0), events 48/0 cold, connect 60/0, short-id 19/0; real-data copy old 0e8a41c vs new: 2,425 reads + 72 writes identical after masking ?v hashes, offline at, route order; event stream on the copy delivers. Not deployed.mre
  • 43be6578w9: re-vendor hybriel master edfd400a; event stream imports sseStart/sseSend/sseAlive from hl:http1 (hybriel#144), useTransport gone; tools/import.hl plain declarations. BLOCKED: hybriel-native refuses `emit client` in a static (lib/api.hl) — the server does not compile on edfd400a, gates fail at start; scratch copy without those emits: events 48/0, gate 254 ok up to the first live pushmre
  • 0e8a41caw6 (ticket #26): event stream for programs — GET /api/events (Server-Sent Events)mre
  • bb64d57cmission 012 (ticket #25 API part): every /api/projects/<x>/… route takes the project's id (12-char record id) as well as its slug, same answers byte for byte; tickets stay under their project, no global /api/tickets/<x>. gate 315/0 (old code: the 13 id checks fail), connect 60/0, live-data copy old vs new 1,484 identical, slug vs id 772 identicalmre
  • 7538b034mission 011 (ticket #25 web part): short page URLs /<slug> and /<slug>/<number>; /projects/<slug>, /projects/<slug>/<n>, /projects/<slug>/tickets/<n> and /tickets/<ref> answer 301 (current slug); slug pages moved behind hl:web's own routes after construction (they answered /__hl/* and /components/*.hl); reserved slugs refused; API paths unchanged. gate 293/0, connect 60/0, live-data copy 187/0, API old vs new: only page links differmre
  • 0369106emission 010 (code order) 4/4: README file map + import order + 'Same output' test, STATUS (entry, lessons, how to verify), LOG, report; tests/realdata-baseline.mjs + realdata-compare*.py (a cleanup answers the same on live data), tests/letcount.pymre
  • a75e0279mission 010 (code order) 3/4: let only where a variable is reassigned or re-bound in a loop body (456 lets → plain declarations; Hybriel refuses a plain declaration inside a loop on its 2nd pass). gate 249/0, connect 60/0, real-data reads identical, a 50-step write sequence (API + faces) identical to the old codemre
  • e9d5c618mission 010 (code order) 2/4: one lib/ file per topic — store.hl split into projects / tickets (+ relations) / events / tickets-helpers, util.hl shared helpers (env, storage dir, URLs, sorts, Vienna time), the function routes out of project.hl into lib/api.hl (thin; auth/filters/Accept in api-helpers.hl), invite + member-removal logic out of the faces/routes into invites.hl / tickets.hl; project.hl is the map. /login/callback gets req + the session store by reference. gate 249/0, connect 60/0, real-data reads identicalmre