gitoria

jukebox

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Main branchmain10f8a8c8Merge branch 'code-order' into mainJukeboxmain/plugins/web/sessions.hl

17.5 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 store pass walks the store
  10. // to REMOVE expired files, never to revive, and never all at once: a slice of a few
  11. // milliseconds per request (W179: a walk of 392 000 files stalled the one request thread 15-30 s).
  12. //
  13. // THE FILENAME IS A HASH OF THE ID, NEVER THE ID: a value a client sent must not
  14. // become a path, and `ls` on the store must not hand out live ids.
  15. //
  16. // THREE CLOCKS, all seconds: `maxAge` is how long a session stays VALID after its
  17. // last touch for a logged-in session (the cookie's Max-Age too);
  18. // anonymous sessions expire after `anonKeep`, with or without app data; `idle` how long it stays RESIDENT in
  19. // memory with no live socket (eviction is non-destructive — the file is the
  20. // truth — so a short clock is safe); `sweepEvery` how often the sweep may run,
  21. // piggybacking on real requests (no timer: a site with no requests has nothing
  22. // to sweep). `stampDrift` bounds how far the on-disk `seen` may lag the one in
  23. // memory, so an active session does not cost a disk write per asset request.
  24. //
  25. // `dir` is the store's absolute path, or null for memory only (the app's
  26. // `sessionDir = false`). The default the framework hands in is `<project>/.sessions`
  27. // — a DOT directory, which the dev watcher skips by construction (measured in the
  28. // archive: a store inside the watched tree made every session write a re-analysis).
  29. import HlwSession from './session.hl'
  30. import { randomToken } from 'hl:http1'
  31. import { now } from 'hl:time'
  32. import { sha256 } from 'hl:crypto'
  33. import { readFile, listDir, exists, writeFile, mkDir, remove, changeTime, stat } from 'hl:fs'
  34. String dir = null
  35. Number maxAge = 1209600
  36. Number idle = 900
  37. Number sweepEvery = 300
  38. Number stampDrift = 60
  39. String cookie = 'hlsid'
  40. secure = null // null: `Secure` when the request came over https; true: always; false: never
  41. Number anonMax = 10000 // the most anonymous sessions (nobody logged in) kept; the oldest go first (W124)
  42. String domain = '' // the cookie's `Domain` (ticket #44): '' = this host only
  43. Number anonKeep = 86400 // seconds any anonymous session keeps its file; the store pass removes older ones (W179)
  44. Number slice = 40 // milliseconds of one request the store pass may use (W179)
  45. map = {} // id → Session, the resident ones
  46. persistedSeen = {} // id → the `seen` last written to disk (write avoidance only)
  47. stamped = {} // id → the file's change time when THIS process last read or wrote it (ident#28)
  48. lastSweep = 0
  49. anonOrder = [] // ids of the anonymous sessions, oldest first (W124 eviction backstop)
  50. reported = {} // path → true: a foreign file in the store, said once
  51. queue = null // session filenames awaiting a slice; full directory entries are never retained (W331)
  52. qi = 0 // the next entry of `queue`
  53. qGone = 0 // files this pass removed so far
  54. qListed = 0 // all directory entries, including foreign ones handled while listing
  55. lastPass = 0 // when the last pass began
  56. // ---- the store --------------------------------------------------------------------
  57. path(sid) {
  58. if (dir == null) { return null }
  59. return dir + '/' + sha256(sid)
  60. }
  61. open() {
  62. if (dir != null) { mkDir(dir, 448) }
  63. lastSweep = now()
  64. if (startPass()) { storeSlice() } // the first pass begins at boot (one listing, one slice); a foreign file in a small store is named at once
  65. return null
  66. }
  67. load(sid) {
  68. let p = path(sid)
  69. if (p == null || !exists(p)) { return null }
  70. let stamp = changeTime(p) // taken BEFORE the read: a write that lands between them shows at the next lookup
  71. let raw = readFile(p)
  72. if (raw == null || !isSessionText(raw)) { return null }
  73. let rec = JSON.parse(raw)
  74. if (rec == null || rec.id != sid) { return null }
  75. if (expired(rec, now())) { drop(sid) return null }
  76. let s = rec > new HlwSession()
  77. map[sid] = s
  78. persistedSeen[sid] = s.seen
  79. stamped[sid] = stamp
  80. return s
  81. }
  82. // IDENT#28 — THE FILE IS THE TRUTH, MEMORY ONLY A COPY. Another process on the same store (the standby
  83. // beside the main one) can write a login into the file while this process holds the session resident.
  84. // `refresh` compares the file's change time with the one this process last saw and, when the file is
  85. // newer, copies it INTO the resident session (the same object, so every socket holding the handle sees
  86. // it). Answers true when it reloaded. A missing or foreign file leaves memory alone.
  87. refresh(s) {
  88. if (dir == null || s == null || s.id == null) { return false }
  89. let p = path(s.id)
  90. let stamp = changeTime(p)
  91. if (stamp == null || stamp == stamped[s.id]) { return false }
  92. let raw = readFile(p)
  93. if (raw == null || !isSessionText(raw)) { return false }
  94. let rec = JSON.parse(raw)
  95. if (rec == null || rec.id != s.id) { return false }
  96. let f = rec > new HlwSession()
  97. s.user = f.user
  98. s.data = f.data
  99. s.handled = f.handled
  100. s.created = f.created
  101. s.issuedSig = f.issuedSig
  102. s.issuedAt = f.issuedAt
  103. if (f.seen > s.seen) { s.seen = f.seen }
  104. persistedSeen[s.id] = f.seen
  105. stamped[s.id] = stamp
  106. return true
  107. }
  108. put(s) {
  109. let p = path(s.id)
  110. if (p == null) { return null }
  111. if (!exists(dir)) { mkDir(dir, 448) }
  112. // IDENT#28: never put an older memory copy over a newer file that holds a login this one lacks
  113. if (s.user == null && stamped[s.id] != null && changeTime(p) != stamped[s.id]) {
  114. refresh(s)
  115. if (s.user != null) { return null }
  116. }
  117. writeFile(p, JSON.stringify(s), 384)
  118. persistedSeen[s.id] = s.seen
  119. stamped[s.id] = changeTime(p)
  120. return null
  121. }
  122. drop(sid) {
  123. let p = path(sid)
  124. if (p != null) { remove(p) }
  125. persistedSeen[sid] = null
  126. stamped[sid] = null
  127. return null
  128. }
  129. // ---- the cookie ----------------------------------------------------------------
  130. parseCookies(header) {
  131. let out = {}
  132. if (header == null) { return out }
  133. for (part of header.split(';')) {
  134. let eq = part.indexOf('=')
  135. if (eq > 0) { out[part.slice(0, eq).trim()] = part.slice(eq + 1).trim() }
  136. }
  137. return out
  138. }
  139. // `https` is whether THIS request came over https (TLS on the server, or X-Forwarded-Proto); the app's
  140. // `sessionSecure` overrides it either way (W124)
  141. cookieHeader(sid, https) {
  142. let sec = secure == null ? https == true : secure
  143. // W138: remember when and with which attributes this session's cookie went out (see `due`)
  144. let rec = sid != null ? map[sid] : null
  145. if (rec != null) {
  146. rec.issuedSig = signature(sec)
  147. rec.issuedAt = now()
  148. save(rec)
  149. }
  150. return cookie + '=' + sid + '; Path=/; HttpOnly; SameSite=Lax; Max-Age=' + maxAge + (domain != '' ? '; Domain=' + domain : '') + (sec ? '; Secure' : '')
  151. }
  152. // W138 (gitoria#24, creator rule): a short signature of the cookie's attributes
  153. signature(sec) {
  154. return cookie + '|' + domain + '|/|' + (sec ? 'S' : '-') + '|Lax'
  155. }
  156. // W138: does a session's cookie need to go out again? Yes when it was never issued, was issued
  157. // with other attributes (a Domain added since), or was
  158. // last issued more than a day ago (Chrome caps a cookie's lifetime at 400 days, and logins do not expire).
  159. // Anonymous sessions that carry a cookie count too (ident#28: a cookie issued with an old short Max-Age is replaced within a day of its next request); a request
  160. // with no cookie has no session here and gets none (lazy sessions).
  161. due(s, https) {
  162. if (s == null || s.id == null) { return false }
  163. let sec = secure == null ? https == true : secure
  164. return s.issuedSig != signature(sec) || now() - s.issuedAt >= 86400000
  165. }
  166. // ---- the map ---------------------------------------------------------------------
  167. // the session a cookie header names: resident, or revived from its file; null when
  168. // it names none (no cookie, or an id nobody knows — that browser is anonymous)
  169. resolve(cookieHeader) {
  170. let ids = cookieValues(cookieHeader)
  171. if (ids.length == 0) { return null }
  172. if (ids.length == 1) { return byId(ids[0]) }
  173. // W137 (gitoria#24): a browser can hold two cookies of the session's name (an old host-only one and a
  174. // newer one with the Domain) and sends both. The first that belongs to a signed-in session wins, else
  175. // the first that belongs to any known session, else none.
  176. let first = null
  177. for (id of ids) {
  178. let s = lookup(id)
  179. if (s == null) { continue }
  180. if (s.user != null) { first = s break }
  181. if (first == null) { first = s }
  182. }
  183. if (first == null) { return null }
  184. touch(first)
  185. return first
  186. }
  187. // every value the Cookie header carries under the session's name, in the order sent
  188. cookieValues(header) {
  189. let out = []
  190. if (header == null) { return out }
  191. for (part of header.split(';')) {
  192. let eq = part.indexOf('=')
  193. if (eq > 0 && part.slice(0, eq).trim() == cookie) { out.push(part.slice(eq + 1).trim()) }
  194. }
  195. return out
  196. }
  197. // W137: the extra headers an answer carries when the request held the session's name more than once and
  198. // `s` is the session chosen among them: the chosen id again with the app's cookie attributes (Domain
  199. // included) under 'Set-Cookie', and, only when the app's cookie has a Domain, a host-only expiry under
  200. // 'set-cookie' (a second header line: the server writes one line per key, and the two keys differ in
  201. // case only). Without a Domain the expiry would delete the chosen cookie itself.
  202. repair(cookieHeaderText, s, https) {
  203. let out = {}
  204. if (s == null || s.id == null) { return out }
  205. let many = cookieValues(cookieHeaderText).length > 1
  206. if (!many && !due(s, https)) { return out }
  207. out['Set-Cookie'] = cookieHeader(s.id, https)
  208. if (many && domain != '') { out['set-cookie'] = expiry(https) }
  209. return out
  210. }
  211. // the same name, no Domain, gone at once: removes a stray host-only cookie
  212. expiry(https) {
  213. let sec = secure == null ? https == true : secure
  214. return cookie + '=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0' + (sec ? '; Secure' : '')
  215. }
  216. // for /__hl/adopt, which sets a new id and chooses nothing: the host-only strays are expired so the new
  217. // cookie is the only one of its name
  218. strays(cookieHeaderText, https) {
  219. let out = {}
  220. if (domain != '' && cookieValues(cookieHeaderText).length > 1) { out['set-cookie'] = expiry(https) }
  221. return out
  222. }
  223. byId(sid) {
  224. let s = lookup(sid)
  225. if (s == null) { return null }
  226. touch(s)
  227. return s
  228. }
  229. lookup(sid) {
  230. if (sid == null) { return null }
  231. let s = map[sid]
  232. if (s == null) { s = load(sid) } else { refresh(s) }
  233. return s
  234. }
  235. // SESSIONS ARE LAZY (W124): a visitor with no cookie has NO session — `fresh()` hands a transient
  236. // one (no id, not in the map, nothing on disk) that a page renders with or a face writes to. Only a
  237. // session that GOT something (a login, `data`, an upload) is `adopt`ed: it gets its id, goes into the
  238. // map and onto disk, and the caller sets the cookie. A flood of cookie-less requests so costs nothing,
  239. // and the anonymous ones that were adopted are capped (`anonMax`, oldest first).
  240. fresh() {
  241. return new HlwSession(created = now(), seen = now())
  242. }
  243. // A NEW SESSION WITH AN ID, in the map and on disk (the call W124 removed and apps used): `adopt(fresh())`.
  244. // The caller sets the cookie (`cookieHeader(s.id)`).
  245. mint() {
  246. return adopt(fresh())
  247. }
  248. // does the session hold anything worth a cookie and a file?
  249. hasContent(s) {
  250. return s != null && (s.user != null || s.data.keys().length > 0)
  251. }
  252. adopt(s) {
  253. maybeSweep([])
  254. if (s.id == null) { s.id = randomToken(32) }
  255. map[s.id] = s
  256. put(s)
  257. if (s.user == null) {
  258. anonOrder.push(s.id)
  259. if (anonOrder.length > anonMax) { evictAnon() }
  260. }
  261. return s
  262. }
  263. // ROTATE (W120): the session `s` gets a NEW id — its user, data and handled list move with it
  264. // (it is the same record, only the id changes), the old id's file and memory entry are deleted so a
  265. // planted id is anonymous from now on. Answers the old id. The caller tells the browser (cookie).
  266. move(s) {
  267. let old = s.id
  268. let sid = randomToken(32)
  269. map[old] = null
  270. drop(old)
  271. s.id = sid
  272. s.rotating = false
  273. s.seen = now()
  274. map[sid] = s
  275. put(s)
  276. let i = anonOrder.indexOf(old)
  277. if (i >= 0) { anonOrder[i] = sid }
  278. return old
  279. }
  280. // an upload (no content yet) is adopted at once; a face's session only when hasContent()
  281. evictAnon() {
  282. let over = anonOrder.length - anonMax
  283. let keep = []
  284. let n = 0
  285. for (id of anonOrder) {
  286. let s = map[id]
  287. if (s == null || s.user != null) { continue }
  288. if (n < over) {
  289. drop(id)
  290. map[id] = null
  291. n = n + 1
  292. } else {
  293. keep.push(id)
  294. }
  295. }
  296. anonOrder = keep
  297. return null
  298. }
  299. // ONE WRITE PATH for the stamp: every request or frame that presents a session
  300. // moves `seen`; the file follows only when it has drifted `stampDrift` seconds
  301. touch(s) {
  302. refresh(s)
  303. s.seen = now()
  304. if (dir != null && s.id != null) {
  305. let last = persistedSeen[s.id]
  306. if (last == null || s.seen - last >= stampDrift * 1000) { put(s) }
  307. }
  308. return null
  309. }
  310. // what a face wrote (login, a cart) reaches the file now, not at the next drift
  311. save(s) {
  312. if (s != null && s.id != null && map[s.id] != null) { put(s) }
  313. return null
  314. }
  315. // The store pass and cold lookup share the login/anonymous validity clocks.
  316. expired(Hybrid rec, Number at) {
  317. return rec.seen <= at - (rec.user != null ? maxAge : anonKeep) * 1000
  318. }
  319. // ---- the sweep -------------------------------------------------------------------
  320. // `live` is the set of session ids with an open socket — those are never evicted
  321. maybeSweep(live) {
  322. let listed = false
  323. if (now() - lastSweep >= sweepEvery * 1000) { listed = sweep(live) }
  324. if (queue != null && !listed) { storeSlice() } // the request that listed the directory does no slice too
  325. return null
  326. }
  327. sweep(live) {
  328. lastSweep = now()
  329. let cutoff = now() - maxAge * 1000
  330. let cold = now() - idle * 1000
  331. let evicted = 0
  332. let expired = 0
  333. let next = {}
  334. for (k of map.keys()) {
  335. let s = map[k]
  336. if (s == null) {
  337. // dropped earlier
  338. } else if (s.seen <= cutoff && !(refresh(s) && s.seen > cutoff)) {
  339. drop(k)
  340. expired = expired + 1
  341. } else if (dir != null && s.seen <= cold && !live.includes(k)) {
  342. persistedSeen[k] = null
  343. evicted = evicted + 1
  344. } else {
  345. next[k] = s
  346. }
  347. }
  348. map = next // a fresh hybrid: the compaction (archive, mission 261)
  349. if (evicted + expired > 0) {
  350. console.log('sessions: sweep — evicted ' + evicted + ', expired ' + expired + ', ' + map.keys().length + ' resident')
  351. }
  352. // a new pass over the files on disk starts when none runs and the last began long enough ago
  353. if (dir != null && queue == null && exists(dir) && now() - lastPass >= sweepEvery * 12000) { return startPass() }
  354. return false
  355. }
  356. startPass() {
  357. if (dir == null || queue != null || !exists(dir)) { return false }
  358. lastPass = now()
  359. queue = []
  360. qListed = 0
  361. for (e of listDir(dir)) {
  362. qListed = qListed + 1
  363. if (!isSessionName(e.name) || e.type != 'file') { foreign(e) } else { queue.push(e.name) }
  364. }
  365. qi = 0
  366. qGone = 0
  367. return true
  368. }
  369. // W179: ONE SLICE of the store pass, as many files as fit in `slice` milliseconds, then the request goes on.
  370. // A file whose change time is newer than the shortest clock is skipped without being read. Of the others:
  371. // a session with a user goes when its `seen` is past `maxAge`; every anonymous session goes
  372. // when older than `anonKeep`, including one with app data. A resident session is never touched.
  373. storeSlice() {
  374. let t0 = now()
  375. let young = t0 - (anonKeep < maxAge ? anonKeep : maxAge) * 1000
  376. let n = queue.length
  377. let done = 0
  378. while (qi < n && (done % 64 != 63 || now() - t0 < slice)) {
  379. name = queue[qi]
  380. queue[qi] = null // release the processed filename while the rest of the pass waits
  381. qi = qi + 1
  382. done = done + 1
  383. p = dir + '/' + name
  384. st = stat(p)
  385. raw = st != null && st.mtime <= young ? readFile(p) : null
  386. if (raw != null && isSessionText(raw)) {
  387. rec = JSON.parse(raw)
  388. dead = expired(rec, t0)
  389. if (dead && map[rec.id] == null) {
  390. remove(p)
  391. persistedSeen[rec.id] = null
  392. qGone = qGone + 1
  393. }
  394. }
  395. }
  396. if (qi >= n) {
  397. console.log('sessions: store pass done — ' + qListed + ' file(s) looked at, ' + qGone + ' removed')
  398. queue = null
  399. }
  400. return null
  401. }
  402. // ---- what the store holds that is not a session -----------------------------------
  403. // A FILE THAT IS NOT A SESSION IS SKIPPED, NEVER PARSED. The store is a directory an
  404. // operator can put anything into (a marker, an editor's backup, a copy), and
  405. // `JSON.parse` aborts the program on text that is not JSON — at the boot sweep that was
  406. // the whole server, before it served anything (ticket #26). Every file this layer
  407. // writes is named by a sha256 (64 lowercase hex characters) and holds a Session's JSON,
  408. // 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
  409. // finished temp file over the target, so a torn session file cannot occur. A file that
  410. // is not that shape is left where it is, and said once.
  411. isSessionName(name) {
  412. if (name.length != 64) { return false }
  413. for (c of name.split('')) {
  414. if (!'0123456789abcdef'.includes(c)) { return false }
  415. }
  416. return true
  417. }
  418. isSessionText(raw) {
  419. let t = raw.trim()
  420. return t.startsWith('{"') && t.endsWith('}') && t.includes('"created":') && t.includes('"seen":')
  421. }
  422. foreign(e) {
  423. if (reported[e.path] == null) {
  424. reported[e.path] = true
  425. 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')
  426. }
  427. return null
  428. }

