gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit866397a0866397a0mission 023: theme from layouts 76f99f6 (current marker, menu count badge), components from 3794c59 (MdEditor keys); Inbox count as badge, current by address; gates and E2E; reportmre866397a0/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

  • 866397a0mission 023: theme from layouts 76f99f6 (current marker, menu count badge), components from 3794c59 (MdEditor keys); Inbox count as badge, current by address; gates and E2E; reportmre
  • 7ed2e5e5deploy.sh: a gate without a 'passed,' line (check-theme) no longer ends the script silently (grep under pipefail), as gitoria/layoutsmre
  • bf9064a3mission 022: tickets on the layouts theme (step 1): shell, styles, gates, audit, E2E; reportmre
  • f3d61711mission 022 WIP: tickets on the layouts theme (dbe3de7): AppHeader/MainMenu/UserMenu/Sidebar/ContentFirst shell, styles reduced to the app's own, check-theme in the gates, 390 audit + real-Chrome walk scriptmre
  • 31cabfccmission 021: E2E script, report, LOG, STATUSmre
  • 6aea8683editor look: .empty rule only for p.empty, files off where tickets has no upload, state note one line, events test scrolls the editor into view; synced md-editor (components d702d76+6f27ad3); gate 377/0, events 52/0mre
  • dce6ffa6Merge branch 'w28-deflake'mre
  • 536092a1tickets (mission 019): de-flake the m016 comment clicks (B: unliked) — calmClick waits until the button stops moving; test only, no app changemre
  • 9c5fd42amission 020: attachments E2E proof (lisbeth Chrome, real-data copy), reportmre
  • 1206404fREADME attachments, report 018, LOG/STATUSmre
  • 3d9e7f3ctests: m017 gate fixes (list count, waits before delete clicks); gate 373/0mre
  • dd41d5bcre-sync components 15be2ac; mission 018mre
  • 420ad1bbtickets (mission 017 WIP, tickets#27): comment attachments — lib/attachments.hl (storage/attachments, limits, type by content, members-only GET /api/attachments/:id, delete drops, edit keeps), multipart POST …/comments (lib/multipart.hl), Respond block in FilesUpload (blocks verbatim from components w27c 1f8d79d), gate m017 checks written (not yet run); report, LOG, STATUSmre
  • a7a1380dmission brief 017mre
  • f83d9c0dtickets (mission 016): report reports/016-comments-block.md, LOG, STATUS, README gate countmre
  • eef80f55tickets (mission 016): comments through the shared Comments block (layouts#2) — edit (author, earlier versions kept), delete (author, asks; leaves one line in the history), like (members, toggle) on the server (lib/comments.hl, append-only tables), faces + API …/comments/:comment/{edit,delete,like}, push commentChanged; every run of comments is a block in place in the history; Markdown fields on the Hybriel MdEditor (shared/md-editor.js retired: it took over the block's <md-editor>); blocks copied verbatim from components.hybriel 9db927d (tools/sync-components.sh); gates browser 351/0 (old 326/0), events 52/0 (old 52/0)mre
  • eb7aeeb9mission brief 016mre
  • e4c34759paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • 26efb23freport w6-events (events test)mre
  • c6bfab04mission 015: re-vendor Hybriel 0f396652 (static build), reportmre