gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitbc3bdecebc3bdecerecords: day38b live, #94 purgedmrebc3bdece/lib/connections.hl

11.5 KB

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

Branches

Latest commits

  • bc3bdecerecords: day38b live, #94 purgedmre
  • f6c5aa0dMerge main (records)mre
  • e23d42acconnect gate: wait for hydration before clicking Disconnectmre
  • a5d45d00records: D38 cause, GOmre
  • 19eeb938records: D38 gates, two day38b failuresmre
  • f8e42a85Re-vendor tickets to Hybriel set day38b (1e554d7)mre
  • 51645016Merge purge-94 (#94, identity rule)mre
  • 94d6ca2arecords: D38 startedmre
  • 9df09aacmission 029: day38b re-vendor + deploymre
  • d2834f65records: #94 backup planmre
  • 4467d8cbrecords: #94 purge readymre
  • aa2d124eREADME: the #94 purge gatemre
  • e843ff7cOne-time purge of miserit-anthar#94 (#94, identity rule): idempotent step in lib/migrate.hl, fixture gate tests/purge94.mjsmre
  • 506a4efdmission 028: #94, identity rulemre
  • 78c7f48eRefine mpackdb holdmre
  • 3d7d89c8Record mpackdb hold until day38mre
  • f1bf7195#51 done; my subscription idmre
  • 9870b945status: #51 proof greenmre
  • e92173c6log: #51 live push proofmre
  • 72d87041log: Hermes push livemre