gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit369e4b9c369e4b9cMerge branch 'k40-lists' into mainTickets369e4b9c/lib/connections.hl

12.1 KB

  1. import { writerOfSession } from './users.hl'
  2. // lib/connections.hl — AN APP IS CONNECTED TO ONE PROJECT (ticket tickets.worldapi.org#21; first app: gitoria).
  3. // Statics only. One hl:mpackdb table beside the others (storage/mpackdb/connections.db, UUID keys):
  4. //
  5. // connectionsTable pk @id index nonce, hash, codeHash, project
  6. // { status, nonce, app, label, returnUrl, state, project, createdBy, codeHash, expires, hash, created }
  7. //
  8. // THE FLOW (README "Connecting an app"):
  9. // 1. the app sends the browser to <tickets>/connect?app=gitoria&label=<owner/repo>&return=<url>&state=<opaque>
  10. // → a REQUEST (status 'request', an unguessable nonce) and a redirect to /connect/<nonce> (components/connect.hl).
  11. // 2. the person logs in (ident), picks a project they are ADMIN of — or makes a new one — and confirms.
  12. // The request becomes a connection (status 'waiting') with a ONE-TIME CODE (5 minutes); the page links back to
  13. // `return?code=<code>&state=<state>`.
  14. // 3. the app exchanges the code on the server: POST /api/connect/exchange { code } → { key, project }.
  15. // The connection is 'active'; only the sha256 of the key is stored (`tktc_` + 48 hex, shown once).
  16. // 4. the key acts inside THAT ONE project only (lib/api-helpers.hl apiAuth / actorIn): create tickets, comment, change state.
  17. // Every write names the person: header `X-Tickets-Identity: <ident public id>`; the person is a tickets user
  18. // (they logged in here once and chose a name) and the project's ROLES apply to them as to a token.
  19. // 5. the project page shows "connected to <app>: <label>"; an admin's "Disconnect" deletes the row — the key is dead at once.
  20. // The return URL is the app's: only https on worldapi.org (and its subdomains) — or an origin listed in
  21. // TICKETS_CONNECT_ORIGINS (comma separated, e.g. http://127.0.0.1:8700 for a dev copy). The page shows the host.
  22. import { MPackDB } from 'hl:mpackdb'
  23. import { now } from 'hl:time'
  24. import { randomBytes, sha256 } from 'hl:crypto'
  25. import { env } from 'hl:proc'
  26. import { storageDir, first, countOf, isHex, plainError } from './util.hl'
  27. import { isIdentId, userOfIdentity, nameOfUser, publicUrl } from './users.hl'
  28. import { projectRecord, projectRecords, isAdminOf, createProject, userOk, notAdmin } from './projects.hl'
  29. static connectionsTable = new MPackDB(file = storageDir + '/connections.db', primaryKey = '@id', indexes = ['nonce', 'hash', 'codeHash', 'project'])
  30. static requestTtlMs = 3600000
  31. static codeTtlMs = 300000
  32. // /connect is open to anyone (the app sends the browser there before anybody is logged in): at most this many requests wait at once,
  33. // expired ones are dropped first (mission ST: every call used to add a row for good)
  34. static maxOpenRequests = 300
  35. static openRequests = () => {
  36. let open = 0
  37. all = connectionsTable.find(null, null)
  38. if (countOf(all) == 0) { return 0 }
  39. for (c of all) {
  40. if ((c.status == 'request' || c.status == 'waiting') && c.expires < now()) { connectionsTable.delete(c.id) }
  41. else if (c.status == 'request') { open = open + 1 }
  42. }
  43. return open
  44. }
  45. static extraOrigins = () => {
  46. v = env('TICKETS_CONNECT_ORIGINS')
  47. out = []
  48. if (v == null || v.trim() == '') { return out }
  49. for (o of v.split(',')) { if (o.trim() != '') { out.push(o.trim()) } }
  50. return out
  51. }
  52. // the characters a return URL may hold: URL-safe, no spaces, no quotes, no '#' (the code goes in the query)
  53. static urlChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;:@!$()*'
  54. // the host (with port) of an absolute URL: everything between '://' and the next '/' or '?'
  55. static authorityOf = (url) => {
  56. at = url.indexOf('://')
  57. if (at < 0) { return '' }
  58. rest = url.slice(at + 3)
  59. let end = rest.length
  60. s = rest.indexOf('/')
  61. if (s >= 0 && s < end) { end = s }
  62. q = rest.indexOf('?')
  63. if (q >= 0 && q < end) { end = q }
  64. return rest.slice(0, end)
  65. }
  66. // null when the URL may be an app's return address, else the reason
  67. static returnError = (url) => {
  68. if (url == null || hlTypeName(url) != 'String' || url == '') { return 'the app sent no return address' }
  69. if (url.length > 500) { return 'the return address is too long' }
  70. let i = 0
  71. while (i < url.length) {
  72. if (!urlChars.includes(url[i])) { return 'the return address holds a character that is not allowed' }
  73. i = i + 1
  74. }
  75. for (o of extraOrigins()) {
  76. if (url == o || url.startsWith(o + '/') || url.startsWith(o + '?')) { return null }
  77. }
  78. if (!url.startsWith('https://')) { return 'the return address must be https on worldapi.org' }
  79. host = authorityOf(url)
  80. if (host == '' || host.includes('@') || host.includes(':') || host.includes('%')) { return 'the return address has an unusual host' }
  81. if (host != 'worldapi.org' && !host.endsWith('.worldapi.org')) { return 'the return address must be on worldapi.org' }
  82. return null
  83. }
  84. static hostOf = (url) => { return authorityOf(url) }
  85. static sepOf = (url) => { return url.includes('?') ? '&' : '?' }
  86. // ---- 1. the request ---------------------------------------------------------------------------
  87. // answers { nonce } or { error }
  88. static createRequest = (app, label, returnUrl, state) => {
  89. a = app == null ? '' : ('' + app).trim()
  90. if (a == '') { return { error = 'the app sent no name' } }
  91. let bad = plainError(a, 60, 'the app name')
  92. if (bad == null) { bad = plainError(label == null ? '' : label, 100, 'the label') }
  93. if (bad == null) { bad = plainError(state == null ? '' : state, 200, 'the state') }
  94. if (bad == null) { bad = returnError(returnUrl) }
  95. if (bad != null) { return { error = bad } }
  96. if (openRequests() >= maxOpenRequests) { return { error = 'too many connection requests are waiting — try again in a few minutes' busy = true } }
  97. let nonce = randomBytes(16)
  98. id = connectionsTable.put({ status = 'request' nonce = nonce app = a label = label == null ? '' : label.trim() returnUrl = returnUrl state = state == null ? '' : state project = '' createdBy = '' codeHash = '' hash = '' expires = now() + requestTtlMs created = now() })
  99. if (id == null) { return { error = 'could not store the request: ' + connectionsTable.lastError() } }
  100. return { nonce = nonce }
  101. }
  102. // the open request of a nonce, or null (unknown, used, expired)
  103. static requestOf = (nonce) => {
  104. if (!isHex(nonce, 64)) { return null }
  105. c = first(connectionsTable.find('nonce', nonce))
  106. if (c == null || c.status != 'request' || c.expires < now()) { return null }
  107. return c
  108. }
  109. // what the connect page shows of a request
  110. static requestView = (c) => {
  111. return { app = c.app label = c.label hasLabel = c.label != '' host = hostOf(c.returnUrl) }
  112. }
  113. // the projects a user is an ADMIN of: [{ id, title, slug }]
  114. static adminProjects = (user) => {
  115. out = []
  116. if (user == null) { return out }
  117. for (p of projectRecords()) { if (isAdminOf(p.id, user)) { out.push({ id = p.id title = p.title slug = p.slug }) } }
  118. return out
  119. }
  120. // ---- 2. the confirmation ----------------------------------------------------------------------
  121. // `projectId` '' = make a new project titled `title` (the person becomes its admin). Answers { error, forbidden? } or
  122. // { url (back to the app, with the one-time code), project (title), slug }
  123. static confirmRequest = (nonce, user, projectId, title) => {
  124. c = requestOf(nonce)
  125. if (c == null) { return { error = 'this request is used up or expired — start again from the app' } }
  126. if (!userOk(user)) { return { error = 'log in with ident and choose a display name first' } }
  127. let p = null
  128. if (projectId == null || projectId == '') {
  129. r = createProject(user, title, '', '')
  130. if (r.error != null) { return { error = r.error } }
  131. p = projectRecord(r.project.id)
  132. } else {
  133. p = projectRecord('' + projectId)
  134. if (p == null) { return { error = 'no such project' } }
  135. if (!isAdminOf(p.id, user)) { return notAdmin }
  136. }
  137. // a second connection of the same app and label to the same project replaces the first: its key dies
  138. for (o of connectionsOf(p.id, true)) { if (o.app == c.app && o.label == c.label && o.id != c.id) { connectionsTable.delete(o.id) } }
  139. code = randomBytes(24)
  140. c.status = 'waiting'
  141. c.nonce = ''
  142. c.project = p.id
  143. c.createdBy = user.id
  144. c.codeHash = sha256(code)
  145. c.expires = now() + codeTtlMs
  146. connectionsTable.update(c.id, c)
  147. let url = c.returnUrl + sepOf(c.returnUrl) + 'code=' + code
  148. if (c.state != '') { url = url + '&state=' + encodeURIComponent(c.state) }
  149. return { url = url project = p.title slug = p.slug }
  150. }
  151. // ---- 3. the exchange --------------------------------------------------------------------------
  152. // answers { key, project (slug), title, api } or { error }
  153. static exchangeConnectCode = (code) => {
  154. if (!isHex(code, 200)) { return { error = 'that is not a connection code' } }
  155. c = first(connectionsTable.find('codeHash', sha256(code)))
  156. if (c == null || c.status != 'waiting' || c.expires < now()) { return { error = 'unknown, used or expired code — connect again' } }
  157. p = projectRecord(c.project)
  158. if (p == null) { return { error = 'the project is gone' } }
  159. let key = 'tktc_' + randomBytes(24)
  160. c.status = 'active'
  161. c.hash = sha256(key)
  162. c.codeHash = ''
  163. c.expires = 0
  164. c.connected = now()
  165. connectionsTable.update(c.id, c)
  166. return { key = key project = p.slug title = p.title api = publicUrl + '/api/projects/' + p.slug }
  167. }
  168. // ---- 4. the key -------------------------------------------------------------------------------
  169. static isKeyHeader = (header) => {
  170. if (header == null || hlTypeName(header) != 'String') { return false }
  171. h = header.trim()
  172. return (h.startsWith('Bearer ') || h.startsWith('bearer ')) && h.slice(7).trim().startsWith('tktc_')
  173. }
  174. // `Authorization: Bearer tktc_…` → the ACTIVE connection, or null
  175. static connectionOfKey = (header) => {
  176. if (!isKeyHeader(header)) { return null }
  177. key = header.trim().slice(7).trim()
  178. if (key.length != 53) { return null }
  179. c = first(connectionsTable.find('hash', sha256(key)))
  180. if (c == null || c.status != 'active') { return null }
  181. return c
  182. }
  183. // the person an app write names (`X-Tickets-Identity`): { user } or { error }
  184. static personOf = (identity) => {
  185. if (identity == null || hlTypeName(identity) != 'String' || !isIdentId(identity.trim())) {
  186. return { error = 'a write through a connection names the person: header X-Tickets-Identity: <their ident id>' }
  187. }
  188. u = userOfIdentity(identity.trim())
  189. if (u == null || u.name == '') { return { error = 'that person has not logged in to tickets yet — they log in once and choose a display name' } }
  190. return { user = u }
  191. }
  192. // ---- 5. the project page ----------------------------------------------------------------------
  193. // the connections of a project: [{ id, app, label, by, when }]; `all` = also the waiting ones
  194. static connectionsOf = (projectId, all) => {
  195. out = []
  196. rows = connectionsTable.find('project', projectId)
  197. if (countOf(rows) == 0) { return out }
  198. for (c of rows) { if (all || c.status == 'active') { out.push(c) } }
  199. return out
  200. }
  201. static connectionRows = (projectId) => {
  202. out = []
  203. for (c of connectionsOf(projectId, false)) {
  204. out.push({ id = c.id app = c.app label = c.label hasLabel = c.label != '' by = nameOfUser(c.createdBy) text = c.app + (c.label != '' ? ': ' + c.label : '') })
  205. }
  206. return out
  207. }
  208. // an admin ends a connection; the key is dead at once. answers { connections } or { error, forbidden? }
  209. static disconnect = (projectId, actor, connectionId) => {
  210. p = projectRecord(projectId)
  211. if (p == null) { return { error = 'no such project' } }
  212. if (!userOk(actor)) { return { error = 'log in with ident and choose a display name first' } }
  213. if (!isAdminOf(p.id, actor)) { return notAdmin }
  214. if (connectionId == null || hlTypeName(connectionId) != 'String' || connectionId == '') { return { error = 'no such connection' } }
  215. c = connectionsTable.fetch(connectionId)
  216. if (c == null || c.project != p.id) { return { error = 'no such connection' } }
  217. connectionsTable.delete(c.id)
  218. return { connections = connectionRows(p.id) }
  219. }
  220. static confirmForSession = (nonce, projectId, title, session) => {
  221. w = writerOfSession(session)
  222. if (w.error != null) { return { error = w.error } }
  223. if (hlTypeName(nonce) != 'String' || hlTypeName(projectId) != 'String' || hlTypeName(title) != 'String') { return { error = 'nonce, project and title must be text' } }
  224. r = confirmRequest(nonce, w.user, projectId, title)
  225. if (r.error != null) { return { error = r.error } }
  226. return { url = r.url project = r.project slug = r.slug }
  227. }

