gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitb3d8a80bb3d8a80bDP69 brief, RV48 mergedmreb3d8a80b/lib/users.hl

9.2 KB

  1. // lib/users.hl — WHO IS SIGNED IN (tracker.worldapi.org#1; copied from calendar.worldapi.org's users.hl unchanged in
  2. // shape, per the architect: "Copy calendar.worldapi.org's login unchanged"). Login is ident's LOGIN BUTTON flow
  3. // (ident README "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, sits beside the
  5. // button (login.js hands its code to the shell).
  6. //
  7. // usersTable pk @id index !identity { identity, created } storage/mpackdb/users.db
  8. // identity = what ident's exchange answers: the identity's public SHORT id (ident#23, `a68sz`) — stays SERVER
  9. // SIDE, never sent to a page.
  10. // The session (hl:web) carries `user = { id = <users @id> }` only. No display name: nothing else is stored.
  11. //
  12. // Config (environment, or `.env` beside project.hl — never read or printed by workers):
  13. // IDENT_URL, IDENT_EXCHANGE_URL, TRACKER_KEY, TRACKER_SECRET as calendar's IDENT_API_KEY/IDENT_API_SECRET
  14. // TRACKER_URL the app's own address, default https://tracker.worldapi.org
  15. // TRACKER_STORAGE table directory, default ./storage/mpackdb
  16. import { MPackDB } from 'hl:mpackdb'
  17. import { Response } from 'hl:http1'
  18. import { randomBytes } from 'hl:crypto'
  19. import { now } from 'hl:time'
  20. import { fetch } from 'hl:fetch'
  21. import { envOr, storageDir, firstOf } from './util.hl'
  22. import { allowHit, clientKey } from './security.hl'
  23. static identUrl = envOr('IDENT_URL', 'https://ident.worldapi.org')
  24. static identExchangeUrl = envOr('IDENT_EXCHANGE_URL', &identUrl)
  25. static identKey = envOr('TRACKER_KEY', '')
  26. static identSecret = envOr('TRACKER_SECRET', '')
  27. static publicUrl = envOr('TRACKER_URL', 'https://tracker.worldapi.org')
  28. // login tries per caller address and minute (the callback; the header selector's face limits per session): TRACKER_LOGIN_PER_MINUTE
  29. static loginPerMinute = toNumber(envOr('TRACKER_LOGIN_PER_MINUTE', '20'))
  30. static usersTable = new MPackDB(file = storageDir + '/users.db', primaryKey = '@id', indexes = ['!identity'])
  31. static selectorScript = identUrl + '/selector.js'
  32. static callbackUrl = publicUrl.replaceAll('/', '') == '' ? '' : publicUrl + '/login/callback'
  33. static loginHref = identUrl + '/login?key=' + identKey + '&return=' + encodeURIComponent(callbackUrl)
  34. // only lowercase hex (ident's one-time codes are 48 hex)
  35. static isHex = (&s, &max) => {
  36. if (s == null || hlTypeName(s) != 'String' || s.length == 0 || s.length > max) { return false }
  37. let i = 0
  38. while (i < s.length) {
  39. c = s.charCodeAt(i)
  40. if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 102))) { return false }
  41. i = i + 1
  42. }
  43. return true
  44. }
  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
  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. 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. // THE EXCHANGE: POST <ident>/api/exchange { key, secret, code } → { identity } | { error }
  58. // (a failed fetch is an `Error` event, absorbed by project.hl's `on Error`; the fetch then yields null)
  59. static exchangeCode = (code) => {
  60. if (identKey == '' || identSecret == '') { return { error = 'login is not set up on this server (TRACKER_KEY / TRACKER_SECRET missing)' } }
  61. if (!isHex(&code, 200)) { return { error = 'that is not an ident login code' } }
  62. r = fetch(identExchangeUrl + '/api/exchange', { method = 'POST' json = { key = identKey secret = identSecret code = code } headers = { 'user-agent' = 'tracker.worldapi.org (ident exchange)' } timeoutMs = 10000 })
  63. if (r == null || r.status == null || r.status == 0) { return { error = 'ident did not answer' } }
  64. j = r.status == 200 ? r.json() : null
  65. if (j == null || j.identity == null || !isIdentId(&j.identity)) {
  66. let why = ''
  67. if (r.status != 200) {
  68. e = r.json()
  69. why = e != null && e.error != null ? ': ' + e.error : ''
  70. }
  71. return { error = 'ident refused the login (' + r.status + why + ')' }
  72. }
  73. return { identity = j.identity }
  74. }
  75. // ---- users --------------------------------------------------------------------------------
  76. // a face's trailing `session` is always the server's since hybriel #16 (a peer's extra argument is refused)
  77. static userRecord = (&userId) => {
  78. if (userId == null || hlTypeName(userId) != 'String' || userId == '') { return null }
  79. return usersTable.fetch(userId)
  80. }
  81. // the user of an identity id, made at its first login
  82. static ensureUser = (identity) => {
  83. u = firstOf(usersTable.find('identity', identity))
  84. if (u != null) { return u }
  85. id = usersTable.put({ identity = identity created = now() })
  86. if (id == null) { return null }
  87. return usersTable.fetch(id)
  88. }
  89. // an ident login code → this app's user (made at its first login): { user } or { error } — both ways in (the header's
  90. // selector, components/main.hl face trackerLogin; the button's return, loginCallbackOf below)
  91. static userOfCode = (code) => {
  92. x = exchangeCode(code)
  93. if (x.error != null) { return { error = x.error } }
  94. u = ensureUser(x.identity)
  95. if (u == null) { return { error = 'could not store the user' } }
  96. return { user = u }
  97. }
  98. static userOfSession = (&session) => {
  99. if (session == null || session.user == null) { return null }
  100. return userRecord(&session.user.id)
  101. }
  102. // the users @id of a session, or null (a page may know it: it is not the identity id)
  103. static userIdOfSession = (&session) => {
  104. u = userOfSession(&session)
  105. return u == null ? null : u.id
  106. }
  107. // ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident"), copied from calendar.worldapi.org's project.hl ---------
  108. // (mission 028: out of project.hl, whose route `/login/callback` calls `loginCallbackOf` with the server's sessions)
  109. // /login/callback?ident_code=<code> the app's server exchanges the code for the identity's short id
  110. // (POST <ident>/api/exchange) and signs this app's OWN session in
  111. // (session.user = { id = <users @id> }); the header's "Log out" signs it out again
  112. // (components/main.hl face trackerLogOut) — ident's own session is untouched
  113. // BACK TO THE PAGE: /login.js puts `?next=` into the button's return URL at the click. Only a same-origin PATH
  114. // goes (one `/`, URL-safe characters, ≤ 500). Anything else → `/`.
  115. static nextChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;@!$()*:'
  116. static safePath = (&want) => {
  117. if (want == null || hlTypeName(want) != 'String' || want == '' || want.length > 500) { return '/' }
  118. if (want.slice(0, 1) != '/' || want.slice(0, 2) == '//' || want.slice(0, 7) == '/login/') { return '/' }
  119. let i = 0
  120. while (i < want.length) {
  121. if (!nextChars.includes(want[i])) { return '/' }
  122. i = i + 1
  123. }
  124. return want
  125. }
  126. // A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked in the session, then → /login/failed
  127. static loginFailedOf = (&sessions, &req, why, https) => {
  128. let s = req.session
  129. fresh = s == null
  130. if (fresh) { s = sessions.mint() }
  131. s.data.loginError = why
  132. sessions.save(s)
  133. res = new Response('login failed: ' + why, { status = 302 headers = { 'Location' = '/login/failed' 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' } })
  134. if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id, https) }
  135. return res
  136. }
  137. // the function route gets the cookie's session as req.session (hybriel #11); none yet → minted here. `sessions` = the
  138. // server's (hl:web `server.sessions`)
  139. static loginCallbackOf = (&sessions, &req, https) => {
  140. if (req.method != 'GET') { return loginFailedOf(&sessions, &req, 'GET only', https) }
  141. q = req.query != null ? req.query : {}
  142. code = q.ident_code
  143. if (code == null || code == '') { return loginFailedOf(&sessions, &req, 'ident sent no login code', https) }
  144. // mission SK: every try is an exchange request to ident — at most `loginPerMinute` per caller address
  145. if (!allowHit('login', clientKey(&req), &loginPerMinute, 60000)) { return loginFailedOf(&sessions, &req, 'too many login attempts — wait a minute', https) }
  146. x = userOfCode(code)
  147. if (x.error != null) { return loginFailedOf(&sessions, &req, x.error, https) }
  148. u = x.user
  149. // mission SK: a NEW session at every login (session fixation: a session id planted in the browser before the login must not be
  150. // the one that is signed in). The cookie of the old one is overwritten below.
  151. s = sessions.mint()
  152. fresh = true
  153. s.user = { id = u.id }
  154. s.data.tag = randomBytes(16)
  155. s.data.loginError = null
  156. sessions.save(s)
  157. res = new Response('logged in', { status = 302 headers = { 'Location' = safePath(&q.next) 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' } })
  158. if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id, https) }
  159. return res
  160. }
  161. static tagOf = (&session) => { return session != null && session.data != null ? session.data.tag : null }
  162. static sessionAudience = (tag, &session) => { return tag != null && tagOf(&session) == tag }

Branches

Latest commits

  • b3d8a80bDP69 brief, RV48 mergedmre
  • ce6d7d32Merge rv48: Hybriel day48mre
  • 3da2ea86RV48: report day48 cold starts, gates and cleanupmre
  • 8d9ecdfeRV48: re-vendor Hybriel set day48 (source b6a8f429, bin 660a9524)mre
  • 4a802ae7status: RV48 runningmre
  • 0a5412b6RV48 brief, day48 outmre
  • 56665efelog: CB69 mergedmre
  • 05448a98Merge cb69-imports: appTitle in a dependency-free topicmre
  • e55b379dKeep shared app title independent of the route import graphmre
  • 9a99659blog: hybriel#334, batch waits for day48mre
  • 85fa6c9blog: CB68 result, CB69 startedmre
  • 2f07c1b7log: DP68 boot gate failed, CB68mre
  • 9652782dlog: HM59 merged, DP68 startedmre
  • 29867a75Merge hm59-logic: tracker#59 page logic moved to libmre
  • f7bfe90bMove remaining page builders into their topicsmre
  • 7c3991f9log: day46 from Antonmre
  • ec54fc35Move show page logic into the shows topicmre
  • c1a8d074log: correct timesmre
  • 5827eba9log: HM57 merged, HM59 startedmre
  • d1a91be9Merge hm57-let: tracker#57 let only for reassigned namesmre