gitoria

ident

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commita4887ea3a4887ea3ident#47: the selector's sign-in frame no longer has a Continue button; the identity row itself is the link (gate tests/signin.mjs fails on the old code)mrea4887ea3/plugins/web/sessions.hl

15.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, 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 signed-in 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 last issued more than a day ago (Chrome caps a
  151. // cookie's lifetime at 400 days, and logins do not expire). Anonymous sessions are not refreshed.
  152. due(s, https) {
  153. if (s == null || s.id == null || s.user == null) { return false }
  154. let sec = secure == null ? https == true : secure
  155. return s.issuedSig != signature(sec) || now() - s.issuedAt >= 86400000
  156. }
  157. // ---- the map ---------------------------------------------------------------------
  158. // the session a cookie header names: resident, or revived from its file; null when
  159. // it names none (no cookie, or an id nobody knows — that browser is anonymous)
  160. resolve(cookieHeader) {
  161. let ids = cookieValues(cookieHeader)
  162. if (ids.length == 0) { return null }
  163. if (ids.length == 1) { return byId(ids[0]) }
  164. // W137 (gitoria#24): a browser can hold two cookies of the session's name (an old host-only one and a
  165. // newer one with the Domain) and sends both. The first that belongs to a signed-in session wins, else
  166. // the first that belongs to any known session, else none.
  167. let first = null
  168. for (id of ids) {
  169. let s = lookup(id)
  170. if (s == null) { continue }
  171. if (s.user != null) { first = s break }
  172. if (first == null) { first = s }
  173. }
  174. if (first == null) { return null }
  175. touch(first)
  176. return first
  177. }
  178. // every value the Cookie header carries under the session's name, in the order sent
  179. cookieValues(header) {
  180. let out = []
  181. if (header == null) { return out }
  182. for (part of header.split(';')) {
  183. let eq = part.indexOf('=')
  184. if (eq > 0 && part.slice(0, eq).trim() == cookie) { out.push(part.slice(eq + 1).trim()) }
  185. }
  186. return out
  187. }
  188. // W137: the extra headers an answer carries when the request held the session's name more than once and
  189. // `s` is the session chosen among them: the chosen id again with the app's cookie attributes (Domain
  190. // included) under 'Set-Cookie', and, only when the app's cookie has a Domain, a host-only expiry under
  191. // 'set-cookie' (a second header line: the server writes one line per key, and the two keys differ in
  192. // case only). Without a Domain the expiry would delete the chosen cookie itself.
  193. repair(cookieHeaderText, s, https) {
  194. let out = {}
  195. if (s == null || s.id == null) { return out }
  196. let many = cookieValues(cookieHeaderText).length > 1
  197. if (!many && !due(s, https)) { return out }
  198. out['Set-Cookie'] = cookieHeader(s.id, https)
  199. if (many && domain != '') { out['set-cookie'] = expiry(https) }
  200. return out
  201. }
  202. // the same name, no Domain, gone at once: removes a stray host-only cookie
  203. expiry(https) {
  204. let sec = secure == null ? https == true : secure
  205. return cookie + '=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0' + (sec ? '; Secure' : '')
  206. }
  207. // for /__hl/adopt, which sets a new id and chooses nothing: the host-only strays are expired so the new
  208. // cookie is the only one of its name
  209. strays(cookieHeaderText, https) {
  210. let out = {}
  211. if (domain != '' && cookieValues(cookieHeaderText).length > 1) { out['set-cookie'] = expiry(https) }
  212. return out
  213. }
  214. byId(sid) {
  215. let s = lookup(sid)
  216. if (s == null) { return null }
  217. touch(s)
  218. return s
  219. }
  220. lookup(sid) {
  221. if (sid == null) { return null }
  222. let s = map[sid]
  223. if (s == null) { s = load(sid) } else { refresh(s) }
  224. return s
  225. }
  226. // SESSIONS ARE LAZY (W124): a visitor with no cookie has NO session — `fresh()` hands a transient
  227. // one (no id, not in the map, nothing on disk) that a page renders with or a face writes to. Only a
  228. // session that GOT something (a login, `data`, an upload) is `adopt`ed: it gets its id, goes into the
  229. // map and onto disk, and the caller sets the cookie. A flood of cookie-less requests so costs nothing,
  230. // and the anonymous ones that were adopted are capped (`anonMax`, oldest first).
  231. fresh() {
  232. return new HlwSession(created = now(), seen = now())
  233. }
  234. // A NEW SESSION WITH AN ID, in the map and on disk (the call W124 removed and apps used): `adopt(fresh())`.
  235. // The caller sets the cookie (`cookieHeader(s.id)`).
  236. mint() {
  237. return adopt(fresh())
  238. }
  239. // does the session hold anything worth a cookie and a file?
  240. hasContent(s) {
  241. return s != null && (s.user != null || s.data.keys().length > 0)
  242. }
  243. adopt(s) {
  244. maybeSweep([])
  245. if (s.id == null) { s.id = randomToken(32) }
  246. map[s.id] = s
  247. put(s)
  248. if (s.user == null) {
  249. anonOrder.push(s.id)
  250. if (anonOrder.length > anonMax) { evictAnon() }
  251. }
  252. return s
  253. }
  254. // ROTATE (W120): the session `s` gets a NEW id — its user, data and handled list move with it
  255. // (it is the same record, only the id changes), the old id's file and memory entry are deleted so a
  256. // planted id is anonymous from now on. Answers the old id. The caller tells the browser (cookie).
  257. move(s) {
  258. let old = s.id
  259. let sid = randomToken(32)
  260. map[old] = null
  261. drop(old)
  262. s.id = sid
  263. s.rotating = false
  264. s.seen = now()
  265. map[sid] = s
  266. put(s)
  267. let i = anonOrder.indexOf(old)
  268. if (i >= 0) { anonOrder[i] = sid }
  269. return old
  270. }
  271. // an upload (no content yet) is adopted at once; a face's session only when hasContent()
  272. evictAnon() {
  273. let over = anonOrder.length - anonMax
  274. let keep = []
  275. let n = 0
  276. for (id of anonOrder) {
  277. let s = map[id]
  278. if (s == null || s.user != null) { continue }
  279. if (n < over) {
  280. drop(id)
  281. map[id] = null
  282. n = n + 1
  283. } else {
  284. keep.push(id)
  285. }
  286. }
  287. anonOrder = keep
  288. return null
  289. }
  290. // ONE WRITE PATH for the stamp: every request or frame that presents a session
  291. // moves `seen`; the file follows only when it has drifted `stampDrift` seconds
  292. touch(s) {
  293. refresh(s)
  294. s.seen = now()
  295. if (dir != null && s.id != null) {
  296. let last = persistedSeen[s.id]
  297. if (last == null || s.seen - last >= stampDrift * 1000) { put(s) }
  298. }
  299. return null
  300. }
  301. // what a face wrote (login, a cart) reaches the file now, not at the next drift
  302. save(s) {
  303. if (s != null && s.id != null && map[s.id] != null) { put(s) }
  304. return null
  305. }
  306. // ---- the sweep -------------------------------------------------------------------
  307. // `live` is the set of session ids with an open socket — those are never evicted
  308. maybeSweep(live) {
  309. if (now() - lastSweep >= sweepEvery * 1000) { sweep(live) }
  310. return null
  311. }
  312. sweep(live) {
  313. lastSweep = now()
  314. let cutoff = now() - maxAge * 1000
  315. let cold = now() - idle * 1000
  316. let evicted = 0
  317. let expired = 0
  318. let next = {}
  319. for (k of map.keys()) {
  320. let s = map[k]
  321. if (s == null) {
  322. // dropped earlier
  323. } else if (s.seen <= cutoff && !(refresh(s) && s.seen > cutoff)) {
  324. drop(k)
  325. expired = expired + 1
  326. } else if (dir != null && s.seen <= cold && !live.includes(k)) {
  327. persistedSeen[k] = null
  328. evicted = evicted + 1
  329. } else {
  330. next[k] = s
  331. }
  332. }
  333. map = next // a fresh hybrid: the compaction (archive, mission 261)
  334. let dropped = 0
  335. if (dir != null) { dropped = sweepStore(cutoff) }
  336. if (evicted + expired + dropped > 0) {
  337. console.log('sessions: sweep — evicted ' + evicted + ', expired ' + expired + ', ' + dropped + ' file(s) removed, ' + map.keys().length + ' resident')
  338. }
  339. return null
  340. }
  341. sweepStore(cutoff) {
  342. let gone = 0
  343. if (!exists(dir)) { return gone }
  344. for (e of listDir(dir)) {
  345. let raw = isSessionName(e.name) && e.type == 'file' ? readFile(e.path) : null
  346. if (raw != null && !isSessionText(raw)) { raw = null }
  347. if (raw == null) { foreign(e) }
  348. if (raw != null) {
  349. let rec = JSON.parse(raw)
  350. if (rec != null && rec.seen <= cutoff) {
  351. remove(e.path)
  352. persistedSeen[rec.id] = null
  353. gone = gone + 1
  354. }
  355. }
  356. }
  357. return gone
  358. }
  359. // ---- what the store holds that is not a session -----------------------------------
  360. // A FILE THAT IS NOT A SESSION IS SKIPPED, NEVER PARSED. The store is a directory an
  361. // operator can put anything into (a marker, an editor's backup, a copy), and
  362. // `JSON.parse` aborts the program on text that is not JSON — at the boot sweep that was
  363. // the whole server, before it served anything (ticket #26). Every file this layer
  364. // writes is named by a sha256 (64 lowercase hex characters) and holds a Session's JSON,
  365. // 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
  366. // finished temp file over the target, so a torn session file cannot occur. A file that
  367. // is not that shape is left where it is, and said once.
  368. isSessionName(name) {
  369. if (name.length != 64) { return false }
  370. for (c of name.split('')) {
  371. if (!'0123456789abcdef'.includes(c)) { return false }
  372. }
  373. return true
  374. }
  375. isSessionText(raw) {
  376. let t = raw.trim()
  377. return t.startsWith('{"') && t.endsWith('}') && t.includes('"created":') && t.includes('"seen":')
  378. }
  379. foreign(e) {
  380. if (reported[e.path] == null) {
  381. reported[e.path] = true
  382. 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')
  383. }
  384. return null
  385. }

Branches

Latest commits

  • a4887ea3ident#47: the selector's sign-in frame no longer has a Continue button; the identity row itself is the link (gate tests/signin.mjs fails on the old code)mre
  • d8ec703dident#45: /docs shows docs/IDENT.md (hl:markdown, vendored from ac1ed9da), one Docs entry in the main menu, README for developers only, gates tests/docs.mjs and tests/sessionwrites.mjs in deploy.shmre
  • ec6aad35Merge branch 'a28g-amp-callsites' into d45-docsmre
  • 6bfbd3f2ident#45: docs/IDENT.md, what ident is and how it works; CONCEPT.md marks one id per app as droppedmre
  • c0edca26ident#28 A28G: write & at every call that hands a session to an &-parameter; gate tests/sessionwrites.mjs pins that sign-in, pending address, embed sign-in and selector land in the session filesmre
  • 80965c08ident#28: README says the deploy goes through the standbymre
  • 2f41670cident#28: ident-standby service on port 45012 (no background round in the standby) and deploy.sh hands over through standby-swap.shmre
  • a544b261ident#28: README names the new vendored Hybrielmre
  • 716860b0ident#28: gates follow Hybriel ac1ed9da (lazy sessions, meta attribute order, JSON key order, default X-Frame-Options switched off for the embed page)mre
  • 889e00fbident#28: Hybriel master ac1ed9da (sessions reload a newer file, a replayed reconnect carries the server session); a startup fault exits 1 (on Error)mre
  • f5a55f8aident#11: apps can ask for nickname, firstname and lastname (fields list on /api/exchange, new POST /api/profile); empty fields come back null; gate checks, READMEmre
  • d8be66ebident: report and log line for the widget cache and frame height changemre
  • 2068f61aident#31: browsers revalidate the widget scripts on every load; the sign-in frame is exactly as tall as the current step (the frame page reports its height, selector.js accepts it from ident only)mre
  • a22d2daaident#31: the sign-in frame is no taller than the tallest step needs (plain CSS height per width), gate check for itmre
  • a77d1b22ident#31: the welcome form keeps editId a plain value (browser gate), README, wider rows in the framemre
  • 5c481bfdident#31: sign in to ident inside the selector's panel (email, code, identity in an iframe; a new address goes to ident in the same tab and comes back)mre
  • 061abfe2ident: the apps gate waits until the test app's login button stops moving before it clicks (the page grows after load and the click missed about every second run)mre
  • 45f7e4daident: the user menu's Sign out waits for the server before it reloads (the apps gate failed because the session could still be signed in)mre
  • f07658c7ident: home page shows the account once (account bar removed, the user menu carries email, Sign out, Sign out everywhere); wildcard origins https://*.domain for apps on many subdomains; gates follow (WIP: gates not re-run after the last edits)mre
  • f2c43bbbtheme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre