notes
All repositories: gitoria
9.9 KB
// project.hl — notes.worldapi.org: THE APP. Routes and WHO HEARS WHAT. Hybriel on hl:web.// Notes with an ident login (ticket notes#1): a sidebar of the user's notes (subject = first line, last edited// first) and the selected note on the right, edited with <md-editor> (shared/md-editor.js, vendored from// worldapi-components). Saved on the server in storage/mpackdb/. Offline use is ticket notes#2.import WebFramework from 'hl:web'import { env } from 'hl:proc'import { Response } from 'hl:http1'import { randomBytes } from 'hl:crypto'import Styles from './styles.hl'import { exchangeCode, ensureUser, userIdOfSession } from './users.hl'import { metaRows, noteView, pushNote, removeNote } from './notes.hl'import { jsonErrorAt } from './jsoncheck.hl'import { dark, darker } from './shared/tokens.hl'import Notes from './components/notes.hl'import LoginFailed from './components/loginfailed.hl'static siteName = "notes"appTitle = siteName// ---- THE INSTALLABLE APP (mission 046), as calendar.worldapi.org / tracker do it: hl:web's own web app manifest// (/__hl/manifest.webmanifest, linked from every head with the apple-touch-icon and theme-color) from these settings.// Icons in icons/ (icon.svg is the source, the PNGs are rendered from it with rsvg-convert, README "PWA"). The theme// colour is the header's background (darker), the splash background the page's (dark) — both off the tokens.// NO `offline = [...]` here ON PURPOSE: that would make hl:web register its own service worker (/__hl/sw.js, scope /)// over notes' own /sw.js (notes-offline.js registers it, same scope) — one would replace the other. Notes keeps its// own offline copy (sw.js + IndexedDB, ticket notes#2) until notes#4 moves it to Hybriel.appThemeColor = darker.valueappBackgroundColor = dark.valueappIcons = [{ src = '/icons/icon-192.png' sizes = '192x192' purpose = 'any' }{ src = '/icons/icon-512.png' sizes = '512x512' purpose = 'any' }{ src = '/icons/icon-192.png' sizes = '192x192' purpose = 'maskable' }{ src = '/icons/icon-512.png' sizes = '512x512' purpose = 'maskable' }]appTouchIcon = '/icons/apple-touch-icon.png'appFavicon = '/icons/favicon.svg'styles = Styles// ---- THE LOGIN BUTTON'S RETURN (ident README "How apps use ident") ----------------------------// BACK TO THE PAGE: /login.js puts `?next=` into the button's return URL at the click. Only a same-origin PATH// goes (one `/`, URL-safe characters, ≤ 500). Anything else → `/`.nextChars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-._~/?&=%+,;@!$()*:'safePath = (want) => {if (want == null || hlTypeName(want) != 'String' || want == '' || want.length > 500) { return '/' }if (want.slice(0, 1) != '/' || want.slice(0, 2) == '//' || want.slice(0, 7) == '/login/') { return '/' }let i = 0while (i < want.length) {if (!nextChars.includes(want[i])) { return '/' }i = i + 1}return want}// A FAILED LOGIN is a page (components/loginfailed.hl): the reason is parked in the session, then → /login/failedfailed = (req, why) => {let s = req.sessionlet fresh = s == nullif (fresh) { s = server.sessions.mint() }s.data.loginError = whyserver.sessions.save(s)let res = new Response('login failed: ' + why, { status = 302 headers = { 'Location' = '/login/failed' 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }return res}// the function route gets the cookie's session as req.session (hybriel #11); none yet → minted hereloginCallback = (route, req) => {if (req.method != 'GET') { return failed(req, 'GET only') }let q = req.query != null ? req.query : {}let code = q.ident_codeif (code == null || code == '') { return failed(req, 'ident sent no login code') }let x = exchangeCode(code)if (x.error != null) { return failed(req, x.error) }let u = ensureUser(x.identity)if (u == null) { return failed(req, 'could not store the user') }let s = req.sessionlet fresh = s == nullif (fresh) { s = server.sessions.mint() }s.user = { id = u.id }s.data.tag = randomBytes(16)s.data.loginError = nullserver.sessions.save(s)let res = new Response('logged in', { status = 302 headers = { 'Location' = safePath(q.next) 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' } })if (fresh) { res.headers['Set-Cookie'] = server.sessions.cookieHeader(s.id) }return res}// ---- THE SYNC API (ticket notes#2): what the browser's offline copy talks to. JSON, the session cookie is the login.// GET /api/me → { user } (an opaque id of the signed-in user, or null)// GET /api/notes → { notes: [{ id, edited, gone }] } every note of the user, tombstones included// GET /api/notes?id=<id> → { id, text, edited, created }// POST /api/notes { op: 'save', id, local, text, base, at } → { id, edited, text, copy? }// POST /api/notes { op: 'delete', id, base } → { ok } | { kept, id, edited, text }// Invalid JSON is refused by jsoncheck.hl before JSON.parse sees it (hybriel #6); unknown/mistyped fields → 400.apiHeaders = { 'Content-Type' = 'application/json; charset=utf-8' 'Cache-Control' = 'no-store' }reply = (status, value) => { return new Response(JSON.stringify(value), { status = status headers = apiHeaders }) }isText = (v) => { return v != null && hlTypeName(v) == 'String' }isTime = (v) => { return v != null && hlTypeName(v) == 'Number' && v >= 0 }apiMe = (route, req) => {let u = userIdOfSession(req.session)return reply(200, { user = u })}apiNotes = (route, req) => {let u = userIdOfSession(req.session)if (u == null) { return reply(401, { error = 'log in with ident first' }) }let q = req.query != null ? req.query : {}if (req.method == 'GET') {if (q.id != null) {let v = noteView(u, q.id)if (v == null) { return reply(404, { error = 'no such note' }) }return reply(200, v)}return reply(200, { notes = metaRows(u) })}if (req.method != 'POST') { return reply(405, { error = 'GET or POST only' }) }if (req.body == null || req.body == '') { return reply(400, { error = 'a JSON body is needed' }) }let at = jsonErrorAt(req.body)if (at >= 0) { return reply(400, { error = 'invalid JSON at character ' + at }) }let b = JSON.parse(req.body)if (b == null || hlTypeName(b) != 'Hybrid') { return reply(400, { error = 'the body must be a JSON object' }) }if (b.op == 'save') {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)' }) }if (b.local.length > 64 || b.id.length > 64) { return reply(400, { error = 'id / local too long' }) }let r = pushNote(u, b.id, b.local, b.text, b.base, b.at)if (r.error != null) { return reply(400, r) }return reply(200, r)}if (b.op == 'delete') {if (!isText(b.id) || !isTime(b.base)) { return reply(400, { error = 'delete needs id (string) and base (number)' }) }return reply(200, removeNote(u, b.id, b.base))}return reply(400, { error = "op must be 'save' or 'delete'" })}routes = [{ pattern = "/favicon.ico" file = "./icons/favicon.ico" headers = { 'Cache-Control' = 'no-cache' } }// the installable app (mission 046): the icons (the manifest is hl:web's own, from appIcons){ pattern = "/icons/icon-192.png" file = "./icons/icon-192.png" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/icons/icon-512.png" file = "./icons/icon-512.png" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/icons/apple-touch-icon.png" file = "./icons/apple-touch-icon.png" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/icons/favicon.svg" file = "./icons/favicon.svg" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/login/callback" function = loginCallback }{ pattern = "/login/failed" component = LoginFailed }{ pattern = "/login.js" file = "./login.js" headers = { 'Cache-Control' = 'no-cache' } }// the Markdown editor <md-editor>, vendored from worldapi-components (one <script> in the shell would do too:// it is loaded by the page component's parent, see components/main.hl){ pattern = "/md-editor.js" file = "./shared/md-editor.js" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/api/me" function = apiMe }{ pattern = "/api/notes" function = apiNotes }// the offline copy: the service worker (network first, the cached page when there is none) and the client that// keeps the notes in IndexedDB and syncs them{ pattern = "/sw.js" file = "./sw.js" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/notes-offline.js" file = "./notes-offline.js" headers = { 'Cache-Control' = 'no-cache' } }{ pattern = "/" component = Notes }{ pattern = "/note/:id" component = Notes }]// WHO GETS THE PUSH: the login state reaches the tabs of one session. (Notes are not pushed: the browser's own copy// pulls through /api/notes.)// `notesSignedIn` / `notesSignedOut` go to the tabs of ONE session: the one whose login carries that random tag.tagOf = (session) => { return session != null && session.data != null ? session.data.tag : null }audience = {notesSignedIn = (tag, session) => { return tag != null && tagOf(session) == tag }notesSignedOut = (tag, session) => { return tag != null && tagOf(session) == tag }}sessionDir = env('NOTES_SESSIONS') != null ? env('NOTES_SESSIONS') : nullport = env('NOTES_PORT') != null ? toNumber(env('NOTES_PORT')) : 8710// HL_HOST = the interface hl:web binds: 127.0.0.1 on Byrodin behind nginx; unset = 0.0.0.0 (dev on Loreana).// NOTES_WATCH=0 = no dev watcher. The session cookie is `notessid` (hybriel #10). A note taker is not logged// out after 15 minutes of thinking: the session idles out after the 14 days of sessionMaxAge.watching = env('NOTES_WATCH') != '0'sessionCookie = 'notessid'sessionIdle = 1209600server = new WebFramework(routes = routes, styles = styles, minify = true, port = port, watchMode = watching, sessionCookie = sessionCookie)on Error(e) { console.log('error absorbed: ' + e.message) }
Branches
- mainmain branch
Latest commits
- e27c7d71notes: Hybriel master 8efba065 (#126 GC by bytes, #48 lambda params copy; audit: nothing to fix; gate 50/0)mre
- 124613b6antcolony#40: mission references point to the moved missionsmre
- 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