gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit31dcf2ad31dcf2admission 045: report, LOGmre31dcf2ad/lib/users.hl

8.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. static identUrl = envOr('IDENT_URL', 'https://ident.worldapi.org')
  23. static identExchangeUrl = envOr('IDENT_EXCHANGE_URL', identUrl)
  24. static identKey = envOr('TRACKER_KEY', '')
  25. static identSecret = envOr('TRACKER_SECRET', '')
  26. static publicUrl = envOr('TRACKER_URL', 'https://tracker.worldapi.org')
  27. static usersTable = new MPackDB(file = storageDir + '/users.db', primaryKey = '@id', indexes = ['!identity'])
  28. static selectorScript = identUrl + '/selector.js'
  29. static callbackUrl = publicUrl.replaceAll('/', '') == '' ? '' : publicUrl + '/login/callback'
  30. static loginHref = identUrl + '/login?key=' + identKey + '&return=' + encodeURIComponent(callbackUrl)
  31. // only lowercase hex (ident's one-time codes are 48 hex)
  32. static isHex = (&s, &max) => {
  33. if (s == null || hlTypeName(s) != 'String' || s.length == 0 || s.length > max) { return false }
  34. let i = 0
  35. while (i < s.length) {
  36. let c = s.charCodeAt(i)
  37. if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 102))) { return false }
  38. i = i + 1
  39. }
  40. return true
  41. }
  42. // an identity id as ident answers it: its public SHORT ID since ident#23 (5 characters like `a68sz`: 2-9 and a-z),
  43. // before that the old per-app id (32 hex) — lower case letters and digits, at most 64
  44. static isIdentId = (&s) => {
  45. if (s == null || hlTypeName(s) != 'String' || s.length == 0 || s.length > 64) { return false }
  46. let i = 0
  47. while (i < s.length) {
  48. let c = s.charCodeAt(i)
  49. if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 122))) { return false }
  50. i = i + 1
  51. }
  52. return true
  53. }
  54. // THE EXCHANGE: POST <ident>/api/exchange { key, secret, code } → { identity } | { error }
  55. // (a failed fetch is an `Error` event, absorbed by project.hl's `on Error`; the fetch then yields null)
  56. static exchangeCode = (code) => {
  57. if (identKey == '' || identSecret == '') { return { error = 'login is not set up on this server (TRACKER_KEY / TRACKER_SECRET missing)' } }
  58. if (!isHex(code, 200)) { return { error = 'that is not an ident login code' } }
  59. r = fetch(identExchangeUrl + '/api/exchange', { method = 'POST' json = { key = identKey secret = identSecret code = code } headers = { 'user-agent' = 'tracker.worldapi.org (ident exchange)' } timeoutMs = 10000 })
  60. if (r == null || r.status == null || r.status == 0) { return { error = 'ident did not answer' } }
  61. j = r.status == 200 ? r.json() : null
  62. if (j == null || j.identity == null || !isIdentId(j.identity)) {
  63. let why = ''
  64. if (r.status != 200) {
  65. e = r.json()
  66. why = e != null && e.error != null ? ': ' + e.error : ''
  67. }
  68. return { error = 'ident refused the login (' + r.status + why + ')' }
  69. }
  70. return { identity = j.identity }
  71. }
  72. // ---- users --------------------------------------------------------------------------------
  73. // a face's trailing `session` is always the server's since hybriel #16 (a peer's extra argument is refused)
  74. static userRecord = (&userId) => {
  75. if (userId == null || hlTypeName(userId) != 'String' || userId == '') { return null }
  76. return usersTable.fetch(userId)
  77. }
  78. // the user of an identity id, made at its first login
  79. static ensureUser = (identity) => {
  80. u = firstOf(usersTable.find('identity', identity))
  81. if (u != null) { return u }
  82. id = usersTable.put({ identity = identity created = now() })
  83. if (id == null) { return null }
  84. return usersTable.fetch(id)
  85. }
  86. // an ident login code → this app's user (made at its first login): { user } or { error } — both ways in (the header's
  87. // selector, components/main.hl face trackerLogin; the button's return, loginCallbackOf below)
  88. static userOfCode = (code) => {
  89. x = exchangeCode(code)
  90. if (x.error != null) { return { error = x.error } }
  91. u = ensureUser(x.identity)
  92. if (u == null) { return { error = 'could not store the user' } }
  93. return { user = u }
  94. }
  95. static userOfSession = (&session) => {
  96. if (session == null || session.user == null) { return null }
  97. return userRecord(session.user.id)
  98. }
  99. // the users @id of a session, or null (a page may know it: it is not the identity id)
  100. static userIdOfSession = (&session) => {
  101. u = userOfSession(session)
  102. return u == null ? null : u.id
  103. }
  104. // ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident"), copied from calendar.worldapi.org's project.hl ---------
  105. // (mission 028: out of project.hl, whose route `/login/callback` calls `loginCallbackOf` with the server's sessions)
  106. // /login/callback?ident_code=<code> the app's server exchanges the code for the identity's short id
  107. // (POST <ident>/api/exchange) and signs this app's OWN session in
  108. // (session.user = { id = <users @id> }); the header's "Log out" signs it out again
  109. // (components/main.hl face trackerLogOut) — ident's own session is untouched
  110. // BACK TO THE PAGE: /login.js puts `?next=` into the button's return URL at the click. Only a same-origin PATH
  111. // goes (one `/`, URL-safe characters, ≤ 500). Anything else → `/`.
  112. static nextChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;@!$()*:'
  113. static safePath = (&want) => {
  114. if (want == null || hlTypeName(want) != 'String' || want == '' || want.length > 500) { return '/' }
  115. if (want.slice(0, 1) != '/' || want.slice(0, 2) == '//' || want.slice(0, 7) == '/login/') { return '/' }
  116. let i = 0
  117. while (i < want.length) {
  118. if (!nextChars.includes(want[i])) { return '/' }
  119. i = i + 1
  120. }
  121. return want
  122. }
  123. // A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked in the session, then → /login/failed
  124. static loginFailedOf = (&sessions, &req, why) => {
  125. let s = req.session
  126. fresh = s == null
  127. if (fresh) { s = sessions.mint() }
  128. s.data.loginError = why
  129. sessions.save(s)
  130. let res = new Response('login failed: ' + why, { status = 302 headers = { 'Location' = '/login/failed' 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })
  131. if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }
  132. return res
  133. }
  134. // the function route gets the cookie's session as req.session (hybriel #11); none yet → minted here. `sessions` = the
  135. // server's (hl:web `server.sessions`)
  136. static loginCallbackOf = (&sessions, &req) => {
  137. if (req.method != 'GET') { return loginFailedOf(sessions, req, 'GET only') }
  138. q = req.query != null ? req.query : {}
  139. code = q.ident_code
  140. if (code == null || code == '') { return loginFailedOf(sessions, req, 'ident sent no login code') }
  141. x = userOfCode(code)
  142. if (x.error != null) { return loginFailedOf(sessions, req, x.error) }
  143. u = x.user
  144. let s = req.session
  145. fresh = s == null
  146. if (fresh) { s = sessions.mint() }
  147. s.user = { id = u.id }
  148. s.data.tag = randomBytes(16)
  149. s.data.loginError = null
  150. sessions.save(s)
  151. let res = new Response('logged in', { status = 302 headers = { 'Location' = safePath(q.next) 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })
  152. if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }
  153. return res
  154. }

