gitoria

notes

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Branchnotes9-no-pollc49ce093|||PR WIP remove notes polling and use framework reachabilityAtlasnotes9-no-poll/lib/api.hl

7.6 KB

  1. // lib/api.hl — THE FUNCTION ROUTES (notes mission 002, code order): thin wrappers — check the input and the session,
  2. // call the topic (lib/notes.hl, lib/users.hl), answer.
  3. //
  4. // THE LOGIN BUTTON'S RETURN (ident README "How apps use ident"): /login/callback?ident_code=&next= → the user
  5. // (lib/users.hl userOfLoginCode) → the session is signed in → back to `next` (lib/api-helpers.hl safePath). A FAILED
  6. // LOGIN is a page (components/loginfailed.hl): the reason is parked in the session, then → /login/failed.
  7. // These two write the session: project.hl hands them the request and the session store BY REFERENCE (&req, &sessions);
  8. // a by-value copy would lose the write (tickets mission 010, gitoria mission 002).
  9. //
  10. // 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.
  11. // GET /api/me → { user } (an opaque id of the signed-in user, or null)
  12. // GET /api/notes → { notes: [{ id, edited, gone }] } every note of the user, tombstones included
  13. // GET /api/notes?id=<id> → { id, text, edited, created }
  14. // POST /api/notes { op: 'save', id, local, text, base, at } → { id, edited, text, copy? }
  15. // POST /api/notes { op: 'delete', id, base } → { ok } | { kept, id, edited, text }
  16. // A conductor may also send `Authorization: Bearer idt_…` (an ident access key, keyActor below) instead of the cookie.
  17. // Invalid JSON is refused by lib/jsoncheck.hl before JSON.parse sees it (hybriel #6); unknown/mistyped fields → 400.
  18. import { Response } from 'hl:http1'
  19. import { randomBytes } from 'hl:crypto'
  20. import { userOfLoginCode, userIdOfSession, ensureUser } from './users.hl'
  21. import { check, refuse } from './ident-access.hl'
  22. import { metaRows, noteView, pushNote, removeNote } from './notes.hl'
  23. import { jsonErrorAt } from './jsoncheck.hl'
  24. import { reply, isText, isTime, safePath } from './api-helpers.hl'
  25. import { loginAllowed } from './ratelimit.hl'
  26. import { publicUrl } from './users.hl'
  27. static loginFailed = (&req, &sessions, String why) => {
  28. let s = req.session
  29. fresh = s == null
  30. if (fresh) { s = sessions.mint() }
  31. s.data.loginError = why
  32. sessions.save(s)
  33. 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' } })
  34. if (fresh) { res.headers['Set-Cookie'] = sessions.cookieHeader(s.id) }
  35. return res
  36. }
  37. // the function route gets the cookie's session as req.session (hybriel #11); none yet → minted here
  38. static loginCallback = (Hybrid route, &req, &sessions) => {
  39. if (req.method != 'GET') { return loginFailed(&req, &sessions, 'GET only') }
  40. 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' } }) }
  41. q = req.query != null ? req.query : {}
  42. code = q.ident_code
  43. if (code == null || code == '') { return loginFailed(&req, &sessions, 'ident sent no login code') }
  44. x = userOfLoginCode(code)
  45. if (x.error != null) { return loginFailed(&req, &sessions, x.error) }
  46. // 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
  47. // app may not store a new cookie, and a session we signed out would leave it anonymous); none yet → minted here
  48. let s = req.session
  49. if (s == null) { s = sessions.mint() }
  50. s.user = { id = x.user.id }
  51. s.data.tag = randomBytes(16)
  52. s.data.loginError = null
  53. sessions.save(s)
  54. 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' } })
  55. res.headers['Set-Cookie'] = sessions.cookieHeader(s.id)
  56. return res
  57. }
  58. // AN IDENT ACCESS KEY (ident#27): `Authorization: Bearer idt_…` is a conductor's key for this app. ident is asked on every call
  59. // (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;
  60. // a bad, revoked or foreign key is 401, ident not answering 503, and nothing is written in those cases.
  61. // Answers null (no idt_ header: the session path goes on exactly as before) | { user } (the users @id) | { response } (the refusal).
  62. // 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
  63. // attach an Authorization header it does not hold).
  64. static keyActor = (Hybrid req) => {
  65. h = req.headers['authorization']
  66. if (h == null || hlTypeName(h) != 'String') { return null }
  67. t = h.trim()
  68. if (t.length < 12 || t.slice(0, 7).toLowerCase() != 'bearer ' || !t.slice(7).trim().startsWith('idt_')) { return null }
  69. who = check(req)
  70. if (!who.ok) { return { response = refuse(who) } }
  71. if (who.access != 'write' && req.method != 'GET' && req.method != 'HEAD') { return { response = reply(403, { error = 'this access key is read-only' }) } }
  72. u = ensureUser(who.identity)
  73. if (u == null) { return { response = reply(500, { error = 'could not store the user' }) } }
  74. return { user = u.id }
  75. }
  76. static apiMe = (Hybrid route, Hybrid req) => {
  77. ka = keyActor(req)
  78. if (ka != null) { return ka.response != null ? ka.response : reply(200, { user = ka.user }) }
  79. u = userIdOfSession(req.session)
  80. return reply(200, { user = u })
  81. }
  82. static apiNotes = (Hybrid route, Hybrid req) => {
  83. ka = keyActor(req)
  84. if (ka != null && ka.response != null) { return ka.response }
  85. u = ka != null ? ka.user : userIdOfSession(req.session)
  86. if (u == null) { return reply(401, { error = 'log in with ident first' }) }
  87. q = req.query != null ? req.query : {}
  88. if (req.method == 'GET') {
  89. if (q.id != null) {
  90. v = noteView(u, q.id)
  91. if (v == null) { return reply(404, { error = 'no such note' }) }
  92. return reply(200, v)
  93. }
  94. return reply(200, { notes = metaRows(u) })
  95. }
  96. if (req.method != 'POST') { return reply(405, { error = 'GET or POST only' }) }
  97. // CSRF: a request that names another Origin is refused; the body must be declared JSON (a cross-site form can only send text/plain,
  98. // urlencoded or multipart — a JSON content type needs a CORS preflight, which this server never grants)
  99. origin = req.headers['origin']
  100. if (ka == null && origin != null && origin != publicUrl) { return reply(403, { error = 'another origin' }) }
  101. ctype = req.headers['content-type']
  102. if (ctype == null || !ctype.toLowerCase().startsWith('application/json')) { return reply(415, { error = 'send Content-Type: application/json' }) }
  103. if (req.body == null || req.body == '') { return reply(400, { error = 'a JSON body is needed' }) }
  104. at = jsonErrorAt(req.body)
  105. if (at >= 0) { return reply(400, { error = 'invalid JSON at character ' + at }) }
  106. b = JSON.parse(req.body)
  107. if (b == null || hlTypeName(b) != 'Hybrid') { return reply(400, { error = 'the body must be a JSON object' }) }
  108. if (b.op == 'save') {
  109. 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)' }) }
  110. if (b.local.length > 64 || b.id.length > 64) { return reply(400, { error = 'id / local too long' }) }
  111. r = pushNote(u, b.id, b.local, b.text, b.base, b.at, '')
  112. if (r.error != null) { return reply(400, r) }
  113. return reply(200, r)
  114. }
  115. if (b.op == 'delete') {
  116. if (!isText(b.id) || !isTime(b.base)) { return reply(400, { error = 'delete needs id (string) and base (number)' }) }
  117. return reply(200, removeNote(u, b.id, b.base, '', ''))
  118. }
  119. return reply(400, { error = "op must be 'save' or 'delete'" })
  120. }

