gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit4a3f557e4a3f557eImport layouts theme ebd00b6 for W61 (startup blocked)mre4a3f557e/lib/users.hl

8.4 KB

  1. // lib/users.hl — WHO MAY CREATE (ticket gitoria#6; CONCEPT.md "login via ident"). Reading is public;
  2. // creating a repo needs a login through ident. Login is ident's LOGIN BUTTON flow (ident README
  3. // "How apps use ident", way 2): <ident>/login?key=&return=<public url>/login/callback → ?ident_code=
  4. // → the server exchanges it (key + secret) for the per-app identity id. Way 3, the IDENTITY SELECTOR
  5. // (gitoria#14, ident README "The identity selector"), sits beside the button; ident checks its caller's origin
  6. // against the app's registered origins, and a repo address (<slug>.<domain>) is not one — so the selector shows
  7. // on the main address only (login.js) and the button works from every address (it returns through the main one).
  8. //
  9. // usersTable pk @id index !identity { identity, name, created } storage/mpackdb/users.db
  10. // identity = what ident's exchange answers: the identity's public SHORT id since ident#23 (`a68sz`; old 32-hex per-app
  11. // ids are rewritten once by tools/migrate-short-ids.hl) — stays SERVER SIDE, never sent to a page.
  12. // name = the display name asked once at the first login ('' until chosen); it is what
  13. // a repo shows as its owner.
  14. // The session (hl:web) carries `user = { id = <users @id> }` only.
  15. //
  16. // Config (environment, or `.env` beside project.hl — never read or printed by workers):
  17. // IDENT_URL, IDENT_EXCHANGE_URL, IDENT_API_KEY, IDENT_API_SECRET as in tickets
  18. // (GITORIA_PUBLIC_URL and GITORIA_STORAGE: lib/util.hl)
  19. import { randomBytes } from 'hl:crypto'
  20. import { MPackDB } from 'hl:mpackdb'
  21. import { now } from 'hl:time'
  22. import { fetch } from 'hl:fetch'
  23. import { envOr, storageDir, publicUrl, scheme, hostPort, firstOf, plainError, isHex } from './util.hl'
  24. static identUrl = envOr('IDENT_URL', 'https://ident.worldapi.org')
  25. static identExchangeUrl = envOr('IDENT_EXCHANGE_URL', identUrl)
  26. static identKey = envOr('IDENT_API_KEY', '')
  27. static identSecret = envOr('IDENT_API_SECRET', '')
  28. static usersTable = new MPackDB(file = storageDir + '/users.db', primaryKey = '@id', indexes = ['!identity'])
  29. static selectorScript = identUrl + '/selector.js'
  30. static callbackUrl = publicUrl.replaceAll('/', '') == '' ? '' : scheme + '://' + hostPort + '/login/callback'
  31. static loginHref = identUrl + '/login?key=' + identKey + '&return=' + encodeURIComponent(callbackUrl)
  32. // an identity id as ident answers it: its public SHORT ID since ident#23 (5 characters like `a68sz`: 2-9 and a-z),
  33. // before that the old per-app id (32 hex) — lower case letters and digits, at most 64 (mission 039; isHex refused `a68sz`)
  34. static isIdentId = (s) => {
  35. if (s == null || hlTypeName(s) != 'String' || s.length == 0 || s.length > 64) { return false }
  36. let i = 0
  37. while (i < s.length) {
  38. c = s.charCodeAt(i)
  39. if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 122))) { return false }
  40. i = i + 1
  41. }
  42. return true
  43. }
  44. // THE EXCHANGE: POST <ident>/api/exchange { key, secret, code } → { identity } | { error }
  45. // (a failed fetch is an `Error` event, absorbed by project.hl's `on Error`; the fetch then yields null)
  46. static exchangeCode = (code) => {
  47. if (identKey == '' || identSecret == '') { return { error = 'login is not set up on this server (IDENT_API_KEY / IDENT_API_SECRET missing)' } }
  48. if (!isHex(code, 200)) { return { error = 'that is not an ident login code' } }
  49. r = fetch(identExchangeUrl + '/api/exchange', { method = 'POST' json = { key = identKey secret = identSecret code = code } headers = { 'user-agent' = 'gitoria.worldapi.org (ident exchange)' } timeoutMs = 10000 })
  50. if (r == null || r.status == null || r.status == 0) { return { error = 'ident did not answer' } }
  51. j = r.status == 200 ? r.json() : null
  52. if (j == null || j.identity == null || !isIdentId(j.identity)) {
  53. let why = ''
  54. if (r.status != 200) {
  55. e = r.json()
  56. why = e != null && e.error != null ? ': ' + e.error : ''
  57. }
  58. return { error = 'ident refused the login (' + r.status + why + ')' }
  59. }
  60. return { identity = j.identity }
  61. }
  62. // ---- users --------------------------------------------------------------------------------
  63. // a face's trailing `session` is always the server's since hybriel #16 (a peer's extra argument is refused)
  64. static userRecord = (userId) => {
  65. if (userId == null || hlTypeName(userId) != 'String' || userId == '') { return null }
  66. return usersTable.fetch(userId)
  67. }
  68. // the user of an identity id, made at its first login (name '' = not chosen yet)
  69. static ensureUser = (identity) => {
  70. u = firstOf(usersTable.find('identity', identity))
  71. if (u != null) { return u }
  72. id = usersTable.put({ identity = identity name = '' created = now() })
  73. if (id == null) { return null }
  74. return usersTable.fetch(id)
  75. }
  76. // what a page may know about a user: NEVER the identity id
  77. static userInfo = (u) => { return { name = u.name named = u.name != '' } }
  78. static userOfSession = (session) => {
  79. if (session == null || session.user == null) { return null }
  80. return userRecord(session.user.id)
  81. }
  82. // the users @id of a session's user, or null — for a page that must NOT carry the whole record (it holds the ident identity, which
  83. // never goes to a page: a page's values are sent to the browser, mission SG)
  84. static userIdOfSession = (session) => {
  85. u = userOfSession(session)
  86. return u == null ? null : u.id
  87. }
  88. static infoOfSession = (session) => {
  89. u = userOfSession(session)
  90. return u == null ? null : userInfo(u)
  91. }
  92. // the display name of an owner, 'someone' for a user without one
  93. static nameOfUser = (userId) => {
  94. u = userRecord(userId)
  95. if (u == null || u.name == '') { return 'someone' }
  96. return u.name
  97. }
  98. // the display name: 1–60 characters, one line, asked ONCE
  99. static setUserName = (userId, name) => {
  100. u = userRecord(userId)
  101. if (u == null) { return { error = 'not logged in' } }
  102. if (u.name != '') { return { error = 'your display name is already set' } }
  103. bad = plainError(name, 60, 'the display name')
  104. if (bad != null) { return { error = bad } }
  105. n = name.trim()
  106. if (n == '') { return { error = 'the display name must not be empty' } }
  107. usersTable.update(u.id, { id = u.id identity = u.identity name = n created = u.created })
  108. after = usersTable.fetch(u.id)
  109. if (after == null || after.name != n) { return { error = 'could not store the name: ' + usersTable.lastError() } }
  110. return { user = after }
  111. }
  112. // A LOGIN (the login button's return, lib/api.hl loginCallback, and the selector's face gitoriaLogin, components/main.hl):
  113. // ident's one-time code → { user } (made at the first login) or { error }. The caller puts the user into the session.
  114. static userOfLoginCode = (code) => {
  115. x = exchangeCode(code)
  116. if (x.error != null) { return { error = x.error } }
  117. u = ensureUser(x.identity)
  118. if (u == null) { return { error = 'could not store the user' } }
  119. return { user = u }
  120. }
  121. // the random tag of a session's login (session.data.tag, set at login): `gitoriaSignedIn` / `gitoriaSignedOut` reach the
  122. // tabs of the session that carries it (project.hl audience)
  123. static tagOf = (session) => { return session != null && session.data != null ? session.data.tag : null }
  124. // the users @ids with exactly this display name (member lists add people by name)
  125. static usersByName = (name) => {
  126. out = []
  127. if (name == null || name == '') { return out }
  128. all = usersTable.find(null, null)
  129. if (all == null || all.length == null) { return out }
  130. for (u of all) { if (u.name == name) { out.push(u.id) } }
  131. return out
  132. }
  133. // A repository API member names a display name or an ident public short id.
  134. // Ambiguous display names are refused, just like the web member form.
  135. static userForMember = (name) => {
  136. if (name == null || hlTypeName(name) != 'String' || name.trim() == '') { return null }
  137. n = name.trim()
  138. ids = usersByName(n)
  139. if (ids.length == 1) { return ids[0] }
  140. if (ids.length > 1) { return null }
  141. u = firstOf(usersTable.find('identity', n))
  142. return u == null ? null : u.id
  143. }
  144. // Both login carriers keep the same session (ident#28): an open tab may not adopt a new cookie.
  145. // The callback supplies the session store to mint/save; the face supplies its framework-owned session.
  146. static login = (code, session, &sessions) => {
  147. x = userOfLoginCode(code)
  148. if (x.error != null) { return { error = x.error } }
  149. let s = session
  150. if (s == null) { s = sessions.mint() }
  151. tag = randomBytes(16)
  152. s.user = { id = x.user.id }
  153. s.data.tag = tag
  154. if (sessions != null) {
  155. s.data.loginError = null
  156. sessions.save(s)
  157. }
  158. return { session = s tag = tag info = userInfo(x.user) }
  159. }
  160. static failedLogin = (why, session, &sessions) => {
  161. let s = session
  162. if (s == null) { s = sessions.mint() }
  163. s.data.loginError = why
  164. sessions.save(s)
  165. return s
  166. }