Branches

Latest commits

  • 31dcf2admission 045: report, LOGmre
  • 9c3971d0tests/persons-skip-count.hlmre
  • 4d72e365mission 045mre
  • b9cae4c9slices: skip and count non-row values from range(); merge persons pass falls back to iterate; guard testmre
  • 3db7dc31merge w44-jobs-slices into w43-trkmemmre
  • 593dab6fmission 043: report, LOGmre
  • 1a5a4818boot scans back to iterate (slices measured slower: titles 114 s, episodes 141 s, persons failed); lambda per rowmre
  • 03d29893boot scans read primary-key slices (lib/slices.hl from mission 044): iterate is eager too; people view log line back; allShows/allEpisodes stay for toolsmre
  • 23375c58mission 044: report, LOG, STATUSmre
  • c6fd928emission 044: 4096 slices for tables over 200 K rows, 15 ms budget, TRACKER_SLICE_DEPTH for testsmre
  • fb057680mission 044: jobs.hl imports mergeLeft (gate found it), mission file, slices benchmre
  • 0d6293ebmission 043: mission filemre
  • d25bd14amission 044: sliced merge prepare + sliced collections prepare; jobs-dump old/new check + bulk fixturemre
  • 633ee210mission 044: sliced table scans (slices.hl, pk-range slices) for the adult/kind/status/art/credits/details-repair queuesmre
  • 55bbd619boot: one streamed pass per table (lib/bootscan.hl) instead of find(null,null) per module; follows/watches/franchises scans streammre
  • 1d465d3ere-vendor plugins to Hybriel master f9614007 (mpackdb #202 copy fix, libmpackdb sha 6fb3b9d6)mre
  • 6648ba44mission 042: real-browser E2E on ce6f2e0a re-vendor 69/0 at 390 + 1280mre
  • 3ed3a0efmission 042: gates old/new equal (browser #41 route-table regex accepts unescaped hl:web output), real-data TTFB, E2E blocked by lisbeth lockmre
  • d5b61e90LOG 042mre
  • 4acdbaccmission 042: memory comparison old vs ce6f2e0a (stopped: warm VmHWM higher), reportmre