gitoriaLog in with ident

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit8bb97ffd8bb97ffddeploy.sh: never send .git or .gitignore to Byrodinmre8bb97ffd/users.hl

8.6 KB

  1. // 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 the main address, default https://gitoria.worldapi.org; repos live at
  19. // <scheme>://<slug>.<host[:port] of this url>
  20. // GITORIA_STORAGE table directory, default ./storage/mpackdb
  21. import { MPackDB } from 'hl:mpackdb'
  22. import { env } from 'hl:proc'
  23. import { now } from 'hl:time'
  24. import { fetch } from 'hl:fetch'
  25. static envOr = (name, fallback) => {
  26. let v = env(name)
  27. return v != null && v.trim() != '' ? v.trim() : fallback
  28. }
  29. static identUrl = envOr('IDENT_URL', 'https://ident.worldapi.org')
  30. static identExchangeUrl = envOr('IDENT_EXCHANGE_URL', identUrl)
  31. static identKey = envOr('IDENT_API_KEY', '')
  32. static identSecret = envOr('IDENT_API_SECRET', '')
  33. static publicUrl = envOr('GITORIA_PUBLIC_URL', 'https://gitoria.worldapi.org')
  34. static storageDir = envOr('GITORIA_STORAGE', './storage/mpackdb')
  35. static usersTable = new MPackDB(file = storageDir + '/users.db', primaryKey = '@id', indexes = ['!identity'])
  36. static countOfList = (list) => {
  37. if (list == null) { return 0 }
  38. let n = list.length
  39. return n == null ? 0 : n
  40. }
  41. static firstOf = (list) => { return countOfList(list) > 0 ? list[0] : null }
  42. // ---- the addresses: main = <scheme>://<hostport>, a repo = <scheme>://<slug>.<hostport> ---------
  43. static schemeEnd = publicUrl.indexOf('://')
  44. static scheme = publicUrl.slice(0, schemeEnd)
  45. static hostPort = publicUrl.slice(schemeEnd + 3).replaceAll('/', '')
  46. static hostOnly = hostPort.split(':')[0]
  47. static repoOrigin = (slug) => { return scheme + '://' + slug + '.' + hostPort }
  48. static selectorScript = identUrl + '/selector.js'
  49. static callbackUrl = publicUrl.replaceAll('/', '') == '' ? '' : scheme + '://' + hostPort + '/login/callback'
  50. static loginHref = identUrl + '/login?key=' + identKey + '&return=' + encodeURIComponent(callbackUrl)
  51. // only lowercase hex (ident's one-time codes are 48 hex)
  52. static isHex = (s, max) => {
  53. if (s == null || hlTypeName(s) != 'String' || s.length == 0 || s.length > max) { return false }
  54. let i = 0
  55. while (i < s.length) {
  56. let c = s.charCodeAt(i)
  57. if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 102))) { return false }
  58. i = i + 1
  59. }
  60. return true
  61. }
  62. // an identity id as ident answers it: its public SHORT ID since ident#23 (5 characters like `a68sz`: 2-9 and a-z),
  63. // before that the old per-app id (32 hex) — lower case letters and digits, at most 64 (mission 039; isHex refused `a68sz`)
  64. static isIdentId = (s) => {
  65. if (s == null || hlTypeName(s) != 'String' || s.length == 0 || s.length > 64) { return false }
  66. let i = 0
  67. while (i < s.length) {
  68. let c = s.charCodeAt(i)
  69. if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 122))) { return false }
  70. i = i + 1
  71. }
  72. return true
  73. }
  74. // THE EXCHANGE: POST <ident>/api/exchange { key, secret, code } → { identity } | { error }
  75. // (a failed fetch is an `Error` event, absorbed by project.hl's `on Error`; the fetch then yields null)
  76. static exchangeCode = (code) => {
  77. if (identKey == '' || identSecret == '') { return { error = 'login is not set up on this server (IDENT_API_KEY / IDENT_API_SECRET missing)' } }
  78. if (!isHex(code, 200)) { return { error = 'that is not an ident login code' } }
  79. let r = fetch(identExchangeUrl + '/api/exchange', { method = 'POST' json = { key = identKey secret = identSecret code = code } headers = { 'user-agent' = 'gitoria.worldapi.org (ident exchange)' } timeoutMs = 10000 })
  80. if (r == null || r.status == null || r.status == 0) { return { error = 'ident did not answer' } }
  81. let j = r.status == 200 ? r.json() : null
  82. if (j == null || j.identity == null || !isIdentId(j.identity)) {
  83. let why = ''
  84. if (r.status != 200) {
  85. let e = r.json()
  86. why = e != null && e.error != null ? ': ' + e.error : ''
  87. }
  88. return { error = 'ident refused the login (' + r.status + why + ')' }
  89. }
  90. return { identity = j.identity }
  91. }
  92. // the session cookie's Domain: every <slug>.<host> shares the login. A host without a dot (localhost) or
  93. // an IP address gets a host-only cookie. GITORIA_COOKIE_DOMAIN overrides ('-' = host-only).
  94. static domainFor = (h) => {
  95. let given = env('GITORIA_COOKIE_DOMAIN')
  96. if (given != null && given != '') { return given == '-' ? '' : given }
  97. if (!h.includes('.')) { return '' }
  98. let last = h.charCodeAt(h.length - 1)
  99. if (last >= 48 && last <= 57) { return '' }
  100. return '.' + h
  101. }
  102. // THE REPO OF A REQUEST HOST (gitoria#16): hl:web hands a page component that declares `host = null` the
  103. // request's Host without port (hybriel#74). '' = the main address (or any other host) → the repo list;
  104. // else the label before .<hostOnly> (a slug that fails slugError, e.g. x.y, is "No such repository").
  105. static slugOfHost = (h) => {
  106. if (h == null || hlTypeName(h) != 'String') { return '' }
  107. let x = h.toLowerCase()
  108. if (x == hostOnly) { return '' }
  109. let tail = '.' + hostOnly
  110. return x.endsWith(tail) ? x.slice(0, x.length - tail.length) : ''
  111. }
  112. // ---- users --------------------------------------------------------------------------------
  113. // a face's trailing `session` is always the server's since hybriel #16 (a peer's extra argument is refused)
  114. static userRecord = (userId) => {
  115. if (userId == null || hlTypeName(userId) != 'String' || userId == '') { return null }
  116. return usersTable.fetch(userId)
  117. }
  118. // the user of an identity id, made at its first login (name '' = not chosen yet)
  119. static ensureUser = (identity) => {
  120. let u = firstOf(usersTable.find('identity', identity))
  121. if (u != null) { return u }
  122. let id = usersTable.put({ identity = identity name = '' created = now() })
  123. if (id == null) { return null }
  124. return usersTable.fetch(id)
  125. }
  126. // what a page may know about a user: NEVER the identity id
  127. static userInfo = (u) => { return { name = u.name named = u.name != '' } }
  128. static userOfSession = (session) => {
  129. if (session == null || session.user == null) { return null }
  130. return userRecord(session.user.id)
  131. }
  132. static infoOfSession = (session) => {
  133. let u = userOfSession(session)
  134. return u == null ? null : userInfo(u)
  135. }
  136. // the display name of an owner, 'someone' for a user without one
  137. static nameOfUser = (userId) => {
  138. let u = userRecord(userId)
  139. if (u == null || u.name == '') { return 'someone' }
  140. return u.name
  141. }
  142. // a short one-line text: trimmed, at most `max` characters, no control characters → null or the complaint
  143. static plainError = (s, max, what) => {
  144. if (s == null || hlTypeName(s) != 'String') { return what + ' must be text' }
  145. let t = s.trim()
  146. if (t.length > max) { return what + ' is too long (at most ' + max + ' characters)' }
  147. let i = 0
  148. while (i < t.length) {
  149. let c = t.charCodeAt(i)
  150. if (c < 32 || c == 127) { return what + ' must be one line without control characters' }
  151. i = i + 1
  152. }
  153. return null
  154. }
  155. // the display name: 1–60 characters, one line, asked ONCE
  156. static setUserName = (userId, name) => {
  157. let u = userRecord(userId)
  158. if (u == null) { return { error = 'not logged in' } }
  159. if (u.name != '') { return { error = 'your display name is already set' } }
  160. let bad = plainError(name, 60, 'the display name')
  161. if (bad != null) { return { error = bad } }
  162. let n = name.trim()
  163. if (n == '') { return { error = 'the display name must not be empty' } }
  164. usersTable.update(u.id, { id = u.id identity = u.identity name = n created = u.created })
  165. let after = usersTable.fetch(u.id)
  166. if (after == null || after.name != n) { return { error = 'could not store the name: ' + usersTable.lastError() } }
  167. return { user = after }
  168. }

Branches

Latest commits

  • 8bb97ffddeploy.sh: never send .git or .gitignore to Byrodinmre
  • fd981932State of 2026-09-27; bin/ no longer tracked (Hybriel commit is in README)mre
  • 4a2d7125initial commitmre