tickets
All repositories: gitoria
13.4 KB
// lib/api-helpers.hl — the plumbing of the function routes (lib/api.hl): query strings, bodies, answers, who is// calling (token or app key), the Markdown Accept check, the small HTML page. Statics only; no topic logic here.import { Response } from 'hl:http1'import { jsonErrorAt } from './jsoncheck.hl'import { userOfBearer } from './users.hl'import { connectionOfKey, personOf } from './connections.hl'import { states, stateOf } from './tickets-helpers.hl'import { partsOf, isUtf8 } from './multipart.hl'import { maxCommentBytes, maxFiles } from './attachments.hl'// SECURITY HEADERS of every answer these function routes make (mission ST; pages are hl:web's): nothing is sniffed into a type it// 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)static secHeaders = { 'X-Content-Type-Options' = 'nosniff' 'X-Frame-Options' = 'DENY' 'Referrer-Policy' = 'no-referrer' 'Content-Security-Policy' = "default-src 'none'; frame-ancestors 'none'" }// the same, plus `own` (the answer's own headers win)static hdr = (own) => {out = {}for (k of secHeaders.keys()) { out[k] = secHeaders[k] }for (k of own.keys()) { out[k] = own[k] }return out}static jsonHeaders = hdr({ 'Content-Type' = 'application/json; charset=utf-8' })// the largest JSON body the API reads (mission ST): jsoncheck.hl walks a body character by character IN HYBRIEL, so a multi-megabyte// body from any token holder held the single-threaded server for minutes. Texts are far smaller (a comment's files travel as multipart).static maxJsonBytes = 1048576static reply = (status, value) => {return new Response(JSON.stringify(value), { status = status headers = jsonHeaders })}static fail = (status, message) => { return reply(status, { error = message }) }// `?a=1&b=x` of a request path → { a = '1', b = 'x' } ('+' is a space; hl:http1// has already percent-decoded the path)static queryOf = (path) => {out = {}q = path.indexOf('?')if (q < 0) { return out }for (pair of path.slice(q + 1).split('&')) {if (pair != '') {let eq = pair.indexOf('=')if (eq < 0) { out[pair] = '' } else { out[pair.slice(0, eq)] = pair.slice(eq + 1).replaceAll('+', ' ') }}}return out}// the request body as JSON, or null when it is notstatic bodyOf = (req) => {if (req.body == null || req.body == '') { return null }return JSON.parse(req.body)}// THE API IS STRICT (ticket #10): a malformed report must not be filed half-read. A body// is a JSON object whose keys are all in `required` or `optional`, every value is a// String, and every required one is non-empty after trimming. Answers null (fine) or// { error, field } — the first offence, naming the field.// (a list has no concat() in this build — NotCallable, hybriel #6's family)static allowedOf = (required, optional) => {all = []for (k of required) { all.push(k) }for (k of optional) { all.push(k) }return all.join(', ')}static bodyError = (b, required, optional) => {if (b == null || hlTypeName(b) != 'Hybrid' || b.length != null) {return { error = 'the body must be a JSON object' field = '' }}for (k of b.keys()) {// ticket #7: the author is the token's user — a body that still names one is refused// (not silently ignored), so a client learns that its field does nothingif (k == 'author') {return { error = "no field 'author' any more: the author is the user of your API token" field = 'author' }}if (!required.includes(k) && !optional.includes(k)) {return { error = "unknown field '" + k + "' (allowed: " + allowedOf(required, optional) + ')' field = k }}if (hlTypeName(b[k]) != 'String') {return { error = "field '" + k + "' must be a string, not " + hlTypeName(b[k]) field = k }}}for (k of required) {if (b[k] == null) { return { error = "field '" + k + "' is required" field = k } }if (b[k].trim() == '') { return { error = "field '" + k + "' must not be empty" field = k } }}return null}static refuse = (e) => { return reply(e.tooBig == true ? 413 : 400, e) }// ticket #7: an API write without a valid token (missing, malformed, unknown, revoked) → 401static unauthorized = () => { return unauthorizedFor('an API write') }// ticket #26: the event stream says what it is that needs the tokenstatic unauthorizedFor = (what) => {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' }) })}// a POST body, checked: { body } or { bad } (bad = the 400 answer's value).// Invalid JSON is refused by jsoncheck.hl BEFORE JSON.parse ever sees it (ticket #15,// workaround for hybriel #12: an uncaught JSON.parse would answer 500 with source paths).static readBody = (req, required, optional) => {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 } } }if (req.body != null && req.body != '') {at = jsonErrorAt(req.body)if (at >= 0) { return { bad = { error = 'invalid JSON at character ' + at } } }}b = bodyOf(req)return { body = b bad = bodyError(b, required, optional) }}// a refusal of a topic function: 403 when the role is missing, else 400static denied = (r) => {if (r.forbidden == true) { return reply(403, { error = r.error field = r.field }) }return refuse({ error = r.error field = r.field })}// ---- who is calling --------------------------------------------------------------------------------// WRITES NEED A TOKEN (ticket #7): `Authorization: Bearer <token>` (users.hl; a logged-in user// makes tokens on /you). No / bad / revoked token → 401, checked BEFORE the body.// the token's user of an API write, or null (→ 401)static apiUser = (req) => { return userOfBearer(req.headers['authorization']) }// WHO WRITES, for the endpoints an app's KEY may also use (ticket #21: create a ticket, comment, change the state):// { user } for a user's token, { conn } for a project key (connections.hl), null = 401 (checked before the body)static apiAuth = (req) => {h = req.headers['authorization']u = userOfBearer(h)if (u != null) { return { user = u } }c = connectionOfKey(h)return c != null ? { conn = c } : null}// the acting user inside project `projectId`: { user } or { response }. A key reaches ITS project only and names the// person by `X-Tickets-Identity`; the project's roles then decide as for any user.static actorIn = (auth, req, projectId) => {if (auth.user != null) { return { user = auth.user } }if (projectId == null || auth.conn.project != projectId) { return { response = reply(403, { error = 'this key belongs to another project' field = '' }) } }a = personOf(req.headers['x-tickets-identity'])if (a.error != null) { return { response = reply(403, { error = a.error field = '' }) } }return { user = a.user }}// ---- list filters ----------------------------------------------------------------------------------static stateFilter = (q) => {if (q.state == null || q.state == '') { return { state = null } }st = stateOf(q.state)if (st == null) { return { bad = fail(400, 'unknown state — one of: ' + states.join(', ')) } }return { state = st }}// the filters of a list, for the Markdown heading ('' = none)static filterLabel = (project, state) => {parts = []if (project != null) { parts.push('project ' + project) }if (state != null) { parts.push('state ' + state) }return parts.join(', ')}// ---- THE MARKDOWN READ VIEW's request side (ticket #6; the documents: lib/mdview.hl) -----------------// does the request ask for Markdown? `Accept` names text/markdown with q > 0 and prefers it to// application/json (a higher q, or the same q and listed first). No Accept / */* → JSON.static qOf = (part) => {let q = 1for (p of part.split(';')) {let kv = p.trim()if (kv.startsWith('q=')) { q = toNumber(kv.slice(2)) }}return q == null ? 0 : q}static wantsMarkdown = (req) => {h = req.headers['accept']if (h == null || hlTypeName(h) != 'String') { return false }let md = -1let js = -1let mdAt = -1let jsAt = -1let i = 0for (part of h.toLowerCase().split(',')) {let type = part.split(';')[0].trim()if (type == 'text/markdown' && mdAt < 0) {md = qOf(part)mdAt = i}if (type == 'application/json' && jsAt < 0) {js = qOf(part)jsAt = i}i = i + 1}if (md <= 0) { return false }if (js < 0) { return true }return md > js || (md == js && mdAt < jsAt)}static markdownReply = (text) => {return new Response(text, { status = 200 headers = hdr({ 'Content-Type' = 'text/markdown; charset=utf-8' 'Vary' = 'Accept' }) })}// ---- A COMMENT WITH FILES (tickets#27, mission 017): POST …/comments as multipart/form-data -----------------------------// fields: `text` (optional when there are files) and any number of file parts named `file` (or `files`, `file[]`, `files[]`), e.g.// `curl -H "Authorization: Bearer $T" -F 'text=390 px' -F [email protected] …/comments`. Answers { text, files ([{ name, type, bytes }]) }// or { bad } (the answer: 413 for a body over the limit, else 400 naming the field). The limits per file / per comment and the// content check are lib/attachments.hl's (addComment).static fileFields = ['file', 'files', 'file[]', 'files[]']static commentFormOf = (req) => {if (req.bytes != null && hlTypeName(req.bytes) == 'Bytes' && req.bytes.length > maxCommentBytes + 1048576) {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' }) }}p = partsOf(req)if (p.error != null) { return { bad = refuse({ error = p.error field = '' }) } }let text = nullfiles = []for (part of p.parts) {if (part.name == 'author') { return { bad = refuse({ error = "no field 'author' any more: the author is the user of your API token" field = 'author' }) } }if (fileFields.includes(part.name) && part.filename != null) {files.push({ name = part.filename type = part.type bytes = part.bytes })} else if (part.name == 'text' && part.filename == null) {if (text != null) { return { bad = refuse({ error = "field 'text' is given twice" field = 'text' }) } }if (!isUtf8(part.bytes)) { return { bad = refuse({ error = "field 'text' is not UTF-8" field = 'text' }) } }text = part.bytes.toString()} else {return { bad = refuse({ error = "unknown field '" + part.name + "' (allowed: text, and files as file=@path)" field = part.name }) }}}if (files.length > maxFiles) { return { bad = refuse({ error = 'at most ' + maxFiles + ' files per comment (' + files.length + ' given)' field = 'files' }) } }return { text = text != null ? text : '' files = files }}// ---- answers that are not JSON ---------------------------------------------------------------------// an attachment's bytes (tickets#27): a picture inline, any other file as a download; its type is the one its CONTENT showed// (lib/attachments.hl); nosniff + a sandbox policy, so nothing in it can run; private to the browser that fetched itstatic fileReply = (f) => {disp = (f.image ? 'inline' : 'attachment') + '; filename=' + DQ + asciiName(f.name) + DQ + "; filename*=UTF-8''" + encodeURIComponent(f.name)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' } })}static DQ = '"'// a name for the plain `filename=` (ASCII only; the exact one rides in filename*)static asciiName = (name) => {let out = ''let i = 0while (i < name.length) {let c = name.slice(i, i + 1)let k = c.charCodeAt(0)out = out + (k >= 32 && k < 127 && c != '"' ? c : '_')i = i + 1}return out}// a small HTML page (the login callback, /connect): a title and one messagestatic htmlPage = (status, title, text) => {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('&', '&').replaceAll('<', '<').replaceAll('>', '>') + '</p><p><a id="home" href="/">back to the tickets</a></p></main></body></html>'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'" }) })}// a page that moved for good (301) / a page that names nothing (404), as plain textstatic moved = (to) => {return new Response('moved to ' + to, { status = 301 headers = hdr({ 'Location' = to 'Content-Type' = 'text/plain; charset=utf-8' }) })}static missing = (message) => { return new Response(message, { status = 404 headers = hdr({ 'Content-Type' = 'text/plain; charset=utf-8' }) }) }
Branches
Latest commits
- 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
- 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
- 31736a80gate: member-name check fails on the old row layout toomre
- e03ae537gate: the phone checks run on without the Show more button (so old code reports every failed check)mre
- adf7f132gate: 390 px checks for the mobile audit fixes (row number, filters, field widths, Edit, member names, relation taps, paging)mre
- 28e9c938ticket list: draw the newest 50 rows and a Show more button (500 rows were a 2-4 s first paint, 740 KB, a 90 000 px phone page)mre
- ccebb0c7mobile: ticket number stays on one line, filter chips one scrolling row, fields full width under their caption, Edit/action buttons, member names whole, 44 px relation linksmre
- f2dc7741gate: the phone toolbar is two even rows (E2)mre
- 20f7c33async components.hybriel 214c318: MdEditor on a phone, two even toolbar rows of 44 px targets, label 15 px, table head 16 px (E2)mre
- d74a5482sync components.hybriel 134b4e3: MdEditor builds an editor put into the page at once, redraws a surface put in anew (F5, hybriel#211)mre
- 9d02c540sync components.hybriel 6b0936a: the 'edited' foldable drops the theme's border and marginmre