gitoria

tickets

All repositories: gitoria

ReadmeCodePull requestsReleasesTicketsSettings
Commitccd3a327ccd3a327tickets: the security gate expects frame-src to be exactly the ident address (the sign-in frame), still no wildcard or selfmreccd3a327/lib/api-helpers.hl

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

Branches

Latest commits

  • ccd3a327tickets: the security gate expects frame-src to be exactly the ident address (the sign-in frame), still no wildcard or selfmre
  • 4348dbabident#31: the selector's sign-in returns to the page the user started on (return attribute = the login callback with next), gate checkmre
  • 66ef3005Merge branch 'iw-ident-widget'mre
  • bc0ad663tickets: a gap between your name and Log out in the phone header (they touched); gate checks itmre
  • 2f818d46UX2: report, LOG line, e2e fixes, gate pause after loadmre
  • af3ef7c4gate: the legacy state line says progressmre
  • 62480a00tickets#33: a state change with a note is a comment card in the feed (same framework rendering, can be liked, edited, deleted), its state line stands alone; gate checks for a new comment with and without a state change, at once and after a reloadmre
  • 4ae80007UX: Respond is one composer (state in its footer, button says what happens); New ticket / New project windows in the list heading row; project form shared; theme copied from layouts; gates and a lisbeth e2emre
  • f03b438atickets header: the selector alone top right plus your name and Log out as before the theme missions; the user icon is gonemre
  • 81f10e4eident selector back in the header (creator 2026-10-24): selector top right signed in and out on phone and desktop, no second Log in button, new gate checks (WIP: gates not re-run after the last edits)mre
  • e9f428e7tools: reown-authors (tracker#36: every author that is not Caramboleyo or Apollo becomes the project's conductor; antcolony, miserit-anthar, hybrilior, termuplex stay) and a read-only author surveymre
  • f51029abMerge branch 'sy-sync'mre
  • eae6e8c7sync components.hybriel 4922f9c: comments like / Edit / Delete / 'edited' are 44 px targets; gate: 'edited' hit-area padding, thread targets check (SY)mre
  • 0de4750btheme: sync from layouts 4994037 (list rows stack, td word-keep, heading code, edited tap target)mre
  • 4eeb7bfeST2 report wordingmre
  • 2558f56cst2-sec: keep the hlsid session cookie name (no one is signed out), Secure flag only; gate: a cookie issued by main stays signed in; ident stub serves selector.js; security.mjs in deploy GATESmre
  • ea2e440esecurity audit (ST): JSON body cap, relation rights, login session rotation, __Host- Secure cookie, API security headers, CSP+referrer meta, /connect cap, one-line subjects, tests/security.mjs, reportmre
  • 7c8c2282sessions last 99 years (creator 2026-10-23: logins never expire; only sign out ends them)mre
  • b6277497report MT-mobile, LOGmre
  • 6709398blist paging: the newest rows come first (the sorted array was not used); filter rows hide their scrollbar; gate checks the ordermre