gitoriaLog in with ident

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit4a2d71254a2d7125initial commitmre4a2d7125/users.hl

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

Branches

Latest commits

  • 4a2d7125initial commitmre