gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitf04afc43f04afc43tickets: MdEditor from components 59704ce (a file manager copy still attaches, pipe rows, tickets#49)mref04afc43/lib/users.hl

10.9 KB

  1. // lib/users.hl — WHO WRITES (ticket tickets.worldapi.org#7, mission 011; CONCEPT.md "Login via
  2. // ident"). Reading stays public; writing needs a login through ident. Two hl:mpackdb tables
  3. // beside the ticket tables (storage/mpackdb/, UUID keys — creator's convention):
  4. //
  5. // usersTable pk @id index !identity { identity, name, created }
  6. // identity = ident's PER-APP identity id (32 hex) — the answer of POST <ident>/api/exchange.
  7. // It stays SERVER SIDE (ident CONCEPT: "the app never exposes the identity id");
  8. // the one exception is the user's own /you page (mission 011: the architect
  9. // needs the creator's id for TICKETS_CREATOR_IDENTITY).
  10. // name = the DISPLAY NAME, asked once at the first login (CONCEPT point 6). An ordinary
  11. // field ('' until chosen) so ident can fill it later (the "handshake" properties).
  12. // tokensTable pk @id index !hash user { user (users @id), hash = sha256(token), label, created }
  13. // API TOKENS for machine clients (CONCEPT point 5): `tkt_` + 48 hex, shown ONCE; only the
  14. // sha256 is stored. `Authorization: Bearer <token>` acts as that user. Revoke = the row goes.
  15. //
  16. // THE SESSION (hl:web) carries `user = { id = <users @id> }` only — hl:web ships
  17. // `session.user` to the page, so never the identity id. `session.data.tag` is a random tag of
  18. // this login: the audience addresses `signedIn` / `signedOut` to THIS session's tabs by it.
  19. //
  20. // Config (environment, or `.env` beside project.hl — the runtime loads it; never commit it):
  21. // IDENT_URL ident's public origin (selector script, login button). Default https://ident.worldapi.org
  22. // IDENT_EXCHANGE_URL where the SERVER posts /api/exchange. Default = IDENT_URL
  23. // IDENT_API_KEY / IDENT_API_SECRET this app's registration in ident (pk_… public, sk_… secret)
  24. // TICKETS_PUBLIC_URL this app's public origin (the login button's return URL). Default https://tickets.worldapi.org
  25. // TICKETS_CREATOR_IDENTITY the creator's ident id (a short id like a68sz; before ident#23 32 hex). Since ticket #20 there is
  26. // no creator-only workflow: it is read ONLY by migrate.hl, which makes this person the admin of
  27. // the projects that existed before roles. Unset = those projects get no admin.
  28. import { MPackDB } from 'hl:mpackdb'
  29. import { now } from 'hl:time'
  30. import { randomBytes, sha256 } from 'hl:crypto'
  31. import { fetch } from 'hl:fetch'
  32. import { localStamp, envOr, storageDir, countOf, first, encode, isHex, plainError, newestFirst } from './util.hl'
  33. static identUrl = envOr('IDENT_URL', 'https://ident.worldapi.org')
  34. static identExchangeUrl = envOr('IDENT_EXCHANGE_URL', identUrl)
  35. static identKey = envOr('IDENT_API_KEY', '')
  36. static identSecret = envOr('IDENT_API_SECRET', '')
  37. static publicUrl = envOr('TICKETS_PUBLIC_URL', 'https://tickets.worldapi.org')
  38. static creatorIdentity = envOr('TICKETS_CREATOR_IDENTITY', '')
  39. static usersTable = new MPackDB(file = storageDir + '/users.db', primaryKey = '@id', indexes = ['!identity'])
  40. static tokensTable = new MPackDB(file = storageDir + '/tokens.db', primaryKey = '@id', indexes = ['!hash', 'user'])
  41. // ---- the two ways in (ident README "How apps use ident") ---------------------------------
  42. static selectorScript = identUrl + '/selector.js'
  43. static callbackUrl = publicUrl + '/login/callback'
  44. static loginHref = identUrl + '/login?key=' + identKey + '&return=' + encode(callbackUrl)
  45. // an identity id as ident answers it: its public SHORT ID since ident#23 (5 characters like `a68sz`: 2-9 and a-z),
  46. // before that the old per-app id (32 hex) — lower case letters and digits, at most 64 (as gitoria's users.hl)
  47. static isIdentId = (s) => {
  48. if (s == null || hlTypeName(s) != 'String' || s.length == 0 || s.length > 64) { return false }
  49. let i = 0
  50. while (i < s.length) {
  51. let c = s.charCodeAt(i)
  52. if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 122))) { return false }
  53. i = i + 1
  54. }
  55. return true
  56. }
  57. // A FAILED FETCH (refused connection, timeout, TLS) is an `Error` event, not an answer: the
  58. // global `on Error` in project.hl absorbs it, the fetch then yields null → "ident did not answer"
  59. // (a 400 page / a message) instead of a 500 with source paths. (A handler in THIS file does not
  60. // catch it — mission 011.)
  61. // THE EXCHANGE: POST <ident>/api/exchange { key, secret, code } → { identity } | { error }
  62. static exchangeCode = (code) => {
  63. if (identKey == '' || identSecret == '') { return { error = 'login is not set up on this server (IDENT_API_KEY / IDENT_API_SECRET missing)' } }
  64. if (!isHex(code, 200)) { return { error = 'that is not an ident login code' } }
  65. r = fetch(identExchangeUrl + '/api/exchange', { method = 'POST' json = { key = identKey secret = identSecret code = code } headers = { 'user-agent' = 'tickets.worldapi.org (ident exchange)' } timeoutMs = 10000 })
  66. if (r == null || r.status == null || r.status == 0) { return { error = 'ident did not answer' } }
  67. j = r.status == 200 ? r.json() : null
  68. if (j == null || j.identity == null || !isIdentId(j.identity)) {
  69. let why = ''
  70. if (r.status != 200) {
  71. e = r.json()
  72. why = e != null && e.error != null ? ': ' + e.error : ''
  73. }
  74. return { error = 'ident refused the login (' + r.status + why + ')' }
  75. }
  76. return { identity = j.identity }
  77. }
  78. // ---- users ------------------------------------------------------------------------------
  79. static userRecord = (userId) => {
  80. if (userId == null || hlTypeName(userId) != 'String' || userId == '') { return null }
  81. return usersTable.fetch(userId)
  82. }
  83. // every user (projects.hl userByRef looks a person up among them)
  84. static userRecords = () => { return usersTable.find(null, null) }
  85. // the user of an identity id, or null
  86. static userOfIdentity = (identity) => { return first(usersTable.find('identity', identity)) }
  87. // the user of an identity id, made at its first login (name '' = not chosen yet)
  88. static ensureUser = (identity) => {
  89. u = userOfIdentity(identity)
  90. if (u != null) { return u }
  91. id = usersTable.put({ identity = identity name = '' created = now() })
  92. if (id == null) { return null }
  93. return usersTable.fetch(id)
  94. }
  95. // THE SITE CREATOR'S user record (TICKETS_CREATOR_IDENTITY), or null while they never logged in
  96. static creatorUser = () => {
  97. if (creatorIdentity == '') { return null }
  98. return userOfIdentity(creatorIdentity)
  99. }
  100. // the same, made if missing (migrate.hl: the creator is admin before their first login here)
  101. static ensureCreatorUser = () => {
  102. if (creatorIdentity == '') { return null }
  103. return ensureUser(creatorIdentity)
  104. }
  105. // what a page may know about a user: NEVER the identity id
  106. static userInfo = (u) => {
  107. return { name = u.name named = u.name != '' }
  108. }
  109. static userOfSession = (session) => {
  110. if (session == null || session.user == null) { return null }
  111. return userRecord(session.user.id)
  112. }
  113. static infoOfSession = (session) => {
  114. u = userOfSession(session)
  115. return u == null ? null : userInfo(u)
  116. }
  117. // may this session write (logged in AND a display name chosen)?
  118. static canWriteSession = (session) => {
  119. u = userOfSession(session)
  120. return u != null && u.name != ''
  121. }
  122. // THE WRITER of a web write: { user } or { error } (the message the page shows)
  123. static writerOfSession = (session) => {
  124. u = userOfSession(session)
  125. if (u == null) { return { error = 'log in with ident (top right) to write' } }
  126. if (u.name == '') { return { error = 'choose a display name first (top of the page)' } }
  127. return { user = u }
  128. }
  129. // the author a history shows for an event written by a user: the CURRENT display name
  130. static nameOfUser = (userId) => {
  131. u = userRecord(userId)
  132. if (u == null || u.name == '') { return 'someone' }
  133. return u.name
  134. }
  135. // the display name: 1–60 characters, one line. Asked ONCE (CONCEPT point 6): a name that is
  136. // set is not changed here (no rename UI — an open question for the creator)
  137. static setUserName = (userId, name) => {
  138. u = userRecord(userId)
  139. if (u == null) { return { error = 'not logged in' } }
  140. if (u.name != '') { return { error = 'your display name is already set' } }
  141. bad = plainError(name, 60, 'the display name')
  142. if (bad != null) { return { error = bad } }
  143. n = name.trim()
  144. if (n == '') { return { error = 'the display name must not be empty' } }
  145. // the whole record, its `id` included (hl:mpackdb refuses an @id record without it: CorruptRecord)
  146. usersTable.update(u.id, { id = u.id identity = u.identity name = n created = u.created })
  147. after = usersTable.fetch(u.id)
  148. if (after == null || after.name != n) { return { error = 'could not store the name: ' + usersTable.lastError() } }
  149. return { user = after }
  150. }
  151. // ---- API tokens ---------------------------------------------------------------------------
  152. static tokenRowOf = (t) => {
  153. return { id = t.id label = t.label != null && t.label != '' ? t.label : '(no label)' created = localStamp(t.created) createdMs = t.created }
  154. }
  155. // the user's tokens, newest first
  156. static tokenRows = (userId) => {
  157. out = []
  158. all = tokensTable.find('user', userId)
  159. if (countOf(all) == 0) { return out }
  160. for (t of all) { out.push(tokenRowOf(t)) }
  161. return newestFirst(out, 'createdMs')
  162. }
  163. // answers { token (shown ONCE), tokens } or { error }
  164. static createToken = (userId, label) => {
  165. bad = plainError(label == null ? '' : label, 60, 'the label')
  166. if (bad != null) { return { error = bad } }
  167. let token = 'tkt_' + randomBytes(24)
  168. id = tokensTable.put({ user = userId hash = sha256(token) label = (label == null ? '' : label.trim()) created = now() })
  169. if (id == null) { return { error = 'could not store the token: ' + tokensTable.lastError() } }
  170. return { token = token tokens = tokenRows(userId) }
  171. }
  172. // only the owner revokes; the row goes, the token is dead at once
  173. static revokeToken = (userId, tokenId) => {
  174. if (tokenId == null || hlTypeName(tokenId) != 'String' || tokenId == '') { return { error = 'no such token' } }
  175. t = tokensTable.fetch(tokenId)
  176. if (t == null || t.user != userId) { return { error = 'no such token' } }
  177. tokensTable.delete(t.id)
  178. return { tokens = tokenRows(userId) }
  179. }
  180. // `Authorization: Bearer <token>` → the user, or null (missing, malformed, unknown, revoked)
  181. static userOfBearer = (header) => {
  182. if (header == null || hlTypeName(header) != 'String') { return null }
  183. h = header.trim()
  184. if (!h.startsWith('Bearer ') && !h.startsWith('bearer ')) { return null }
  185. token = h.slice(7).trim()
  186. if (!token.startsWith('tkt_') || token.length != 52) { return null }
  187. t = first(tokensTable.find('hash', sha256(token)))
  188. if (t == null) { return null }
  189. return userRecord(t.user)
  190. }
  191. // ---- the /you page: the user's OWN data (the only place the identity id is shown) -----------
  192. static youOf = (session) => {
  193. u = userOfSession(session)
  194. if (u == null) { return null }
  195. return { name = u.name named = u.name != '' identity = u.identity tokens = tokenRows(u.id) }
  196. }
  197. // the random tag of a session's login (session.data.tag): project.hl's audience sends `signedIn` / `signedOut` to the
  198. // tabs of the session that carries it
  199. static tagOf = (session) => { return session != null && session.data != null ? session.data.tag : null }

