gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit48c1ba7948c1ba79tickets: md-paste-files gate with the file manager casesmre48c1ba79/plugins/web/sessions.hl

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

Branches

Latest commits

  • 48c1ba79tickets: md-paste-files gate with the file manager casesmre
  • f04afc43tickets: MdEditor from components 59704ce (a file manager copy still attaches, pipe rows, tickets#49)mre
  • 06599fa0tickets: MdEditor from components b0f1ec2 (a clipboard with text always pastes the text, tickets#49); real Ctrl+V gatemre
  • 2e1b116ftickets: re-vendor Hybriel master acaceaf3 (framework ec8d6c1d): plugins/web patch queue while a page is built, anonymous session cookies refresh; gate waits for the comment editors to draw (W174) and clicks the form editor when it stands still; security gate: main's code runs on its own binary, lazy-session cookie checksmre
  • 361bc0fetickets: re-vendor Hybriel 7a684920 (WIP, not deployed); on Error exits 1 at startup; migrate passes its log by reference; gate checks follow lazy sessions and the 413 refusalmre
  • 8a69999cident#28: /login/callback never signs out the session it finds; a valid code puts the user on the same sessionmre
  • 337e9b21tickets#37: a comment's files are open to everyone who can read the commentmre
  • 1800600ftickets: write the standby service out in full so the boot gate can read the main servicemre
  • 8179d287tickets: standby service on its port plus 10 and a deploy that hands over through it without a gapmre
  • 0398145ctickets: the table grid rule is marked functional for check-thememre
  • 40fddc20tickets takes components e54f83a: tables get thin grey lines from the theme, desktop toolbar stays one row with the Table button, F4 check counts 11 buttonsmre
  • c1b77d61tickets#35: text typed before the editor is built is taken in once by the build (the input handler no longer writes it to the field first, which doubled the first letters); the gate failure shows the surfacemre
  • 32bf1873tickets#35: the gate types right after the load with the CPU slowed, no waitingmre
  • 64ea9ca2tickets#35: text typed into the reply editor before the page has finished starting is kept; the gate types right after loadmre
  • ccd3a327tickets: the security gate expects frame-src to be exactly the ident address (the sign-in frame), still no wildcard or selfmre
  • 4348dbabident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
  • 66ef3005Merge branch 'iw-ident-widget'mre
  • bc0ad663tickets: a gap between your name and Log out in the phone header (they touched); gate checks itmre
  • 2f818d46UX2: report, LOG line, e2e fixes, gate pause after loadmre
  • af3ef7c4gate: the legacy state line says progressmre