gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit09780f4e09780f4emission 040 WIP: theme, modal, pagination, tokens re-copied from layouts 76f99f6; tilelist uses onPage; tap sizes 44 px for tracker's own small buttons; tests/e2e-theme.mjsmre09780f4e/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

  • 09780f4emission 040 WIP: theme, modal, pagination, tokens re-copied from layouts 76f99f6; tilelist uses onPage; tap sizes 44 px for tracker's own small buttons; tests/e2e-theme.mjsmre
  • fb80bb8chotfix: open the 5 show stores without compaction (compact = false) — compact-on-open left another handle on stale offsets, every read gave a bare Number (hybriel mpackdb refresh after a shrink); live down 2026-10-20 05:11mre
  • e00d3bf7paths: projects moved into /media/STORAGE/projects/WorldAPI/mre
  • a8c7f234tracker#36 (mission 039): tools/tmdb-check.hl survives a dropped connection (on Error, asked again, failed lines) and resumes with --from N; tests/tmdbcheck.mjs 6/6 against a fake TMDBmre
  • 9c230516mission brief w39mre
  • 3609121dmission 038 docs + report (quota stop): README/kinds.md for #43 #42 #36, STATUS, LOG; HEAD browser gate 374/8 in the in-app daily run block (hour-boundary suspected, rerun pending), other gates green; #36 real run needs TMDB_READ_TOKENmre
  • a5d06e79tracker#36 (mission 038): tools/tmdb-check.hl + lib/tmdbcheck.hl — every live migrated title's migrated title + year against its TMDB entry (one GET /movie|tv/<id>?append_to_response=alternative_titles, 260 ms apart, passing failures asked once more): ok / ambiguous (one of title, year disagrees) / clear (both, or 404); read-only; token only from TMDB_READ_TOKEN; --stored = a title-only preview from the TMDB names already stored (no request). Tested against a fake TMDB (.scratch/w38/t36): 7 titles, 3 ok, 2 ambiguous, 2 clear, data unchangedmre
  • 982554f3tracker#42 (mission 038): series pages — an unknown slug no longer scans every title (lib/shows.hl showBySlug: the slug map only; new titles are noted by refreshTitleCaches, which both title puts already reach): 10.7–15.7 s → 0.013 s on the real copy (the one-request-at-a-time server was blocked meanwhile); cast/crew rows take name + slug from a person-link cache (personLinkOf) instead of whole person records (SNL: 303 cast with 4,761 credits, ~49k allocations per render) — allocations per series page −5…−40 %; HTML of 20 pages identical to beforemre
  • 4586b6e3docker-compose: init: true (hybriel#156)mre
  • 085c2e5ftracker#43 (mission 038): TVmaze's type makes Variety / Talk Show / Game Show / Reality / News / Panel Show / Award Show / Sports titles Shows (TMDB calls Saturday Night Live UK Scripted) — the #43 part of parked w37-wip a79c8c1 only (no re-vendor, no cache volume): tvmazeType stored by the sync and the TVmaze status backfill (asks every series with a TVmaze id once), kindOfTitle/kindWithTvmaze, tools/tvmaze-types.hl, gate fixture Variety Gate Series; start waits 150 smre
  • 4fa303b5mission brief w38mre
  • 975f6843tracker#41 (mission 037b): no request tap — an old /movies|/series slug renders the keeper's page (slug map) with og:url naming the keeper's address, /shows/ 301; no moved slug in any page's HTML. Real copy 168/168 old addresses, 0 moved slugs in 54 pages, 300x + 1000x stress without a crash; gates on 06617221 380/0, 32/0, 53/0, 229/0, 26/0, theme 0mre
  • 6decff4ftracker#41 (mission 037): moved slugs no longer listed in every page's HTML — a request tap answers their 301 by a slug-map lookup (shows.hl movedTitlePath); catalog.hl buildIndex pushes genre lists in place (the quadratic copy hung the boot > 20 min on today's data); gate: no moved slug in 19 page kinds signed out/in, immediate 301 after a merge. Gates on hybriel 06617221 green (380/0, 32/0, 53/0, 229/0, 26/0, theme 0); real copy 84/84 301, 0 moved slugs in 54 pages. NOT deployable: the tap faults after ~38 answers on 06617221 (report 037).mre
  • 35f7a872mission brief 037mre
  • 5cbcddd7tracker mission 036: recheck of the 16 review tickets — 15 WORKS, #39 PARTLY; review packages + bugs in reports/036-review-recheck.md (no code change)mre
  • 9e18c2d0mission brief (w36)mre
  • 216fac57missions 028-035 + reports 033/034 (were untracked)mre
  • 5cb85d75deploy.sh: a backup taken while a background job writes (tar exit 1) is a warning; archive checked with gzip -tmre
  • 9abda75dtracker: report 035mre
  • 12595e47mission 035: theme re-vendored from layouts.worldapi.org 0222f67 (two corner radii: radiusSmall 5px, radiusLarge 10px); the tracker's 18 own radii -> radiusSmall/radiusLarge (--layout-radius is gone); check-theme 0; gates 379/0, 32/0, 53/0, 229/0, 26/0; real copy: every computed radius in {0, 5px, 10px, 50%}mre