gitoriaLog in with ident

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit9883c5409883c540deploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre9883c540/project.hl

8.1 KB

  1. // project.hl — notes.worldapi.org: THE APP. Routes and WHO HEARS WHAT. Hybriel on hl:web.
  2. // Notes with an ident login (ticket notes#1): a sidebar of the user's notes (subject = first line, last edited
  3. // first) and the selected note on the right, edited with <md-editor> (shared/md-editor.js, vendored from
  4. // worldapi-components). Saved on the server in storage/mpackdb/. Offline use is ticket notes#2.
  5. import WebFramework from 'hl:web'
  6. import { env } from 'hl:proc'
  7. import { Response } from 'hl:http1'
  8. import { randomBytes } from 'hl:crypto'
  9. import Styles from './styles.hl'
  10. import { exchangeCode, ensureUser, userIdOfSession } from './users.hl'
  11. import { metaRows, noteView, pushNote, removeNote } from './notes.hl'
  12. import { jsonErrorAt } from './jsoncheck.hl'
  13. import Notes from './components/notes.hl'
  14. import LoginFailed from './components/loginfailed.hl'
  15. static siteName = "notes"
  16. appTitle = siteName
  17. styles = Styles
  18. // ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident") ----------------------------
  19. // BACK TO THE PAGE: /login.js puts `?next=` into the button's return URL at the click. Only a same-origin PATH
  20. // goes (one `/`, URL-safe characters, ≤ 500). Anything else → `/`.
  21. nextChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;@!$()*:'
  22. safePath = (want) => {
  23. if (want == null || hlTypeName(want) != 'String' || want == '' || want.length > 500) { return '/' }
  24. if (want.slice(0, 1) != '/' || want.slice(0, 2) == '//' || want.slice(0, 7) == '/login/') { return '/' }
  25. let i = 0
  26. while (i < want.length) {
  27. if (!nextChars.includes(want[i])) { return '/' }
  28. i = i + 1
  29. }
  30. return want
  31. }
  32. // A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked in the session, then → /login/failed
  33. failed = (req, why) => {
  34. let s = req.session
  35. let fresh = s == null
  36. if (fresh) { s = server.sessions.mint() }
  37. s.data.loginError = why
  38. server.sessions.save(s)
  39. let res = new Response('login failed: ' + why, { status = 302 headers = { 'Location' = '/login/failed' 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })
  40. if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }
  41. return res
  42. }
  43. // the function route gets the cookie's session as req.session (hybriel #11); none yet → minted here
  44. loginCallback = (route, req) => {
  45. if (req.method != 'GET') { return failed(req, 'GET only') }
  46. let q = req.query != null ? req.query : {}
  47. let code = q.ident_code
  48. if (code == null || code == '') { return failed(req, 'ident sent no login code') }
  49. let x = exchangeCode(code)
  50. if (x.error != null) { return failed(req, x.error) }
  51. let u = ensureUser(x.identity)
  52. if (u == null) { return failed(req, 'could not store the user') }
  53. let s = req.session
  54. let fresh = s == null
  55. if (fresh) { s = server.sessions.mint() }
  56. s.user = { id = u.id }
  57. s.data.tag = randomBytes(16)
  58. s.data.loginError = null
  59. server.sessions.save(s)
  60. let res = new Response('logged in', { status = 302 headers = { 'Location' = safePath(q.next) 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })
  61. if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }
  62. return res
  63. }
  64. // ---- THE SYNC API (ticket notes#2): what the browser's offline copy talks to. JSON, the session cookie is the login.
  65. // GET /api/me → { user } (an opaque id of the signed-in user, or null)
  66. // GET /api/notes → { notes: [{ id, edited, gone }] } every note of the user, tombstones included
  67. // GET /api/notes?id=<id> → { id, text, edited, created }
  68. // POST /api/notes { op: 'save', id, local, text, base, at } → { id, edited, text, copy? }
  69. // POST /api/notes { op: 'delete', id, base } → { ok } | { kept, id, edited, text }
  70. // Invalid JSON is refused by jsoncheck.hl before JSON.parse sees it (hybriel #6); unknown/mistyped fields → 400.
  71. apiHeaders = { 'Content-Type' = 'application/json; charset=utf-8' 'Cache-Control' = 'no-store' }
  72. reply = (status, value) => { return new Response(JSON.stringify(value), { status = status headers = apiHeaders }) }
  73. isText = (v) => { return v != null && hlTypeName(v) == 'String' }
  74. isTime = (v) => { return v != null && hlTypeName(v) == 'Number' && v >= 0 }
  75. apiMe = (route, req) => {
  76. let u = userIdOfSession(req.session)
  77. return reply(200, { user = u })
  78. }
  79. apiNotes = (route, req) => {
  80. let u = userIdOfSession(req.session)
  81. if (u == null) { return reply(401, { error = 'log in with ident first' }) }
  82. let q = req.query != null ? req.query : {}
  83. if (req.method == 'GET') {
  84. if (q.id != null) {
  85. let v = noteView(u, q.id)
  86. if (v == null) { return reply(404, { error = 'no such note' }) }
  87. return reply(200, v)
  88. }
  89. return reply(200, { notes = metaRows(u) })
  90. }
  91. if (req.method != 'POST') { return reply(405, { error = 'GET or POST only' }) }
  92. if (req.body == null || req.body == '') { return reply(400, { error = 'a JSON body is needed' }) }
  93. let at = jsonErrorAt(req.body)
  94. if (at >= 0) { return reply(400, { error = 'invalid JSON at character ' + at }) }
  95. let b = JSON.parse(req.body)
  96. if (b == null || hlTypeName(b) != 'Hybrid') { return reply(400, { error = 'the body must be a JSON object' }) }
  97. if (b.op == 'save') {
  98. if (!isText(b.id) || !isText(b.local) || !isText(b.text) || !isTime(b.base) || !isTime(b.at)) { return reply(400, { error = 'save needs id, local, text (strings) and base, at (numbers)' }) }
  99. if (b.local.length > 64 || b.id.length > 64) { return reply(400, { error = 'id / local too long' }) }
  100. let r = pushNote(u, b.id, b.local, b.text, b.base, b.at)
  101. if (r.error != null) { return reply(400, r) }
  102. return reply(200, r)
  103. }
  104. if (b.op == 'delete') {
  105. if (!isText(b.id) || !isTime(b.base)) { return reply(400, { error = 'delete needs id (string) and base (number)' }) }
  106. return reply(200, removeNote(u, b.id, b.base))
  107. }
  108. return reply(400, { error = "op must be 'save' or 'delete'" })
  109. }
  110. routes = [
  111. { pattern = "/favicon.ico" direct = "" }
  112. { pattern = "/login/callback" function = loginCallback }
  113. { pattern = "/login/failed" component = LoginFailed }
  114. { pattern = "/login.js" file = "./login.js" headers = { 'Cache-Control' = 'no-cache' } }
  115. // the Markdown editor <md-editor>, vendored from worldapi-components (one <script> in the shell would do too:
  116. // it is loaded by the page component's parent, see components/main.hl)
  117. { pattern = "/md-editor.js" file = "./shared/md-editor.js" headers = { 'Cache-Control' = 'no-cache' } }
  118. { pattern = "/api/me" function = apiMe }
  119. { pattern = "/api/notes" function = apiNotes }
  120. // the offline copy: the service worker (network first, the cached page when there is none) and the client that
  121. // keeps the notes in IndexedDB and syncs them
  122. { pattern = "/sw.js" file = "./sw.js" headers = { 'Cache-Control' = 'no-cache' } }
  123. { pattern = "/notes-offline.js" file = "./notes-offline.js" headers = { 'Cache-Control' = 'no-cache' } }
  124. { pattern = "/" component = Notes }
  125. { pattern = "/note/:id" component = Notes }
  126. ]
  127. // WHO GETS THE PUSH: the login state reaches the tabs of one session. (Notes are not pushed: the browser's own copy
  128. // pulls through /api/notes.)
  129. // `notesSignedIn` / `notesSignedOut` go to the tabs of ONE session: the one whose login carries that random tag.
  130. tagOf = (session) => { return session != null && session.data != null ? session.data.tag : null }
  131. audience = {
  132. notesSignedIn = (tag, session) => { return tag != null && tagOf(session) == tag }
  133. notesSignedOut = (tag, session) => { return tag != null && tagOf(session) == tag }
  134. }
  135. sessionDir = env('NOTES_SESSIONS') != null ? env('NOTES_SESSIONS') : null
  136. port = env('NOTES_PORT') != null ? toNumber(env('NOTES_PORT')) : 8710
  137. // HL_HOST = the interface hl:web binds: 127.0.0.1 on Byrodin behind nginx; unset = 0.0.0.0 (dev on Loreana).
  138. // NOTES_WATCH=0 = no dev watcher. The session cookie is `notessid` (hybriel #10). A note taker is not logged
  139. // out after 15 minutes of thinking: the session idles out after the 14 days of sessionMaxAge.
  140. watching = env('NOTES_WATCH') != '0'
  141. sessionCookie = 'notessid'
  142. sessionIdle = 1209600
  143. server = new WebFramework(routes = routes, styles = styles, minify = true, port = port, watchMode = watching, sessionCookie = sessionCookie)
  144. on Error(e) { console.log('error absorbed: ' + e.message) }

Branches

Latest commits

  • 9883c540deploy.sh: back up live storage/.sessions/.env before every deploy (newest 5 kept)mre
  • eee693b8deploy.sh: never send .git or .gitignore to Byrodinmre
  • c8904061State of 2026-09-27, before the move to gitoriamre