Branches

Latest commits

  • c49ce093|||PR WIP remove notes polling and use framework reachabilityAtlas
  • c028ac61Merge branch 'notes-pr7-kunibert' into mainAtlas
  • 9cc92bdfKeep conflict and history fixes while awaiting queued save supportAtlas
  • a5c27cb6Allow real edits back to earlier text and honor configured identAtlas
  • 15c46ced|||PR Preserve note edits, conflict bases and visible historyAtlas
  • 4c6e0bf6Merge branch 'notes13-day61' into mainAtlas
  • eb51864f|||PR Back/Forward via navigate, server drafts, Hybriel day61Atlas
  • 3537cf7eMerge branch 'vendor-day59' into mainAtlas
  • c13d188b|||PR Vendor Hybriel day59Atlas
  • 24c95433Merge branch 'notes17-ghost-note' into mainAtlas
  • ae1075b2Preserve rejected drafts during note ID adoptionAtlas
  • 383cce23|||PR Prevent saved local edits from restoring deleted notesAtlas
  • 99ca1cf6Merge branch 'vendor-day56' into mainAtlas
  • 649cef37|||PR Vendor Hybriel day56Atlas
  • aadd0abcMerge branch 'hl-standard-2' into mainAtlas
  • 52ffac9f|||PR Keyboard and reload checks for the notes gate (HL-STANDARD F21, F5)Atlas
  • 617ee8c0Merge branch 'hl-standard' into mainAtlas
  • 452458ee|||PR Type the function parameters of notes' own .hl files (HL-STANDARD L10)Atlas
  • 23758cd6Re-vendor complete Hybriel plugins and runtime to day44mre
  • 5d7cc700Backup tar: --hard-dereference, so mpackdb sidecars are never stored as hard links (Tracker's finding)mre