Branches

Latest commits

  • f04afc43tickets: MdEditor from components 59704ce (a file manager copy still attaches, pipe rows, tickets#49)mre
  • 06599fa0tickets: MdEditor from components b0f1ec2 (a clipboard with text always pastes the text, tickets#49); real Ctrl+V gatemre
  • 2e1b116ftickets: re-vendor Hybriel master acaceaf3 (framework ec8d6c1d): plugins/web patch queue while a page is built, anonymous session cookies refresh; gate waits for the comment editors to draw (W174) and clicks the form editor when it stands still; security gate: main's code runs on its own binary, lazy-session cookie checksmre
  • 361bc0fetickets: re-vendor Hybriel 7a684920 (WIP, not deployed); on Error exits 1 at startup; migrate passes its log by reference; gate checks follow lazy sessions and the 413 refusalmre
  • 8a69999cident#28: /login/callback never signs out the session it finds; a valid code puts the user on the same sessionmre
  • 337e9b21tickets#37: a comment's files are open to everyone who can read the commentmre
  • 1800600ftickets: write the standby service out in full so the boot gate can read the main servicemre
  • 8179d287tickets: standby service on its port plus 10 and a deploy that hands over through it without a gapmre
  • 0398145ctickets: the table grid rule is marked functional for check-thememre
  • 40fddc20tickets takes components e54f83a: tables get thin grey lines from the theme, desktop toolbar stays one row with the Table button, F4 check counts 11 buttonsmre
  • c1b77d61tickets#35: text typed before the editor is built is taken in once by the build (the input handler no longer writes it to the field first, which doubled the first letters); the gate failure shows the surfacemre
  • 32bf1873tickets#35: the gate types right after the load with the CPU slowed, no waitingmre
  • 64ea9ca2tickets#35: text typed into the reply editor before the page has finished starting is kept; the gate types right after loadmre
  • ccd3a327tickets: the security gate expects frame-src to be exactly the ident address (the sign-in frame), still no wildcard or selfmre
  • 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