gitoriaLog in with ident

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit1ca2f34d1ca2f34dantcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre1ca2f34d/project.hl

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

Branches

Latest commits

  • 1ca2f34dantcolony#40: history (LOG.md), worker briefs (missions/) and reports moved here from antcolony, numbered per project; old numbers in antcolony docs/mission-map.mdmre
  • 2bebebdanotes: Hybriel master ff51cf46 (re-vendor round)mre
  • 3eff126dnotes#3: installable app (manifest + own icon/favicon; notes' own sw.js kept)mre
  • 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