gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commit18d2df6018d2df60md-editor.hl: verbatim copy of components f3-mdvalue (an outside value change is shown by the editor)mre18d2df60/lib/api-helpers.hl

12.1 KB

  1. // lib/api-helpers.hl — the plumbing of the function routes (lib/api.hl): query strings, bodies, answers, who is
  2. // calling (token or app key), the Markdown Accept check, the small HTML page. Statics only; no topic logic here.
  3. import { Response } from 'hl:http1'
  4. import { jsonErrorAt } from './jsoncheck.hl'
  5. import { userOfBearer } from './users.hl'
  6. import { connectionOfKey, personOf } from './connections.hl'
  7. import { states, stateOf } from './tickets-helpers.hl'
  8. import { partsOf, isUtf8 } from './multipart.hl'
  9. import { maxCommentBytes, maxFiles } from './attachments.hl'
  10. static jsonHeaders = { 'Content-Type' = 'application/json; charset=utf-8' }
  11. static reply = (status, value) => {
  12. return new Response(JSON.stringify(value), { status = status headers = jsonHeaders })
  13. }
  14. static fail = (status, message) => { return reply(status, { error = message }) }
  15. // `?a=1&b=x` of a request path → { a = '1', b = 'x' } ('+' is a space; hl:http1
  16. // has already percent-decoded the path)
  17. static queryOf = (path) => {
  18. out = {}
  19. q = path.indexOf('?')
  20. if (q < 0) { return out }
  21. for (pair of path.slice(q + 1).split('&')) {
  22. if (pair != '') {
  23. let eq = pair.indexOf('=')
  24. if (eq < 0) { out[pair] = '' } else { out[pair.slice(0, eq)] = pair.slice(eq + 1).replaceAll('+', ' ') }
  25. }
  26. }
  27. return out
  28. }
  29. // the request body as JSON, or null when it is not
  30. static bodyOf = (req) => {
  31. if (req.body == null || req.body == '') { return null }
  32. return JSON.parse(req.body)
  33. }
  34. // THE API IS STRICT (ticket #10): a malformed report must not be filed half-read. A body
  35. // is a JSON object whose keys are all in `required` or `optional`, every value is a
  36. // String, and every required one is non-empty after trimming. Answers null (fine) or
  37. // { error, field } — the first offence, naming the field.
  38. // (a list has no concat() in this build — NotCallable, hybriel #6's family)
  39. static allowedOf = (required, optional) => {
  40. all = []
  41. for (k of required) { all.push(k) }
  42. for (k of optional) { all.push(k) }
  43. return all.join(', ')
  44. }
  45. static bodyError = (b, required, optional) => {
  46. if (b == null || hlTypeName(b) != 'Hybrid' || b.length != null) {
  47. return { error = 'the body must be a JSON object' field = '' }
  48. }
  49. for (k of b.keys()) {
  50. // ticket #7: the author is the token's user — a body that still names one is refused
  51. // (not silently ignored), so a client learns that its field does nothing
  52. if (k == 'author') {
  53. return { error = "no field 'author' any more: the author is the user of your API token" field = 'author' }
  54. }
  55. if (!required.includes(k) && !optional.includes(k)) {
  56. return { error = "unknown field '" + k + "' (allowed: " + allowedOf(required, optional) + ')' field = k }
  57. }
  58. if (hlTypeName(b[k]) != 'String') {
  59. return { error = "field '" + k + "' must be a string, not " + hlTypeName(b[k]) field = k }
  60. }
  61. }
  62. for (k of required) {
  63. if (b[k] == null) { return { error = "field '" + k + "' is required" field = k } }
  64. if (b[k].trim() == '') { return { error = "field '" + k + "' must not be empty" field = k } }
  65. }
  66. return null
  67. }
  68. static refuse = (e) => { return reply(400, e) }
  69. // ticket #7: an API write without a valid token (missing, malformed, unknown, revoked) → 401
  70. static unauthorized = () => { return unauthorizedFor('an API write') }
  71. // ticket #26: the event stream says what it is that needs the token
  72. static unauthorizedFor = (what) => {
  73. return new Response(JSON.stringify({ error = what + ' needs Authorization: Bearer <token> — log in with ident and create a token on /you' }), { status = 401 headers = { 'Content-Type' = 'application/json; charset=utf-8' 'WWW-Authenticate' = 'Bearer' } })
  74. }
  75. // a POST body, checked: { body } or { bad } (bad = the 400 answer's value).
  76. // Invalid JSON is refused by jsoncheck.hl BEFORE JSON.parse ever sees it (ticket #15,
  77. // workaround for hybriel #12: an uncaught JSON.parse would answer 500 with source paths).
  78. static readBody = (req, required, optional) => {
  79. if (req.body != null && req.body != '') {
  80. at = jsonErrorAt(req.body)
  81. if (at >= 0) { return { bad = { error = 'invalid JSON at character ' + at } } }
  82. }
  83. b = bodyOf(req)
  84. return { body = b bad = bodyError(b, required, optional) }
  85. }
  86. // a refusal of a topic function: 403 when the role is missing, else 400
  87. static denied = (r) => {
  88. if (r.forbidden == true) { return reply(403, { error = r.error field = r.field }) }
  89. return refuse({ error = r.error field = r.field })
  90. }
  91. // ---- who is calling --------------------------------------------------------------------------------
  92. // WRITES NEED A TOKEN (ticket #7): `Authorization: Bearer <token>` (users.hl; a logged-in user
  93. // makes tokens on /you). No / bad / revoked token → 401, checked BEFORE the body.
  94. // the token's user of an API write, or null (→ 401)
  95. static apiUser = (req) => { return userOfBearer(req.headers['authorization']) }
  96. // WHO WRITES, for the endpoints an app's KEY may also use (ticket #21: create a ticket, comment, change the state):
  97. // { user } for a user's token, { conn } for a project key (connections.hl), null = 401 (checked before the body)
  98. static apiAuth = (req) => {
  99. h = req.headers['authorization']
  100. u = userOfBearer(h)
  101. if (u != null) { return { user = u } }
  102. c = connectionOfKey(h)
  103. return c != null ? { conn = c } : null
  104. }
  105. // the acting user inside project `projectId`: { user } or { response }. A key reaches ITS project only and names the
  106. // person by `X-Tickets-Identity`; the project's roles then decide as for any user.
  107. static actorIn = (auth, req, projectId) => {
  108. if (auth.user != null) { return { user = auth.user } }
  109. if (projectId == null || auth.conn.project != projectId) { return { response = reply(403, { error = 'this key belongs to another project' field = '' }) } }
  110. a = personOf(req.headers['x-tickets-identity'])
  111. if (a.error != null) { return { response = reply(403, { error = a.error field = '' }) } }
  112. return { user = a.user }
  113. }
  114. // ---- list filters ----------------------------------------------------------------------------------
  115. static stateFilter = (q) => {
  116. if (q.state == null || q.state == '') { return { state = null } }
  117. st = stateOf(q.state)
  118. if (st == null) { return { bad = fail(400, 'unknown state — one of: ' + states.join(', ')) } }
  119. return { state = st }
  120. }
  121. // the filters of a list, for the Markdown heading ('' = none)
  122. static filterLabel = (project, state) => {
  123. parts = []
  124. if (project != null) { parts.push('project ' + project) }
  125. if (state != null) { parts.push('state ' + state) }
  126. return parts.join(', ')
  127. }
  128. // ---- THE MARKDOWN READ VIEW's request side (ticket #6; the documents: lib/mdview.hl) -----------------
  129. // does the request ask for Markdown? `Accept` names text/markdown with q > 0 and prefers it to
  130. // application/json (a higher q, or the same q and listed first). No Accept / */* → JSON.
  131. static qOf = (part) => {
  132. let q = 1
  133. for (p of part.split(';')) {
  134. let kv = p.trim()
  135. if (kv.startsWith('q=')) { q = toNumber(kv.slice(2)) }
  136. }
  137. return q == null ? 0 : q
  138. }
  139. static wantsMarkdown = (req) => {
  140. h = req.headers['accept']
  141. if (h == null || hlTypeName(h) != 'String') { return false }
  142. let md = -1
  143. let js = -1
  144. let mdAt = -1
  145. let jsAt = -1
  146. let i = 0
  147. for (part of h.toLowerCase().split(',')) {
  148. let type = part.split(';')[0].trim()
  149. if (type == 'text/markdown' && mdAt < 0) {
  150. md = qOf(part)
  151. mdAt = i
  152. }
  153. if (type == 'application/json' && jsAt < 0) {
  154. js = qOf(part)
  155. jsAt = i
  156. }
  157. i = i + 1
  158. }
  159. if (md <= 0) { return false }
  160. if (js < 0) { return true }
  161. return md > js || (md == js && mdAt < jsAt)
  162. }
  163. static markdownReply = (text) => {
  164. return new Response(text, { status = 200 headers = { 'Content-Type' = 'text/markdown; charset=utf-8' 'Vary' = 'Accept' } })
  165. }
  166. // ---- A COMMENT WITH FILES (tickets#27, mission 017): POST …/comments as multipart/form-data -----------------------------
  167. // fields: `text` (optional when there are files) and any number of file parts named `file` (or `files`, `file[]`, `files[]`), e.g.
  168. // `curl -H "Authorization: Bearer $T" -F 'text=390 px' -F [email protected] …/comments`. Answers { text, files ([{ name, type, bytes }]) }
  169. // or { bad } (the answer: 413 for a body over the limit, else 400 naming the field). The limits per file / per comment and the
  170. // content check are lib/attachments.hl's (addComment).
  171. static fileFields = ['file', 'files', 'file[]', 'files[]']
  172. static commentFormOf = (req) => {
  173. if (req.bytes != null && hlTypeName(req.bytes) == 'Bytes' && req.bytes.length > maxCommentBytes + 1048576) {
  174. return { bad = reply(413, { error = 'the body is ' + req.bytes.length + ' bytes: the files of one comment may have at most 25 MB together' field = 'files' }) }
  175. }
  176. p = partsOf(req)
  177. if (p.error != null) { return { bad = refuse({ error = p.error field = '' }) } }
  178. let text = null
  179. files = []
  180. for (part of p.parts) {
  181. if (part.name == 'author') { return { bad = refuse({ error = "no field 'author' any more: the author is the user of your API token" field = 'author' }) } }
  182. if (fileFields.includes(part.name) && part.filename != null) {
  183. files.push({ name = part.filename type = part.type bytes = part.bytes })
  184. } else if (part.name == 'text' && part.filename == null) {
  185. if (text != null) { return { bad = refuse({ error = "field 'text' is given twice" field = 'text' }) } }
  186. if (!isUtf8(part.bytes)) { return { bad = refuse({ error = "field 'text' is not UTF-8" field = 'text' }) } }
  187. text = part.bytes.toString()
  188. } else {
  189. return { bad = refuse({ error = "unknown field '" + part.name + "' (allowed: text, and files as file=@path)" field = part.name }) }
  190. }
  191. }
  192. if (files.length > maxFiles) { return { bad = refuse({ error = 'at most ' + maxFiles + ' files per comment (' + files.length + ' given)' field = 'files' }) } }
  193. return { text = text != null ? text : '' files = files }
  194. }
  195. // ---- answers that are not JSON ---------------------------------------------------------------------
  196. // an attachment's bytes (tickets#27): a picture inline, any other file as a download; its type is the one its CONTENT showed
  197. // (lib/attachments.hl); nosniff + a sandbox policy, so nothing in it can run; private to the browser that fetched it
  198. static fileReply = (f) => {
  199. disp = (f.image ? 'inline' : 'attachment') + '; filename=' + DQ + asciiName(f.name) + DQ + "; filename*=UTF-8''" + encodeURIComponent(f.name)
  200. return new Response(f.bytes, { status = 200 headers = { 'Content-Type' = f.type 'Content-Disposition' = disp 'X-Content-Type-Options' = 'nosniff' 'Content-Security-Policy' = "default-src 'none'; img-src 'self'; style-src 'unsafe-inline'; sandbox" 'Cache-Control' = 'private, max-age=86400' 'Cross-Origin-Resource-Policy' = 'same-origin' } })
  201. }
  202. static DQ = '"'
  203. // a name for the plain `filename=` (ASCII only; the exact one rides in filename*)
  204. static asciiName = (name) => {
  205. let out = ''
  206. let i = 0
  207. while (i < name.length) {
  208. let c = name.slice(i, i + 1)
  209. let k = c.charCodeAt(0)
  210. out = out + (k >= 32 && k < 127 && c != '"' ? c : '_')
  211. i = i + 1
  212. }
  213. return out
  214. }
  215. // a small HTML page (the login callback, /connect): a title and one message
  216. static htmlPage = (status, title, text) => {
  217. body = '<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"><title>tickets | ' + title + '</title><style>body{margin:0;padding:1.5rem 1rem;font:16px/1.5 system-ui,sans-serif;color:rgb(195, 200, 205);background:rgb(25, 30, 35)}main{max-width:34rem;margin:0 auto;display:grid;gap:1rem}h1{margin:0;font-size:1.3rem;color:rgb(245, 250, 255)}p{margin:0}a{display:inline-flex;align-items:center;min-height:2.75rem;color:#c586c0}.error{color:#f44747}</style></head><body><main><h1>' + title + '</h1><p id="error" class="error">' + text.replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;') + '</p><p><a id="home" href="/">back to the tickets</a></p></main></body></html>'
  218. return new Response(body, { status = status headers = { 'Content-Type' = 'text/html; charset=utf-8' 'Cache-Control' = 'no-store' } })
  219. }
  220. // a page that moved for good (301) / a page that names nothing (404), as plain text
  221. static moved = (to) => {
  222. return new Response('moved to ' + to, { status = 301 headers = { 'Location' = to 'Content-Type' = 'text/plain; charset=utf-8' } })
  223. }
  224. static missing = (message) => { return new Response(message, { status = 404 headers = { 'Content-Type' = 'text/plain; charset=utf-8' } }) }

