notes
All repositories: gitoria
7.6 KB
// lib/api.hl — THE FUNCTION ROUTES (notes mission 002, code order): thin wrappers — check the input and the session,// call the topic (lib/notes.hl, lib/users.hl), answer.//// THE LOGIN BUTTON'S RETURN (ident README "How apps use ident"): /login/callback?ident_code=&next= → the user// (lib/users.hl userOfLoginCode) → the session is signed in → back to `next` (lib/api-helpers.hl safePath). A FAILED// LOGIN is a page (components/loginfailed.hl): the reason is parked in the session, then → /login/failed.// These two write the session: project.hl hands them the request and the session store BY REFERENCE (&req, &sessions);// a by-value copy would lose the write (tickets mission 010, gitoria mission 002).//// THE JSON API (ticket notes#2; since notes#4 the page syncs through its faces, components/notes.hl). 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 }// A conductor may also send `Authorization: Bearer idt_…` (an ident access key, keyActor below) instead of the cookie.// Invalid JSON is refused by lib/jsoncheck.hl before JSON.parse sees it (hybriel #6); unknown/mistyped fields → 400.import { Response } from 'hl:http1'import { randomBytes } from 'hl:crypto'import { userOfLoginCode, userIdOfSession, ensureUser } from './users.hl'import { check, refuse } from './ident-access.hl'import { metaRows, noteView, pushNote, removeNote } from './notes.hl'import { jsonErrorAt } from './jsoncheck.hl'import { reply, isText, isTime, safePath } from './api-helpers.hl'import { loginAllowed } from './ratelimit.hl'import { publicUrl } from './users.hl'static loginFailed = (&req, &sessions, why) => {let s = req.sessionfresh = s == nullif (fresh) { s = sessions.mint() }s.data.loginError = whysessions.save(s)res = new Response('login failed: ' + why, { status = 302 headers = { 'Location' = '/login/failed' 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' } })if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }return res}// the function route gets the cookie's session as req.session (hybriel #11); none yet → minted herestatic loginCallback = (route, &req, &sessions) => {if (req.method != 'GET') { return loginFailed(&req, &sessions, 'GET only') }if (!loginAllowed(req.headers['x-client-ip'])) { return new Response('too many login attempts — wait a few minutes', { status = 429 headers = { 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' 'Retry-After' = '600' } }) }q = req.query != null ? req.query : {}code = q.ident_codeif (code == null || code == '') { return loginFailed(&req, &sessions, 'ident sent no login code') }x = userOfLoginCode(code)if (x.error != null) { return loginFailed(&req, &sessions, x.error) }// THE SAME SESSION, NEVER SIGNED OUT (ident#28): a good code signs the session the browser already has in (a second tab or an installed// app may not store a new cookie, and a session we signed out would leave it anonymous); none yet → minted herelet s = req.sessionif (s == null) { s = sessions.mint() }s.user = { id = x.user.id }s.data.tag = randomBytes(16)s.data.loginError = nullsessions.save(s)res = new Response('logged in', { status = 302 headers = { 'Location' = safePath(q.next) 'Cache-Control' = 'no-store' 'Content-Type' = 'text/plain; charset=utf-8' 'X-Content-Type-Options' = 'nosniff' } })res.headers['Set-Cookie'] = sessions.cookieHeader(s.id)return res}// AN IDENT ACCESS KEY (ident#27): `Authorization: Bearer idt_…` is a conductor's key for this app. ident is asked on every call// (lib/ident-access.hl); the key's identity is this app's user (made at the first call if it never logged in). A `read` key may only GET;// a bad, revoked or foreign key is 401, ident not answering 503, and nothing is written in those cases.// Answers null (no idt_ header: the session path goes on exactly as before) | { user } (the users @id) | { response } (the refusal).// A Bearer call carries no cookie, so the CSRF Origin check of the session path does not apply to it (a cross-site page cannot// attach an Authorization header it does not hold).static keyActor = (req) => {h = req.headers['authorization']if (h == null || hlTypeName(h) != 'String') { return null }t = h.trim()if (t.length < 12 || t.slice(0, 7).toLowerCase() != 'bearer ' || !t.slice(7).trim().startsWith('idt_')) { return null }who = check(req)if (!who.ok) { return { response = refuse(who) } }if (who.access != 'write' && req.method != 'GET' && req.method != 'HEAD') { return { response = reply(403, { error = 'this access key is read-only' }) } }u = ensureUser(who.identity)if (u == null) { return { response = reply(500, { error = 'could not store the user' }) } }return { user = u.id }}static apiMe = (route, req) => {ka = keyActor(req)if (ka != null) { return ka.response != null ? ka.response : reply(200, { user = ka.user }) }u = userIdOfSession(req.session)return reply(200, { user = u })}static apiNotes = (route, req) => {ka = keyActor(req)if (ka != null && ka.response != null) { return ka.response }u = ka != null ? ka.user : userIdOfSession(req.session)if (u == null) { return reply(401, { error = 'log in with ident first' }) }q = req.query != null ? req.query : {}if (req.method == 'GET') {if (q.id != null) {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' }) }// CSRF: a request that names another Origin is refused; the body must be declared JSON (a cross-site form can only send text/plain,// urlencoded or multipart — a JSON content type needs a CORS preflight, which this server never grants)origin = req.headers['origin']if (ka == null && origin != null && origin != publicUrl) { return reply(403, { error = 'another origin' }) }ctype = req.headers['content-type']if (ctype == null || !ctype.toLowerCase().startsWith('application/json')) { return reply(415, { error = 'send Content-Type: application/json' }) }if (req.body == null || req.body == '') { return reply(400, { error = 'a JSON body is needed' }) }at = jsonErrorAt(req.body)if (at >= 0) { return reply(400, { error = 'invalid JSON at character ' + at }) }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' }) }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'" })}
Branches
Latest commits
- d860dc2dnotes#12: the markup names its own rules instead of hand-written class strings: the selected row is `aria-current="page"` (the list-first theme rule styles it, no class), the delete question is `Style.pAsk` and follows its own `open` attribute (bound to `asking`), the error line is `Style.pMessage` (body once in lib/looks.hl, rule in notes.hl, main.hl and loginfailed.hl). The CSS declarations are the same, only selectors changed (.ask -> p.ask, .ask.open -> p.ask[open], .message -> p.message); the pages look the same (AE 0 at 4 sizes). main.hl's selectorClass in/out stays (login.js reads it).mre
- 2e7f8664notes#13: the list and back links pass the note key from the loop (emit pick(e, r.key)) instead of writing data-note into the View and reading it back with getAttribute; the two window.history.replaceState calls and the identcode e.target.value read stay (hl:web has no replace-navigation, a bound hidden input is not adopted on a script's change event), see NO13 reportmre
- 4dc98282notes#15: a deleted note made in this tab leaves the list at once (the delete now removes this tab's edit under every key the row has: local id, server id); gate: browser.mjs notes#15 section, red on the old codemre
- e4e7402fnotes#11: plain declarations instead of let for variables never reassigned (components/notes.hl 3, lib/jsoncheck.hl 5, lib/util.hl 2, tools/migrate-short-ids.hl 8)mre
- 27b6a09enotes#8: Style blocks in the nested form (note-list, note-editor, .ask with their children nested, :empty as a nested pseudo-class); the same CSS rules, the pages look the samemre
- 71a9538bnotes: B27W report, log linemre
- 78ba0073notes: an ident access key (Authorization: Bearer idt_…) reads and writes its identity's notes through /api/me and /api/notes; gate tests/ident-access-notes.mjs (ident#27)mre
- 3de46dacnotes: the sign-in callback keeps the session it finds and signs it in (same cookie, nothing signed out; ident#28); security gate 73+5 failing → 78 passedmre
- 5909d458notes: MdEditor from components 59704ce (text on the clipboard always pastes, a file manager copy still attaches; pipe rows without a delimiter row; tickets#49, notes#5)mre
- 98bd6a98N5b: pipe rows without a delimiter row are a table (MdEditor ad4e929, plain copy); gate tests/dashboard-table.mjs; reportmre
- dbf93319N5 report: components gate rerun 613 passed, 0 failedmre
- 3a8bc0d2N5: empty Table-button table is written as a real pipe table (MdEditor 4bd1112, plain copy); gate tests/table-button.mjs; reportmre
- c16bd443N5: step 1 report (tables pass locally; his DASHBOARD note has no delimiter row)mre
- 6091320anotes: MdEditor 7437e32 (surface drawn at once when the page is claimed); gate measures claim-to-text on 5 note loads at 1280 and 390mre
- 0aa9277enotes: move each component's styles into its own Style block (shell and header selector in main.hl, list, editor frame and delete question in notes.hl); styles.hl keeps the theme inherit, the accent and the message colour; .gitignore ignores a bin symlink too; tests/shots.mjs for the pixel comparemre
- 9ba01de3notes: write the standby service out in full so the boot gate can read the main servicemre
- 98cab40anotes: standby service on its port plus 10 and a deploy that hands over through it without a gapmre
- 1fadb473notes gate: the editor table now has 1 px cell lines from the notes thememre
- 8762115cnotes: take the components e54f83a (paste as Markdown, text typed before the editor is built is kept, Table button); table lines come from the notes thememre
- ac23e194ident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre