gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit9af8e7809af8e780|||PR Use keyed list mutations for live ticket updatesmre9af8e780/lib/users.hl

11.8 KB

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

Branches

Latest commits

  • 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
  • b9fb9a91|||PR bind ticket dialog visibility to member flagsmre