Branches

Latest commits

  • 18d2df60md-editor.hl: verbatim copy of components f3-mdvalue (an outside value change is shown by the editor)mre
  • f6764bedreports/H1-hydrate.mdmre
  • 1bbbf0edtests/browser.mjs: wait for hydration before clicking the login button on / (device B)mre
  • 6f503cfctests/cdp.mjs: HL_CPU_THROTTLE=<rate> optional CPU throttling for gate runsmre
  • e17e2855re-vendor Hybriel 5406d146 (hl:web batches 9+10: #72 emits while the socket is closed delivered after reconnect, browser boot linear, faster list appends; contains int 6–14 + m406)mre
  • a6ddccd2re-vendor Hybriel 6f8a0689 (int 6–11: streaming cursors, #203 index heal + close() fix, fd403 listDir/cursor fds, hl:time browser side, hl:web batches 5+6)mre
  • 81e036b7docker-compose: nofile 65536 (Hybriel int 6+ boot opened >1024 files in the tracker)mre
  • 5d8d2cf6deploy: backup copies index files first and *.mpack data last (hot-copy skew, hybriel #203)mre
  • 58e8c02cmission 024: report, LOG, STATUS, e2e fixmre
  • 50778073tests/e2e-route-marker.mjs: first paint marker, comments post/edit redrawmre
  • c5203298mission 024: MainMenu marks the page from the route (layouts 0bcc629 main-menu.hl); browser-side marker removed; gate: marker in the server HTMLmre
  • b1a4c270re-vendor Hybriel master f9614007: bin/ (git-ignored) and plugins wholemre
  • 866397a0mission 023: theme from layouts 76f99f6 (current marker, menu count badge), components from 3794c59 (MdEditor keys); Inbox count as badge, current by address; gates and E2E; reportmre
  • 7ed2e5e5deploy.sh: a gate without a 'passed,' line (check-theme) no longer ends the script silently (grep under pipefail), as gitoria/layoutsmre
  • bf9064a3mission 022: tickets on the layouts theme (step 1): shell, styles, gates, audit, E2E; reportmre
  • f3d61711mission 022 WIP: tickets on the layouts theme (dbe3de7): AppHeader/MainMenu/UserMenu/Sidebar/ContentFirst shell, styles reduced to the app's own, check-theme in the gates, 390 audit + real-Chrome walk scriptmre
  • 31cabfccmission 021: E2E script, report, LOG, STATUSmre
  • 6aea8683editor look: .empty rule only for p.empty, files off where tickets has no upload, state note one line, events test scrolls the editor into view; synced md-editor (components d702d76+6f27ad3); gate 377/0, events 52/0mre
  • dce6ffa6Merge branch 'w28-deflake'mre
  • 536092a1tickets (mission 019): de-flake the m016 comment clicks (B: unliked) — calmClick waits until the button stops moving; test only, no app changemre