Branches

Latest commits

  • 369e4b9cMerge branch 'k40-lists' into mainTickets
  • 9af8e780|||PR Use keyed list mutations for live ticket updatesmre
  • 610d8e8aMerge branch 'records-t39' into mainTickets
  • 32bcdf24|||PR records: GO P39 K40mre
  • 4123c6d1Merge branch 'records-t38' into mainTickets
  • cd3641a1|||PR records: day72 deploy live, tickets closedmre
  • 7d44d852Merge branch 'records-t37' into mainTickets
  • 926f7061|||PR records: merges, D36 deploymre
  • bf58534eMerge branch 'l33-final' into mainTickets
  • 759a9ac3|||PR thin login (tickets#46, #45): merge main, route entry cleanupmre
  • 239436d8Merge remote-tracking branch 'origin/main' into l33-finalmre
  • 5822cb3aMerge branch 'o34-clean' into mainTickets
  • 0870653c|||PR offline note from __hlOnline, no polling (tickets#41)mre
  • 14cf96b4Merge branch 'records-t36' into mainTickets
  • 07749fa1|||PR records: day72 + #40 mergedmre
  • ecd7e226|||PR Consolidate login and move handler logic into topic libraries (partial)mre
  • 6dea1c60Merge branch 'r35-day72' into mainTickets
  • 7bcfdc22|||PR drop worker edits to conductor recordsmre
  • 2617b6ee|||PR dialogs: host flag cleared on close, dialog gate (tickets#40)mre
  • 6e701371|||PR record partial day72 dialog validationmre