Branches

Latest commits

  • 4a3f557eImport layouts theme ebd00b6 for W61 (startup blocked)mre
  • 53ca42b2log: W60 merged, W61 W62 startedmre
  • 80870a33mission W61: style passmre
  • 560fd208Merge W60: helpers, bound forms, login in topics, two form fixes (gitoria#28 #32 #33)mre
  • ac5ba6a4log: W60, #25 measuredmre
  • 220f6342W60: record corrected form proof, full AE and remaining gapsmre
  • 7e31cac5gitoria#28: restrict reply form layout to reply formsmre
  • ae373cfdgitoria#28: keep each reply draft in its thread componentmre
  • eeeebd5agitoria: insert a newly created organization oncemre
  • 34d2d5cagitoria: clear the bound public-key textarea after creationmre
  • 119e54c0W60: restore conductor-owned tracking filesmre
  • 24b479e7W60: record final gates, Chrome failures and AE evidencemre
  • 5e11184cW60: record partial validation, framework gaps and cleanupmre
  • 20fe13fagitoria#33: centralize login and tickets connection statemre
  • 859754c0gitoria#29: retain the offline note and record the framework gapmre
  • d140bc04gitoria#30: reproduce the upsert ordering constraintmre
  • 6960e8f8gitoria#28: keep form values in bound component membersmre
  • 0db27200gitoria#32: share character checks and environment lookupmre
  • 452f6a1amission W60: logic clean-upsmre
  • 1448c899log: cleanup, #49 GPTBot, tracker mentions on #36mre