tracker
All repositories: gitoria
9.2 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) {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) {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, https) => {let s = req.sessionfresh = s == nullif (fresh) { s = sessions.mint() }s.data.loginError = whysessions.save(s)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, https) }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, https) => {if (req.method != 'GET') { return loginFailedOf(&sessions, &req, 'GET only', https) }q = req.query != null ? req.query : {}code = q.ident_codeif (code == null || code == '') { return loginFailedOf(&sessions, &req, 'ident sent no login code', https) }// 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', https) }x = userOfCode(code)if (x.error != null) { return loginFailedOf(&sessions, &req, x.error, https) }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.s = sessions.mint()fresh = trues.user = { id = u.id }s.data.tag = randomBytes(16)s.data.loginError = nullsessions.save(s)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, https) }return res}static tagOf = (&session) => { return session != null && session.data != null ? session.data.tag : null }static sessionAudience = (tag, &session) => { return tag != null && tagOf(&session) == tag }
Branches
Latest commits
- ed4cbab2status timemre
- e982c26dlog: HM65 mergedmre
- 6e72f9d1Merge hm65-fields: episode boot scan reads three fieldsmre
- 07a5c883HM65 report measured field projection and complete validationmre
- 0eab858fRead only catalog date fields during the episode boot scanmre
- d3179273log: HM65 hl:heap vendoringmre
- cb78a1a0HM65 report missing heap diagnostic package with repromre
- 89606a5cHM65 briefmre
- 096ce0d4log: DP69 live on day48mre
- 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