gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita80da7bda80da7bdWIP gs: security gate for lazy sessions, g24 browser checksmrea80da7bd/plugins/web/sessions.hl

13.1 KB

  1. // THE SESSION LAYER — a port of the archived hl:web's web_session.hl (mission 093,
  2. // 252, 255, 261), re-read 2026-09-12. The design is the creator's own from
  3. // hybrilior: one cookie holds a random id, the SERVER holds everything else; a
  4. // session fans out to every socket that shares the cookie; delivery is a
  5. // predicate per socket (here: the app's `audience`).
  6. //
  7. // THE FILE IS THE SESSION; MEMORY IS A CACHE OF THE ONES IN FLIGHT. A lookup
  8. // misses in memory, reads ONE file, revives it. Nothing loads the directory at
  9. // boot; a restart is a cold cache, not a wipe. The boot sweep walks the store
  10. // once to REMOVE expired files, never to revive.
  11. //
  12. // THE FILENAME IS A HASH OF THE ID, NEVER THE ID: a value a client sent must not
  13. // become a path, and `ls` on the store must not hand out live ids.
  14. //
  15. // THREE CLOCKS, all seconds: `maxAge` is how long a session stays VALID after its
  16. // last touch (the cookie's Max-Age too); `idle` how long it stays RESIDENT in
  17. // memory with no live socket (eviction is non-destructive — the file is the
  18. // truth — so a short clock is safe); `sweepEvery` how often the sweep may run,
  19. // piggybacking on real requests (no timer: a site with no requests has nothing
  20. // to sweep). `stampDrift` bounds how far the on-disk `seen` may lag the one in
  21. // memory, so an active session does not cost a disk write per asset request.
  22. //
  23. // `dir` is the store's absolute path, or null for memory only (the app's
  24. // `sessionDir = false`). The default the framework hands in is `<project>/.sessions`
  25. // — a DOT directory, which the dev watcher skips by construction (measured in the
  26. // archive: a store inside the watched tree made every session write a re-analysis).
  27. import HlwSession from './session.hl'
  28. import { randomToken } from 'hl:http1'
  29. import { now } from 'hl:time'
  30. import { sha256 } from 'hl:crypto'
  31. import { readFile, listDir, exists, writeFile, mkDir, remove } from 'hl:fs'
  32. String dir = null
  33. Number maxAge = 1209600
  34. Number idle = 900
  35. Number sweepEvery = 300
  36. Number stampDrift = 60
  37. String cookie = 'hlsid'
  38. secure = null // null: `Secure` when the request came over https; true: always; false: never
  39. Number anonMax = 10000 // the most anonymous sessions (nobody logged in) kept; the oldest go first (W124)
  40. String domain = '' // the cookie's `Domain` (ticket #44): '' = this host only
  41. map = {} // id → Session, the resident ones
  42. persistedSeen = {} // id → the `seen` last written to disk (write avoidance only)
  43. lastSweep = 0
  44. anonOrder = [] // ids of the anonymous sessions, oldest first (W124 eviction backstop)
  45. reported = {} // path → true: a foreign file in the store, said once
  46. // ---- the store --------------------------------------------------------------------
  47. path(sid) {
  48. if (dir == null) { return null }
  49. return dir + '/' + sha256(sid)
  50. }
  51. open() {
  52. if (dir != null) { mkDir(dir, 448) }
  53. lastSweep = now()
  54. if (dir != null) {
  55. let n = sweepStore(now() - maxAge * 1000)
  56. if (n > 0) { console.log('sessions: boot sweep removed ' + n + ' expired session file(s) from ' + dir) }
  57. }
  58. return null
  59. }
  60. load(sid) {
  61. let p = path(sid)
  62. if (p == null || !exists(p)) { return null }
  63. let raw = readFile(p)
  64. if (raw == null || !isSessionText(raw)) { return null }
  65. let rec = JSON.parse(raw)
  66. if (rec == null || rec.id != sid) { return null }
  67. let s = rec > new HlwSession()
  68. map[sid] = s
  69. persistedSeen[sid] = s.seen
  70. return s
  71. }
  72. put(s) {
  73. let p = path(s.id)
  74. if (p == null) { return null }
  75. if (!exists(dir)) { mkDir(dir, 448) }
  76. writeFile(p, JSON.stringify(s), 384)
  77. persistedSeen[s.id] = s.seen
  78. return null
  79. }
  80. drop(sid) {
  81. let p = path(sid)
  82. if (p != null) { remove(p) }
  83. persistedSeen[sid] = null
  84. return null
  85. }
  86. // ---- the cookie ----------------------------------------------------------------
  87. parseCookies(header) {
  88. let out = {}
  89. if (header == null) { return out }
  90. for (part of header.split(';')) {
  91. let eq = part.indexOf('=')
  92. if (eq > 0) { out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim() }
  93. }
  94. return out
  95. }
  96. // `https` is whether THIS request came over https (TLS on the server, or X-Forwarded-Proto); the app's
  97. // `sessionSecure` overrides it either way (W124)
  98. cookieHeader(sid, https) {
  99. let sec = secure == null ? https == true : secure
  100. // W138: remember when and with which attributes this session's cookie went out (see `due`)
  101. let rec = sid != null ? map[sid] : null
  102. if (rec != null) {
  103. rec.issuedSig = signature(sec)
  104. rec.issuedAt = now()
  105. save(rec)
  106. }
  107. return cookie + '=' + sid + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + maxAge + (domain != '' ? '; Domain=' + domain : '') + (sec ? '; Secure' : '')
  108. }
  109. // W138 (gitoria#24, creator rule): a short signature of the cookie's attributes
  110. signature(sec) {
  111. return cookie + '|' + domain + '|/|' + (sec ? 'S' : '-') + '|Lax'
  112. }
  113. // W138: does a signed-in session's cookie need to go out again? Yes when it was never issued, was issued
  114. // with other attributes (a Domain added since), or was last issued more than a day ago (Chrome caps a
  115. // cookie's lifetime at 400 days, and logins do not expire). Anonymous sessions are not refreshed.
  116. due(s, https) {
  117. if (s == null || s.id == null || s.user == null) { return false }
  118. let sec = secure == null ? https == true : secure
  119. return s.issuedSig != signature(sec) || now() - s.issuedAt >= 86400000
  120. }
  121. // ---- the map ---------------------------------------------------------------------
  122. // the session a cookie header names: resident, or revived from its file; null when
  123. // it names none (no cookie, or an id nobody knows — that browser is anonymous)
  124. resolve(cookieHeader) {
  125. let ids = cookieValues(cookieHeader)
  126. if (ids.length == 0) { return null }
  127. if (ids.length == 1) { return byId(ids[0]) }
  128. // W137 (gitoria#24): a browser can hold two cookies of the session's name (an old host-only one and a
  129. // newer one with the Domain) and sends both. The first that belongs to a signed-in session wins, else
  130. // the first that belongs to any known session, else none.
  131. let first = null
  132. for (id of ids) {
  133. let s = lookup(id)
  134. if (s == null) { continue }
  135. if (s.user != null) { first = s break }
  136. if (first == null) { first = s }
  137. }
  138. if (first == null) { return null }
  139. touch(first)
  140. return first
  141. }
  142. // every value the Cookie header carries under the session's name, in the order sent
  143. cookieValues(header) {
  144. let out = []
  145. if (header == null) { return out }
  146. for (part of header.split(';')) {
  147. let eq = part.indexOf('=')
  148. if (eq > 0 && part.slice(0, eq).trim() == cookie) { out.push(part.slice(eq + 1).trim()) }
  149. }
  150. return out
  151. }
  152. // W137: the extra headers an answer carries when the request held the session's name more than once and
  153. // `s` is the session chosen among them: the chosen id again with the app's cookie attributes (Domain
  154. // included) under 'Set-Cookie', and, only when the app's cookie has a Domain, a host-only expiry under
  155. // 'set-cookie' (a second header line: the server writes one line per key, and the two keys differ in
  156. // case only). Without a Domain the expiry would delete the chosen cookie itself.
  157. repair(cookieHeaderText, s, https) {
  158. let out = {}
  159. if (s == null || s.id == null) { return out }
  160. let many = cookieValues(cookieHeaderText).length > 1
  161. if (!many && !due(s, https)) { return out }
  162. out['Set-Cookie'] = cookieHeader(s.id, https)
  163. if (many && domain != '') { out['set-cookie'] = expiry(https) }
  164. return out
  165. }
  166. // the same name, no Domain, gone at once: removes a stray host-only cookie
  167. expiry(https) {
  168. let sec = secure == null ? https == true : secure
  169. return cookie + '=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0' + (sec ? '; Secure' : '')
  170. }
  171. // for /__hl/adopt, which sets a new id and chooses nothing: the host-only strays are expired so the new
  172. // cookie is the only one of its name
  173. strays(cookieHeaderText, https) {
  174. let out = {}
  175. if (domain != '' && cookieValues(cookieHeaderText).length > 1) { out['set-cookie'] = expiry(https) }
  176. return out
  177. }
  178. byId(sid) {
  179. let s = lookup(sid)
  180. if (s == null) { return null }
  181. touch(s)
  182. return s
  183. }
  184. lookup(sid) {
  185. if (sid == null) { return null }
  186. let s = map[sid]
  187. if (s == null) { s = load(sid) }
  188. return s
  189. }
  190. // SESSIONS ARE LAZY (W124): a visitor with no cookie has NO session — `fresh()` hands a transient
  191. // one (no id, not in the map, nothing on disk) that a page renders with or a face writes to. Only a
  192. // session that GOT something (a login, `data`, an upload) is `adopt`ed: it gets its id, goes into the
  193. // map and onto disk, and the caller sets the cookie. A flood of cookie-less requests so costs nothing,
  194. // and the anonymous ones that were adopted are capped (`anonMax`, oldest first).
  195. fresh() {
  196. return new HlwSession(created = now(), seen = now())
  197. }
  198. // A NEW SESSION WITH AN ID, in the map and on disk (the call W124 removed and apps used): `adopt(fresh())`.
  199. // The caller sets the cookie (`cookieHeader(s.id)`).
  200. mint() {
  201. return adopt(fresh())
  202. }
  203. // does the session hold anything worth a cookie and a file?
  204. hasContent(s) {
  205. return s != null && (s.user != null || s.data.keys().length > 0)
  206. }
  207. adopt(s) {
  208. maybeSweep([])
  209. if (s.id == null) { s.id = randomToken(32) }
  210. map[s.id] = s
  211. put(s)
  212. if (s.user == null) {
  213. anonOrder.push(s.id)
  214. if (anonOrder.length > anonMax) { evictAnon() }
  215. }
  216. return s
  217. }
  218. // ROTATE (W120): the session `s` gets a NEW id — its user, data and handled list move with it
  219. // (it is the same record, only the id changes), the old id's file and memory entry are deleted so a
  220. // planted id is anonymous from now on. Answers the old id. The caller tells the browser (cookie).
  221. move(s) {
  222. let old = s.id
  223. let sid = randomToken(32)
  224. map[old] = null
  225. drop(old)
  226. s.id = sid
  227. s.rotating = false
  228. s.seen = now()
  229. map[sid] = s
  230. put(s)
  231. let i = anonOrder.indexOf(old)
  232. if (i >= 0) { anonOrder[i] = sid }
  233. return old
  234. }
  235. // an upload (no content yet) is adopted at once; a face's session only when hasContent()
  236. evictAnon() {
  237. let over = anonOrder.length - anonMax
  238. let keep = []
  239. let n = 0
  240. for (id of anonOrder) {
  241. let s = map[id]
  242. if (s == null || s.user != null) { continue }
  243. if (n < over) {
  244. drop(id)
  245. map[id] = null
  246. n = n + 1
  247. } else {
  248. keep.push(id)
  249. }
  250. }
  251. anonOrder = keep
  252. return null
  253. }
  254. // ONE WRITE PATH for the stamp: every request or frame that presents a session
  255. // moves `seen`; the file follows only when it has drifted `stampDrift` seconds
  256. touch(s) {
  257. s.seen = now()
  258. if (dir != null && s.id != null) {
  259. let last = persistedSeen[s.id]
  260. if (last == null || s.seen - last >= stampDrift * 1000) { put(s) }
  261. }
  262. return null
  263. }
  264. // what a face wrote (login, a cart) reaches the file now, not at the next drift
  265. save(s) {
  266. if (s != null && s.id != null && map[s.id] != null) { put(s) }
  267. return null
  268. }
  269. // ---- the sweep -------------------------------------------------------------------
  270. // `live` is the set of session ids with an open socket — those are never evicted
  271. maybeSweep(live) {
  272. if (now() - lastSweep >= sweepEvery * 1000) { sweep(live) }
  273. return null
  274. }
  275. sweep(live) {
  276. lastSweep = now()
  277. let cutoff = now() - maxAge * 1000
  278. let cold = now() - idle * 1000
  279. let evicted = 0
  280. let expired = 0
  281. let next = {}
  282. for (k of map.keys()) {
  283. let s = map[k]
  284. if (s == null) {
  285. // dropped earlier
  286. } else if (s.seen <= cutoff) {
  287. drop(k)
  288. expired = expired + 1
  289. } else if (dir != null && s.seen <= cold && !live.includes(k)) {
  290. persistedSeen[k] = null
  291. evicted = evicted + 1
  292. } else {
  293. next[k] = s
  294. }
  295. }
  296. map = next // a fresh hybrid: the compaction (archive, mission 261)
  297. let dropped = 0
  298. if (dir != null) { dropped = sweepStore(cutoff) }
  299. if (evicted + expired + dropped > 0) {
  300. console.log('sessions: sweep — evicted ' + evicted + ', expired ' + expired + ', ' + dropped + ' file(s) removed, ' + map.keys().length + ' resident')
  301. }
  302. return null
  303. }
  304. sweepStore(cutoff) {
  305. let gone = 0
  306. if (!exists(dir)) { return gone }
  307. for (e of listDir(dir)) {
  308. let raw = isSessionName(e.name) && e.type == 'file' ? readFile(e.path) : null
  309. if (raw != null && !isSessionText(raw)) { raw = null }
  310. if (raw == null) { foreign(e) }
  311. if (raw != null) {
  312. let rec = JSON.parse(raw)
  313. if (rec != null && rec.seen <= cutoff) {
  314. remove(e.path)
  315. persistedSeen[rec.id] = null
  316. gone = gone + 1
  317. }
  318. }
  319. }
  320. return gone
  321. }
  322. // ---- what the store holds that is not a session -----------------------------------
  323. // A FILE THAT IS NOT A SESSION IS SKIPPED, NEVER PARSED. The store is a directory an
  324. // operator can put anything into (a marker, an editor's backup, a copy), and
  325. // `JSON.parse` aborts the program on text that is not JSON — at the boot sweep that was
  326. // the whole server, before it served anything (ticket #26). Every file this layer
  327. // writes is named by a sha256 (64 lowercase hex characters) and holds a Session's JSON,
  328. // whose keys come out sorted, so it opens with `{"created":`; `writeFile` renames a
  329. // finished temp file over the target, so a torn session file cannot occur. A file that
  330. // is not that shape is left where it is, and said once.
  331. isSessionName(name) {
  332. if (name.length != 64) { return false }
  333. for (c of name.split('')) {
  334. if (!'0123456789abcdef'.includes(c)) { return false }
  335. }
  336. return true
  337. }
  338. isSessionText(raw) {
  339. let t = raw.trim()
  340. return t.startsWith('{"created":') && t.endsWith('}')
  341. }
  342. foreign(e) {
  343. if (reported[e.path] == null) {
  344. reported[e.path] = true
  345. console.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')
  346. }
  347. return null
  348. }

Branches

Latest commits

  • 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
  • 2f2725actests/browser.mjs: commit-row check (one row, centred date)MG
  • 4df1ea01tests/browser.mjs: MG phone checks (list first, no dead strip, one branch heading, tab grid, commit rows, PR title row, ticket columns, wrapping commands)MG
  • c52424e9gitoria mobile: repo list before the forms, 3x2 tab grid, no duplicate branch heading, ordered commit rows, aligned ticket rows, pull title on its own row, wrapping clone commands, no dead strip under formsMG
  • 3a95252dG3: cache parsed README blocks by sha256 of the text (bounded LRU), reportmre
  • 570138cddeploy: security gate (tests/security.mjs)mre