gitoria

tracker

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitf567f025f567f025|||PR records: park #55, no Claude workers ruleTrackerf567f025/plugins/web/sessions.hl

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

Branches

Latest commits

  • f567f025|||PR records: park #55, no Claude workers ruleTracker
  • c21aff6bMerge branch 'records-hm55c' into mainTracker
  • 9ba258d3|||PR records: HM55b resultTracker
  • 64f2d300Merge branch 'records-hm55b2' into mainTracker
  • ae3b80dc|||PR records: HM55b briefTracker
  • 7ef3cb3bMerge branch 'records-st55' into mainTracker
  • fec2e080|||PR records: STATUS HM55Tracker
  • 8e174918Merge branch 'records-hm55b' into mainTracker
  • b1ecee57|||PR records: HM55 stateTracker
  • 28eab08cMerge branch 'records-hm55' into mainTracker
  • d3edaa05|||PR records: HM55 start, PROCEDURES.mdTracker
  • 3059f86cMerge branch 'records-design-rule' into mainTracker
  • 421a4809|||PR records: his-design rule (Apollo 2026-11-13)Tracker
  • d1390692Merge branch 'records-dp75b' into mainTracker
  • a4d1a7d2|||PR records: later steps checked, branch auditTracker
  • e070e16fMerge branch 'records-dp75' into mainTracker
  • 642b4fa8|||PR records: DP75 day62 live, AP62 briefTracker
  • bfc4ea4dMerge branch 'ap62' into mainTracker
  • 2c95ac46|||PR AP62: re-vendor Hybriel set day62 (source 70341ad2, bin a54f5f08)Tracker
  • b9c7c3c8Merge branch 'records-dp74' into mainTracker