tracker
All repositories: gitoria
8.9 KB
// lib/users.hl — WHO IS SIGNED IN (tracker.worldapi.org#1; copied from calendar.worldapi.org's users.hl unchanged in// shape, per the architect: "Copy calendar.worldapi.org's login unchanged"). Login is ident's LOGIN BUTTON flow// (ident README "How apps use ident", way 2): <ident>/login?key=&return=<public url>/login/callback → ?ident_code=// → the server exchanges it (key + secret) for the per-app identity id. Way 3, the IDENTITY SELECTOR, sits beside the// button (login.js hands its code to the shell).//// usersTable pk @id index !identity { identity, created } storage/mpackdb/users.db// identity = what ident's exchange answers: the identity's public SHORT id (ident#23, `a68sz`) — stays SERVER// SIDE, never sent to a page.// The session (hl:web) carries `user = { id = <users @id> }` only. No display name: nothing else is stored.//// Config (environment, or `.env` beside project.hl — never read or printed by workers):// IDENT_URL, IDENT_EXCHANGE_URL, TRACKER_KEY, TRACKER_SECRET as calendar's IDENT_API_KEY/IDENT_API_SECRET// TRACKER_URL the app's own address, default https://tracker.worldapi.org// TRACKER_STORAGE table directory, default ./storage/mpackdbimport { MPackDB } from 'hl:mpackdb'import { Response } from 'hl:http1'import { randomBytes } from 'hl:crypto'import { now } from 'hl:time'import { fetch } from 'hl:fetch'import { envOr, storageDir, firstOf } from './util.hl'import { allowHit, clientKey } from './security.hl'static identUrl = envOr('IDENT_URL', 'https://ident.worldapi.org')static identExchangeUrl = envOr('IDENT_EXCHANGE_URL', identUrl)static identKey = envOr('TRACKER_KEY', '')static identSecret = envOr('TRACKER_SECRET', '')static publicUrl = envOr('TRACKER_URL', 'https://tracker.worldapi.org')// login tries per caller address and minute (the callback; the header selector's face limits per session): TRACKER_LOGIN_PER_MINUTEstatic loginPerMinute = toNumber(envOr('TRACKER_LOGIN_PER_MINUTE', '20'))static usersTable = new MPackDB(file = storageDir + '/users.db', primaryKey = '@id', indexes = ['!identity'])static selectorScript = identUrl + '/selector.js'static callbackUrl = publicUrl.replaceAll('/', '') == '' ? '' : publicUrl + '/login/callback'static loginHref = identUrl + '/login?key=' + identKey + '&return=' + encodeURIComponent(callbackUrl)// only lowercase hex (ident's one-time codes are 48 hex)static isHex = (&s, &max) => {if (s == null || hlTypeName(s) != 'String' || s.length == 0 || s.length > max) { return false }let i = 0while (i < s.length) {let c = s.charCodeAt(i)if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 102))) { return false }i = i + 1}return true}// an identity id as ident answers it: its public SHORT ID since ident#23 (5 characters like `a68sz`: 2-9 and a-z),// before that the old per-app id (32 hex) — lower case letters and digits, at most 64static isIdentId = (&s) => {if (s == null || hlTypeName(s) != 'String' || s.length == 0 || s.length > 64) { return false }let i = 0while (i < s.length) {let c = s.charCodeAt(i)if (!((c >= 48 && c <= 57) || (c >= 97 && c <= 122))) { return false }i = i + 1}return true}// THE EXCHANGE: POST <ident>/api/exchange { key, secret, code } → { identity } | { error }// (a failed fetch is an `Error` event, absorbed by project.hl's `on Error`; the fetch then yields null)static exchangeCode = (code) => {if (identKey == '' || identSecret == '') { return { error = 'login is not set up on this server (TRACKER_KEY / TRACKER_SECRET missing)' } }if (!isHex(code, 200)) { return { error = 'that is not an ident login code' } }r = fetch(identExchangeUrl + '/api/exchange', { method = 'POST' json = { key = identKey secret = identSecret code = code } headers = { 'user-agent' = 'tracker.worldapi.org (ident exchange)' } timeoutMs = 10000 })if (r == null || r.status == null || r.status == 0) { return { error = 'ident did not answer' } }j = r.status == 200 ? r.json() : nullif (j == null || j.identity == null || !isIdentId(j.identity)) {let why = ''if (r.status != 200) {e = r.json()why = e != null && e.error != null ? ': ' + e.error : ''}return { error = 'ident refused the login (' + r.status + why + ')' }}return { identity = j.identity }}// ---- users --------------------------------------------------------------------------------// a face's trailing `session` is always the server's since hybriel #16 (a peer's extra argument is refused)static userRecord = (&userId) => {if (userId == null || hlTypeName(userId) != 'String' || userId == '') { return null }return usersTable.fetch(userId)}// the user of an identity id, made at its first loginstatic ensureUser = (identity) => {u = firstOf(usersTable.find('identity', identity))if (u != null) { return u }id = usersTable.put({ identity = identity created = now() })if (id == null) { return null }return usersTable.fetch(id)}// an ident login code → this app's user (made at its first login): { user } or { error } — both ways in (the header's// selector, components/main.hl face trackerLogin; the button's return, loginCallbackOf below)static userOfCode = (code) => {x = exchangeCode(code)if (x.error != null) { return { error = x.error } }u = ensureUser(x.identity)if (u == null) { return { error = 'could not store the user' } }return { user = u }}static userOfSession = (&session) => {if (session == null || session.user == null) { return null }return userRecord(session.user.id)}// the users @id of a session, or null (a page may know it: it is not the identity id)static userIdOfSession = (&session) => {u = userOfSession(session)return u == null ? null : u.id}// ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident"), copied from calendar.worldapi.org's project.hl ---------// (mission 028: out of project.hl, whose route `/login/callback` calls `loginCallbackOf` with the server's sessions)// /login/callback?ident_code=<code> the app's server exchanges the code for the identity's short id// (POST <ident>/api/exchange) and signs this app's OWN session in// (session.user = { id = <users @id> }); the header's "Log out" signs it out again// (components/main.hl face trackerLogOut) — ident's own session is untouched// BACK TO THE PAGE: /login.js puts `?next=` into the button's return URL at the click. Only a same-origin PATH// goes (one `/`, URL-safe characters, ≤ 500). Anything else → `/`.static nextChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;@!$()*:'static safePath = (&want) => {if (want == null || hlTypeName(want) != 'String' || want == '' || want.length > 500) { return '/' }if (want.slice(0, 1) != '/' || want.slice(0, 2) == '//' || want.slice(0, 7) == '/login/') { return '/' }let i = 0while (i < want.length) {if (!nextChars.includes(want[i])) { return '/' }i = i + 1}return want}// A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked in the session, then → /login/failedstatic loginFailedOf = (&sessions, &req, why) => {let s = req.sessionfresh = s == nullif (fresh) { s = sessions.mint() }s.data.loginError = whysessions.save(s)let 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' } })if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }return res}// the function route gets the cookie's session as req.session (hybriel #11); none yet → minted here. `sessions` = the// server's (hl:web `server.sessions`)static loginCallbackOf = (&sessions, &req) => {if (req.method != 'GET') { return loginFailedOf(sessions, req, 'GET only') }q = req.query != null ? req.query : {}code = q.ident_codeif (code == null || code == '') { return loginFailedOf(sessions, req, 'ident sent no login code') }// mission SK: every try is an exchange request to ident — at most `loginPerMinute` per caller addressif (!allowHit('login', clientKey(req), loginPerMinute, 60000)) { return loginFailedOf(sessions, req, 'too many login attempts — wait a minute') }x = userOfCode(code)if (x.error != null) { return loginFailedOf(sessions, req, x.error) }u = x.user// mission SK: a NEW session at every login (session fixation: a session id planted in the browser before the login must not be// the one that is signed in). The cookie of the old one is overwritten below.let s = sessions.mint()fresh = trues.user = { id = u.id }s.data.tag = randomBytes(16)s.data.loginError = nullsessions.save(s)let 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' } })if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }return res}
Branches
Latest commits
- 24e401b8Tracker: TR7 watch cleanmre
- b0412957Tracker: RV28b handed overmre
- 456940c8Tracker: RULINGS pathmre
- b87a8fdcTracker: worldapi-conductor paths backmre
- 641f3b54Tracker: Apollo answermre
- 8b3cbddaTracker: status, TR7 fix livemre
- ec30162aTracker: TR7 fix livemre
- 54cbec80compose: ignore SIGPIPE (TR7 crash loop, exit 141)mre
- 3e164b63Tracker: status after CL1mre
- 9d686bb3Tracker: CL1 reviewedmre
- b8bba562CL1: crash loop report (SIGPIPE confirmed, trap wrapper option)mre
- 298785f2Tracker: CL1 startedmre
- 36b22710Tracker: port slot, CL1 briefmre
- a401190fTracker: GO for the crash loopmre
- e195d372Tracker: token pathsmre
- 7f541d11Tracker conductor: CONDUCTOR.md, short STATUS.md, old status + decisions archive to archive/2026-10-31mre
- 8dd423f7README: login.js stays by caramboleyo's explicit rulemre
- d8df1493tracker: standby service on port 45018 and a gap-free hand-over in deploy.sh step 4mre
- 36dd1686ident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
- ff9b838etracker: the Ended status pill uses the same red as layouts (pill danger); gate updatedmre