gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit4348dbab4348dbabident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre4348dbab/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

  • 4348dbabident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
  • 66ef3005Merge branch 'iw-ident-widget'mre
  • bc0ad663tickets: a gap between your name and Log out in the phone header (they touched); gate checks itmre
  • 2f818d46UX2: report, LOG line, e2e fixes, gate pause after loadmre
  • af3ef7c4gate: the legacy state line says progressmre
  • 62480a00tickets#33: a state change with a note is a comment card in the feed (same framework rendering, can be liked, edited, deleted), its state line stands alone; gate checks for a new comment with and without a state change, at once and after a reloadmre
  • 4ae80007UX: Respond is one composer (state in its footer, button says what happens); New ticket / New project windows in the list heading row; project form shared; theme copied from layouts; gates and a lisbeth e2emre
  • f03b438atickets header: the selector alone top right plus your name and Log out as before the theme missions; the user icon is gonemre
  • 81f10e4eident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
  • e9f428e7tools: reown-authors (tracker#36: every author that is not Caramboleyo or Apollo becomes the project's conductor; antcolony, miserit-anthar, hybrilior, termuplex stay) and a read-only author surveymre
  • f51029abMerge branch 'sy-sync'mre
  • eae6e8c7sync components.hybriel 4922f9c: comments like / Edit / Delete / 'edited' are 44 px targets; gate: 'edited' hit-area padding, thread targets check (SY)mre
  • 0de4750btheme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 4eeb7bfeST2 report wordingmre
  • 2558f56cst2-sec: keep the hlsid session cookie name (no one is signed out), Secure flag only; gate: a cookie issued by main stays signed in; ident stub serves selector.js; security.mjs in deploy GATESmre
  • ea2e440esecurity audit (ST): JSON body cap, relation rights, login session rotation, __Host- Secure cookie, API security headers, CSP+referrer meta, /connect cap, one-line subjects, tests/security.mjs, reportmre
  • 7c8c2282sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b6277497report MT-mobile, LOGmre
  • 6709398blist paging: the newest rows come first (the sorted array was not used); filter rows hide their scrollbar; gate checks the ordermre
  • 31736a80gate: member-name check fails on the old row layout toomre