gitoria

gitoria

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita81abdc9a81abdc9gitoria#34: org page via function route, member-reachable orgs, selects, reportmrea81abdc9/plugins/web/sessions.hl

13.4 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 in the order the Session class declares its fields (older stores wrote them sorted, so a file opening with `{"created":` is still a session); a session file is a JSON object that carries the keys `created` and `seen`. `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('{"') && t.endsWith('}') && t.includes('"created":') && t.includes('"seen":')
  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

  • a81abdc9gitoria#34: org page via function route, member-reachable orgs, selects, reportmre
  • 17f031f0gitoria#34: private repos, organizations, members, move tool, gatemre
  • 71b69343gitoria#23: the sidebar's Repositories link was a 404 after any in-page navigation (static menu re-evaluated publicUrl in the browser); the menu is an instance property now; gate taps it after a tab, folder, filemre
  • 90b4f728gitoria#25: restore the homepage cache and the parsed-blocks cache (they store data under immutable keys, no HTML); the page key, the framework readme key and the textHash key stay removedmre
  • a487248cgitoria#25: remove every cache that hid the page build (page key, Markdown render key, homepage cache, parsed-blocks cache) and the gate that only tested themmre
  • 12f2f4fegitoria: re-vendor Hybriel set-day27b, a startup fault in on Error exits 1mre
  • c21c084egitoria: write the standby service out in full so the boot gate can read the main servicemre
  • e307d69agitoria: say what is per process during the hand-overmre
  • f0cbe6a6gitoria: standby service on port 45014 and a deploy that hands over through it without a gapmre
  • 727cd083gitoria#25: README: vendor notes for Hybriel c1b1010f and the page cachemre
  • 61b72dedgitoria#25: re-vendor Hybriel master c1b1010f (W149 page cache), key the repo Readme page by slug and main commit, extend the readme-cache gatemre
  • 5b0b4b9ereadme-cache gate: use the security gate's ports when no own ports are givenmre
  • bc8f20d9gitoria#25: re-vendor Hybriel c09538bb with the W141 render cache, cache the homepage per commit, add the readme-cache gatemre
  • 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