Branches

Latest commits

  • 10f8a8c8Merge branch 'code-order' into mainJukebox
  • 204fc828Merge branch 'day72' into mainJukebox
  • 95f5faae|||PR jukebox#7 Drop needless let declarationsmre
  • 33072bb5|||PR Record day72 gates and Chrome proofmre
  • 95f2cd73|||PR Use typed parent methods for screen playback and local server facesmre
  • 6422a020Sync media-player at 51c3818mre
  • b582ba1cVendor complete Hybriel day72 plugin setmre
  • 02dccbc9Merge branch 'records-1119' into mainJukebox
  • a39e1c23|||PR Records: missions 013-015, reconnect fix livemre
  • fc7db075Merge branch 'reconnect-retry' into mainJukebox
  • ac6f4c6fL2: plain declaration for a in pickedNextmre
  • 2f335086Review round 2: only an explicit queue pick drops pend (not the automatic advance); jb23 records every source changemre
  • 3eb6695fReview fixes: action generation, queue pick clears pend, Previous/Next retry the decided request, typed handlersmre
  • 7a53c0c2|||PR A tap lost to a dead socket plays after reconnect (mission 015)mre
  • 1f0cd77bMerge branch 'records-day41' into mainJukebox
  • 67be229f|||PR Records: day41 live (PR #4), mission 012, statusmre
  • 0bb027daconductor: caramboleyo is the user, not owner/creatorApollo
  • 04f5d9d5Merge branch 'day41' into mainJukebox
  • 8ed6da45|||PR README: media-player pin df9e7dfmre
  • d5d45fc3|||PR media-player df9e7df (repeat-one fix), sync pin and SOURCEmre