gitoria
All repositories: gitoria
13.1 KB
// THE SESSION LAYER — a port of the archived hl:web's web_session.hl (mission 093,// 252, 255, 261), re-read 2026-09-12. The design is the creator's own from// hybrilior: one cookie holds a random id, the SERVER holds everything else; a// session fans out to every socket that shares the cookie; delivery is a// predicate per socket (here: the app's `audience`).//// THE FILE IS THE SESSION; MEMORY IS A CACHE OF THE ONES IN FLIGHT. A lookup// misses in memory, reads ONE file, revives it. Nothing loads the directory at// boot; a restart is a cold cache, not a wipe. The boot sweep walks the store// once to REMOVE expired files, never to revive.//// THE FILENAME IS A HASH OF THE ID, NEVER THE ID: a value a client sent must not// become a path, and `ls` on the store must not hand out live ids.//// THREE CLOCKS, all seconds: `maxAge` is how long a session stays VALID after its// last touch (the cookie's Max-Age too); `idle` how long it stays RESIDENT in// memory with no live socket (eviction is non-destructive — the file is the// truth — so a short clock is safe); `sweepEvery` how often the sweep may run,// piggybacking on real requests (no timer: a site with no requests has nothing// to sweep). `stampDrift` bounds how far the on-disk `seen` may lag the one in// memory, so an active session does not cost a disk write per asset request.//// `dir` is the store's absolute path, or null for memory only (the app's// `sessionDir = false`). The default the framework hands in is `<project>/.sessions`// — a DOT directory, which the dev watcher skips by construction (measured in the// archive: a store inside the watched tree made every session write a re-analysis).import HlwSession from './session.hl'import { randomToken } from 'hl:http1'import { now } from 'hl:time'import { sha256 } from 'hl:crypto'import { readFile, listDir, exists, writeFile, mkDir, remove } from 'hl:fs'String dir = nullNumber maxAge = 1209600Number idle = 900Number sweepEvery = 300Number stampDrift = 60String cookie = 'hlsid'secure = null // null: `Secure` when the request came over https; true: always; false: neverNumber anonMax = 10000 // the most anonymous sessions (nobody logged in) kept; the oldest go first (W124)String domain = '' // the cookie's `Domain` (ticket #44): '' = this host onlymap = {} // id → Session, the resident onespersistedSeen = {} // id → the `seen` last written to disk (write avoidance only)lastSweep = 0anonOrder = [] // ids of the anonymous sessions, oldest first (W124 eviction backstop)reported = {} // path → true: a foreign file in the store, said once// ---- the store --------------------------------------------------------------------path(sid) {if (dir == null) { return null }return dir + '/' + sha256(sid)}open() {if (dir != null) { mkDir(dir, 448) }lastSweep = now()if (dir != null) {let n = sweepStore(now() - maxAge * 1000)if (n > 0) { console.log('sessions: boot sweep removed ' + n + ' expired session file(s) from ' + dir) }}return null}load(sid) {let p = path(sid)if (p == null || !exists(p)) { return null }let raw = readFile(p)if (raw == null || !isSessionText(raw)) { return null }let rec = JSON.parse(raw)if (rec == null || rec.id != sid) { return null }let s = rec > new HlwSession()map[sid] = spersistedSeen[sid] = s.seenreturn s}put(s) {let p = path(s.id)if (p == null) { return null }if (!exists(dir)) { mkDir(dir, 448) }writeFile(p, JSON.stringify(s), 384)persistedSeen[s.id] = s.seenreturn null}drop(sid) {let p = path(sid)if (p != null) { remove(p) }persistedSeen[sid] = nullreturn null}// ---- the cookie ----------------------------------------------------------------parseCookies(header) {let out = {}if (header == null) { return out }for (part of header.split(';')) {let eq = part.indexOf('=')if (eq > 0) { out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim() }}return out}// `https` is whether THIS request came over https (TLS on the server, or X-Forwarded-Proto); the app's// `sessionSecure` overrides it either way (W124)cookieHeader(sid, https) {let sec = secure == null ? https == true : secure// W138: remember when and with which attributes this session's cookie went out (see `due`)let rec = sid != null ? map[sid] : nullif (rec != null) {rec.issuedSig = signature(sec)rec.issuedAt = now()save(rec)}return cookie + '=' + sid + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + maxAge + (domain != '' ? '; Domain=' + domain : '') + (sec ? '; Secure' : '')}// W138 (gitoria#24, creator rule): a short signature of the cookie's attributessignature(sec) {return cookie + '|' + domain + '|/|' + (sec ? 'S' : '-') + '|Lax'}// W138: does a signed-in session's cookie need to go out again? Yes when it was never issued, was issued// with other attributes (a Domain added since), or was last issued more than a day ago (Chrome caps a// cookie's lifetime at 400 days, and logins do not expire). Anonymous sessions are not refreshed.due(s, https) {if (s == null || s.id == null || s.user == null) { return false }let sec = secure == null ? https == true : securereturn s.issuedSig != signature(sec) || now() - s.issuedAt >= 86400000}// ---- the map ---------------------------------------------------------------------// the session a cookie header names: resident, or revived from its file; null when// it names none (no cookie, or an id nobody knows — that browser is anonymous)resolve(cookieHeader) {let ids = cookieValues(cookieHeader)if (ids.length == 0) { return null }if (ids.length == 1) { return byId(ids[0]) }// W137 (gitoria#24): a browser can hold two cookies of the session's name (an old host-only one and a// newer one with the Domain) and sends both. The first that belongs to a signed-in session wins, else// the first that belongs to any known session, else none.let first = nullfor (id of ids) {let s = lookup(id)if (s == null) { continue }if (s.user != null) { first = s break }if (first == null) { first = s }}if (first == null) { return null }touch(first)return first}// every value the Cookie header carries under the session's name, in the order sentcookieValues(header) {let out = []if (header == null) { return out }for (part of header.split(';')) {let eq = part.indexOf('=')if (eq > 0 && part.slice(0, eq).trim() == cookie) { out.push(part.slice(eq + 1).trim()) }}return out}// W137: the extra headers an answer carries when the request held the session's name more than once and// `s` is the session chosen among them: the chosen id again with the app's cookie attributes (Domain// included) under 'Set-Cookie', and, only when the app's cookie has a Domain, a host-only expiry under// 'set-cookie' (a second header line: the server writes one line per key, and the two keys differ in// case only). Without a Domain the expiry would delete the chosen cookie itself.repair(cookieHeaderText, s, https) {let out = {}if (s == null || s.id == null) { return out }let many = cookieValues(cookieHeaderText).length > 1if (!many && !due(s, https)) { return out }out['Set-Cookie'] = cookieHeader(s.id, https)if (many && domain != '') { out['set-cookie'] = expiry(https) }return out}// the same name, no Domain, gone at once: removes a stray host-only cookieexpiry(https) {let sec = secure == null ? https == true : securereturn cookie + '=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0' + (sec ? '; Secure' : '')}// for /__hl/adopt, which sets a new id and chooses nothing: the host-only strays are expired so the new// cookie is the only one of its namestrays(cookieHeaderText, https) {let out = {}if (domain != '' && cookieValues(cookieHeaderText).length > 1) { out['set-cookie'] = expiry(https) }return out}byId(sid) {let s = lookup(sid)if (s == null) { return null }touch(s)return s}lookup(sid) {if (sid == null) { return null }let s = map[sid]if (s == null) { s = load(sid) }return s}// SESSIONS ARE LAZY (W124): a visitor with no cookie has NO session — `fresh()` hands a transient// one (no id, not in the map, nothing on disk) that a page renders with or a face writes to. Only a// session that GOT something (a login, `data`, an upload) is `adopt`ed: it gets its id, goes into the// map and onto disk, and the caller sets the cookie. A flood of cookie-less requests so costs nothing,// and the anonymous ones that were adopted are capped (`anonMax`, oldest first).fresh() {return new HlwSession(created = now(), seen = now())}// A NEW SESSION WITH AN ID, in the map and on disk (the call W124 removed and apps used): `adopt(fresh())`.// The caller sets the cookie (`cookieHeader(s.id)`).mint() {return adopt(fresh())}// does the session hold anything worth a cookie and a file?hasContent(s) {return s != null && (s.user != null || s.data.keys().length > 0)}adopt(s) {maybeSweep([])if (s.id == null) { s.id = randomToken(32) }map[s.id] = sput(s)if (s.user == null) {anonOrder.push(s.id)if (anonOrder.length > anonMax) { evictAnon() }}return s}// ROTATE (W120): the session `s` gets a NEW id — its user, data and handled list move with it// (it is the same record, only the id changes), the old id's file and memory entry are deleted so a// planted id is anonymous from now on. Answers the old id. The caller tells the browser (cookie).move(s) {let old = s.idlet sid = randomToken(32)map[old] = nulldrop(old)s.id = sids.rotating = falses.seen = now()map[sid] = sput(s)let i = anonOrder.indexOf(old)if (i >= 0) { anonOrder[i] = sid }return old}// an upload (no content yet) is adopted at once; a face's session only when hasContent()evictAnon() {let over = anonOrder.length - anonMaxlet keep = []let n = 0for (id of anonOrder) {let s = map[id]if (s == null || s.user != null) { continue }if (n < over) {drop(id)map[id] = nulln = n + 1} else {keep.push(id)}}anonOrder = keepreturn null}// ONE WRITE PATH for the stamp: every request or frame that presents a session// moves `seen`; the file follows only when it has drifted `stampDrift` secondstouch(s) {s.seen = now()if (dir != null && s.id != null) {let last = persistedSeen[s.id]if (last == null || s.seen - last >= stampDrift * 1000) { put(s) }}return null}// what a face wrote (login, a cart) reaches the file now, not at the next driftsave(s) {if (s != null && s.id != null && map[s.id] != null) { put(s) }return null}// ---- the sweep -------------------------------------------------------------------// `live` is the set of session ids with an open socket — those are never evictedmaybeSweep(live) {if (now() - lastSweep >= sweepEvery * 1000) { sweep(live) }return null}sweep(live) {lastSweep = now()let cutoff = now() - maxAge * 1000let cold = now() - idle * 1000let evicted = 0let expired = 0let next = {}for (k of map.keys()) {let s = map[k]if (s == null) {// dropped earlier} else if (s.seen <= cutoff) {drop(k)expired = expired + 1} else if (dir != null && s.seen <= cold && !live.includes(k)) {persistedSeen[k] = nullevicted = evicted + 1} else {next[k] = s}}map = next // a fresh hybrid: the compaction (archive, mission 261)let dropped = 0if (dir != null) { dropped = sweepStore(cutoff) }if (evicted + expired + dropped > 0) {console.log('sessions: sweep — evicted ' + evicted + ', expired ' + expired + ', ' + dropped + ' file(s) removed, ' + map.keys().length + ' resident')}return null}sweepStore(cutoff) {let gone = 0if (!exists(dir)) { return gone }for (e of listDir(dir)) {let raw = isSessionName(e.name) && e.type == 'file' ? readFile(e.path) : nullif (raw != null && !isSessionText(raw)) { raw = null }if (raw == null) { foreign(e) }if (raw != null) {let rec = JSON.parse(raw)if (rec != null && rec.seen <= cutoff) {remove(e.path)persistedSeen[rec.id] = nullgone = gone + 1}}}return gone}// ---- what the store holds that is not a session -----------------------------------// A FILE THAT IS NOT A SESSION IS SKIPPED, NEVER PARSED. The store is a directory an// operator can put anything into (a marker, an editor's backup, a copy), and// `JSON.parse` aborts the program on text that is not JSON — at the boot sweep that was// the whole server, before it served anything (ticket #26). Every file this layer// writes is named by a sha256 (64 lowercase hex characters) and holds a Session's JSON,// whose keys come out sorted, so it opens with `{"created":`; `writeFile` renames a// finished temp file over the target, so a torn session file cannot occur. A file that// is not that shape is left where it is, and said once.isSessionName(name) {if (name.length != 64) { return false }for (c of name.split('')) {if (!'0123456789abcdef'.includes(c)) { return false }}return true}isSessionText(raw) {let t = raw.trim()return t.startsWith('{"created":') && t.endsWith('}')}foreign(e) {if (reported[e.path] == null) {reported[e.path] = trueconsole.log('sessions: skipped ' + e.path + ' — not a session file (the store names its files by a hash and writes JSON); it is left where it is')}return null}
Branches
- f1-broken-json
- f2-api-bugs
- gp-gate-ports
- heap-revert
- hl25-records
- ident-chooser-selector
- mainmain branch
- p51-public-pr-reads
- records-1112
- s25-no-session-on-login-error
- v59
- w52-person-approval
- w52b-approval-followup
- w52c-header-phone
- w53-pulls-speed-pr
- w54-repo-rename-pr
- w55-rename-org
- w56-owner-members
- w62-pr-close
- w63-force-push
- w64-org-slash
Latest commits
- 9feebbd3Re-vendor Hybriel to ded47c13 (W145: Firefox start script fix)mre
- 28ed41e5gitoria#24: one sign-in comes from hl:web batch 20, the /session/share workaround is gonemre
- 3b2669e4gs: drop the unbuildable legacy check, fix pwa fetchmre
- 2a2fdd77gs: C2 check before cookie experimentsmre
- 76e0587aWIP gs 2mre
- a80da7bdWIP gs: security gate for lazy sessions, g24 browser checksmre
- 23fb05d8re-vendor Hybriel aaa39e69 (hl:web batch 20: login emit and Sessions.mint, tab follows a login, signed-in session cookie wins among duplicates and is re-issued with the Domain, W85 faster render, lazy sessions)mre
- a0727ca3ident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
- a06975f9gitoria: a gap between your name and Log out in the phone header (they touched); gate checks itmre
- 32ba9d59gitoria: leave the host-only cookie experiment out of the browser gate (gitoria#24 is a separate mission)mre
- 43ad2bcfgitoria header: the selector alone plus your name and Log out as before the theme missions; tests follow (WIP: host-only cookie experiment fails)mre
- ac2c4e3fident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
- b279f536theme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
- 2b01515ctests/ticketskit: a failed start kills the tickets server (own process group); stop() kills the groupmre
- 109cfc5ctests/ticketskit: keep the rotated session cookie of the tickets login (tickets ST2 session rotation)mre
- 7eb6be27sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
- b3911918reports/MG-mobile.md: 404 fixed, rebased gatesMG
- 9da65b42tests/browser.mjs: 404 checks (host, no hydration wait)MG
- 00517fafgitoria: shell 404 page for unknown paths (catch-all route, status 404, JSON 404 under /api), 390 gate checksMG
- d9e977f0reports/MG-mobile.md, LOGMG