notes
All repositories: gitoria
8.1 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 Notes from './components/notes.hl'import LoginFailed from './components/loginfailed.hl'static siteName = "notes"appTitle = siteNamestyles = 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" direct = "" }{ 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