gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit26efb23f26efb23freport w6-events (events test)mre26efb23f/lib/api.hl

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

Branches

Latest commits

  • 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
  • 97e269b5mission 010 (code order) 1/4: .hl files out of the root — lib/ (store, users, connections, invites, migrate, markdown, mdview, import = ticketfile, util = localtime, jsoncheck, api-helpers = api), tools/import.hl, components/styles.hl; import paths only. gate 249/0, connect 60/0, real-data reads identicalmre
  • 38f9d10ftickets: Hybriel master 06617221 (plugin allocators 3a781359 + 413f60e4, mpackdb 2cb7ae5e, http1 773de63e); gate 249/0, connect 60/0mre
  • d3db6139tickets: Hybriel master 190aa11d (fc838894 GC correctness, #126 closure scopes, #127); gate 249/0, connect 60/0mre
  • bce182e3tickets: Hybriel master 7eea0d32 (#126 memory, #48 lambda copies its argument); migrate.hl lambdas take &logmre